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
MoonieNFT
contracts/ethereum/MoonieNFT.sol
0x744418761efbd3e7239d76e429d6df7f18fca590
Solidity
MoonieNFT
contract MoonieNFT is IERC721Mintable, ERC721Burnable, ERC721Enumerable, ERC721URIStorage, AccessControlMixin, NativeMetaTransaction, ContextMixin, FxBaseRootTunnel { // STATE CONSTANTS bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); // EVENTS event TransferToPolygon(address indexed owner, uint256 indexed tokenId); event ReceivedFromPolygon(address indexed owner, uint256 indexed tokenId); event Burned(uint256 indexed tokenId); // CONSTRUCTOR constructor( string memory name_, string memory symbol_, address checkpointManager, address fxRoot ) ERC721(name_, symbol_) FxBaseRootTunnel(checkpointManager, fxRoot) { _setupContractId("MoonieNFT"); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _initializeEIP712(name_); } // VIEWS function tokenURI(uint256 tokenId) public view virtual override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, AccessControl, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } // EXTERNAL FUNCTIONS /** * @dev See {IMintableERC721-mint}. * * If you're attempting to bring metadata associated with token * from L2 to L1, you must implement this method */ function mint(address user, uint256 tokenId, string memory tokenUri) external override only(MINTER_ROLE) { _mint(user, tokenId); _setTokenURI(tokenId, tokenUri); } function exists(uint256 tokenId) external view override returns (bool) { return _exists(tokenId); } function transferToPolygon(uint256 tokenId) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "MoonieNFT: caller is not owner nor approved"); _sendMessageToChild(abi.encode(_msgSender(), tokenId, _stripBaseURI(tokenId))); _burn(tokenId); emit TransferToPolygon(_msgSender(), tokenId); } // INTERNAL FUNCTIONS function _burn(uint256 tokenId) internal virtual override(ERC721, ERC721URIStorage) { emit Burned(tokenId); super._burn(tokenId); } // This is to support Native meta transactions // never use msg.sender directly, use _msgSender() instead function _msgSender() internal override view returns (address) { return ContextMixin.msgSender(); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function _baseURI() internal view virtual override returns (string memory) { return "ipfs://"; } function _stripBaseURI(uint256 tokenId) internal view returns (string memory) { bytes memory uri = bytes(tokenURI(tokenId)); uint256 uriLength = uri.length; bytes memory strippedUri = new bytes(uriLength - 7); for (uint256 i = 7; i < uriLength; i++) { strippedUri[i - 7] = uri[i]; } return string(strippedUri); } function _processMessageFromChild(bytes memory message) virtual internal override { (address owner, uint256 tokenId, string memory tokenUri) = abi.decode(message, (address, uint256, string)); _mint(owner, tokenId); _setTokenURI(tokenId, tokenUri); emit ReceivedFromPolygon(owner, tokenId); } }
tokenURI
function tokenURI(uint256 tokenId) public view virtual override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); }
// VIEWS
LineComment
v0.8.4+commit.c7e474f2
MIT
ipfs://e272d0561e5d257fa285f8fe8be939eea21aea62940820517462c2d69edbff82
{ "func_code_index": [ 922, 1090 ] }
8,407
MoonieNFT
contracts/ethereum/MoonieNFT.sol
0x744418761efbd3e7239d76e429d6df7f18fca590
Solidity
MoonieNFT
contract MoonieNFT is IERC721Mintable, ERC721Burnable, ERC721Enumerable, ERC721URIStorage, AccessControlMixin, NativeMetaTransaction, ContextMixin, FxBaseRootTunnel { // STATE CONSTANTS bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); // EVENTS event TransferToPolygon(address indexed owner, uint256 indexed tokenId); event ReceivedFromPolygon(address indexed owner, uint256 indexed tokenId); event Burned(uint256 indexed tokenId); // CONSTRUCTOR constructor( string memory name_, string memory symbol_, address checkpointManager, address fxRoot ) ERC721(name_, symbol_) FxBaseRootTunnel(checkpointManager, fxRoot) { _setupContractId("MoonieNFT"); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _initializeEIP712(name_); } // VIEWS function tokenURI(uint256 tokenId) public view virtual override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, AccessControl, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } // EXTERNAL FUNCTIONS /** * @dev See {IMintableERC721-mint}. * * If you're attempting to bring metadata associated with token * from L2 to L1, you must implement this method */ function mint(address user, uint256 tokenId, string memory tokenUri) external override only(MINTER_ROLE) { _mint(user, tokenId); _setTokenURI(tokenId, tokenUri); } function exists(uint256 tokenId) external view override returns (bool) { return _exists(tokenId); } function transferToPolygon(uint256 tokenId) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "MoonieNFT: caller is not owner nor approved"); _sendMessageToChild(abi.encode(_msgSender(), tokenId, _stripBaseURI(tokenId))); _burn(tokenId); emit TransferToPolygon(_msgSender(), tokenId); } // INTERNAL FUNCTIONS function _burn(uint256 tokenId) internal virtual override(ERC721, ERC721URIStorage) { emit Burned(tokenId); super._burn(tokenId); } // This is to support Native meta transactions // never use msg.sender directly, use _msgSender() instead function _msgSender() internal override view returns (address) { return ContextMixin.msgSender(); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function _baseURI() internal view virtual override returns (string memory) { return "ipfs://"; } function _stripBaseURI(uint256 tokenId) internal view returns (string memory) { bytes memory uri = bytes(tokenURI(tokenId)); uint256 uriLength = uri.length; bytes memory strippedUri = new bytes(uriLength - 7); for (uint256 i = 7; i < uriLength; i++) { strippedUri[i - 7] = uri[i]; } return string(strippedUri); } function _processMessageFromChild(bytes memory message) virtual internal override { (address owner, uint256 tokenId, string memory tokenUri) = abi.decode(message, (address, uint256, string)); _mint(owner, tokenId); _setTokenURI(tokenId, tokenUri); emit ReceivedFromPolygon(owner, tokenId); } }
mint
function mint(address user, uint256 tokenId, string memory tokenUri) external override only(MINTER_ROLE) { _mint(user, tokenId); _setTokenURI(tokenId, tokenUri); }
/** * @dev See {IMintableERC721-mint}. * * If you're attempting to bring metadata associated with token * from L2 to L1, you must implement this method */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
MIT
ipfs://e272d0561e5d257fa285f8fe8be939eea21aea62940820517462c2d69edbff82
{ "func_code_index": [ 1573, 1764 ] }
8,408
MoonieNFT
contracts/ethereum/MoonieNFT.sol
0x744418761efbd3e7239d76e429d6df7f18fca590
Solidity
MoonieNFT
contract MoonieNFT is IERC721Mintable, ERC721Burnable, ERC721Enumerable, ERC721URIStorage, AccessControlMixin, NativeMetaTransaction, ContextMixin, FxBaseRootTunnel { // STATE CONSTANTS bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); // EVENTS event TransferToPolygon(address indexed owner, uint256 indexed tokenId); event ReceivedFromPolygon(address indexed owner, uint256 indexed tokenId); event Burned(uint256 indexed tokenId); // CONSTRUCTOR constructor( string memory name_, string memory symbol_, address checkpointManager, address fxRoot ) ERC721(name_, symbol_) FxBaseRootTunnel(checkpointManager, fxRoot) { _setupContractId("MoonieNFT"); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _initializeEIP712(name_); } // VIEWS function tokenURI(uint256 tokenId) public view virtual override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, AccessControl, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } // EXTERNAL FUNCTIONS /** * @dev See {IMintableERC721-mint}. * * If you're attempting to bring metadata associated with token * from L2 to L1, you must implement this method */ function mint(address user, uint256 tokenId, string memory tokenUri) external override only(MINTER_ROLE) { _mint(user, tokenId); _setTokenURI(tokenId, tokenUri); } function exists(uint256 tokenId) external view override returns (bool) { return _exists(tokenId); } function transferToPolygon(uint256 tokenId) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "MoonieNFT: caller is not owner nor approved"); _sendMessageToChild(abi.encode(_msgSender(), tokenId, _stripBaseURI(tokenId))); _burn(tokenId); emit TransferToPolygon(_msgSender(), tokenId); } // INTERNAL FUNCTIONS function _burn(uint256 tokenId) internal virtual override(ERC721, ERC721URIStorage) { emit Burned(tokenId); super._burn(tokenId); } // This is to support Native meta transactions // never use msg.sender directly, use _msgSender() instead function _msgSender() internal override view returns (address) { return ContextMixin.msgSender(); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function _baseURI() internal view virtual override returns (string memory) { return "ipfs://"; } function _stripBaseURI(uint256 tokenId) internal view returns (string memory) { bytes memory uri = bytes(tokenURI(tokenId)); uint256 uriLength = uri.length; bytes memory strippedUri = new bytes(uriLength - 7); for (uint256 i = 7; i < uriLength; i++) { strippedUri[i - 7] = uri[i]; } return string(strippedUri); } function _processMessageFromChild(bytes memory message) virtual internal override { (address owner, uint256 tokenId, string memory tokenUri) = abi.decode(message, (address, uint256, string)); _mint(owner, tokenId); _setTokenURI(tokenId, tokenUri); emit ReceivedFromPolygon(owner, tokenId); } }
_burn
function _burn(uint256 tokenId) internal virtual override(ERC721, ERC721URIStorage) { emit Burned(tokenId); super._burn(tokenId); }
// INTERNAL FUNCTIONS
LineComment
v0.8.4+commit.c7e474f2
MIT
ipfs://e272d0561e5d257fa285f8fe8be939eea21aea62940820517462c2d69edbff82
{ "func_code_index": [ 2264, 2423 ] }
8,409
MoonieNFT
contracts/ethereum/MoonieNFT.sol
0x744418761efbd3e7239d76e429d6df7f18fca590
Solidity
MoonieNFT
contract MoonieNFT is IERC721Mintable, ERC721Burnable, ERC721Enumerable, ERC721URIStorage, AccessControlMixin, NativeMetaTransaction, ContextMixin, FxBaseRootTunnel { // STATE CONSTANTS bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); // EVENTS event TransferToPolygon(address indexed owner, uint256 indexed tokenId); event ReceivedFromPolygon(address indexed owner, uint256 indexed tokenId); event Burned(uint256 indexed tokenId); // CONSTRUCTOR constructor( string memory name_, string memory symbol_, address checkpointManager, address fxRoot ) ERC721(name_, symbol_) FxBaseRootTunnel(checkpointManager, fxRoot) { _setupContractId("MoonieNFT"); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _initializeEIP712(name_); } // VIEWS function tokenURI(uint256 tokenId) public view virtual override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, AccessControl, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } // EXTERNAL FUNCTIONS /** * @dev See {IMintableERC721-mint}. * * If you're attempting to bring metadata associated with token * from L2 to L1, you must implement this method */ function mint(address user, uint256 tokenId, string memory tokenUri) external override only(MINTER_ROLE) { _mint(user, tokenId); _setTokenURI(tokenId, tokenUri); } function exists(uint256 tokenId) external view override returns (bool) { return _exists(tokenId); } function transferToPolygon(uint256 tokenId) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "MoonieNFT: caller is not owner nor approved"); _sendMessageToChild(abi.encode(_msgSender(), tokenId, _stripBaseURI(tokenId))); _burn(tokenId); emit TransferToPolygon(_msgSender(), tokenId); } // INTERNAL FUNCTIONS function _burn(uint256 tokenId) internal virtual override(ERC721, ERC721URIStorage) { emit Burned(tokenId); super._burn(tokenId); } // This is to support Native meta transactions // never use msg.sender directly, use _msgSender() instead function _msgSender() internal override view returns (address) { return ContextMixin.msgSender(); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function _baseURI() internal view virtual override returns (string memory) { return "ipfs://"; } function _stripBaseURI(uint256 tokenId) internal view returns (string memory) { bytes memory uri = bytes(tokenURI(tokenId)); uint256 uriLength = uri.length; bytes memory strippedUri = new bytes(uriLength - 7); for (uint256 i = 7; i < uriLength; i++) { strippedUri[i - 7] = uri[i]; } return string(strippedUri); } function _processMessageFromChild(bytes memory message) virtual internal override { (address owner, uint256 tokenId, string memory tokenUri) = abi.decode(message, (address, uint256, string)); _mint(owner, tokenId); _setTokenURI(tokenId, tokenUri); emit ReceivedFromPolygon(owner, tokenId); } }
_msgSender
function _msgSender() internal override view returns (address) { return ContextMixin.msgSender(); }
// This is to support Native meta transactions // never use msg.sender directly, use _msgSender() instead
LineComment
v0.8.4+commit.c7e474f2
MIT
ipfs://e272d0561e5d257fa285f8fe8be939eea21aea62940820517462c2d69edbff82
{ "func_code_index": [ 2542, 2701 ] }
8,410
CyberFrogz
contracts/CyberFrogz.sol
0xdccc916bf4a0186065f4d1e5b94176f4d17b8c42
Solidity
CyberFrogz
contract CyberFrogz is ERC721, EIP712, Ownable { using Counters for Counters.Counter; using Strings for uint256; enum SaleStatus { PAUSED, PRESALE, PUBLIC } Counters.Counter private _tokenIds; uint public constant COLLECTION_SIZE = 5555; uint public constant MINT_PRICE = 0.1 ether; uint public constant PRESALE_MINT_PRICE = 0.1 ether; SaleStatus public saleStatus = SaleStatus.PAUSED; bool public canReveal = false; string private _placeholderUri; string private _baseUri; address private immutable _txSigner; mapping(address => uint) private _mintedCount; mapping(address => uint) private _whitelistMintedCount; constructor(string memory placeholderUri, address txSigner) ERC721("CyberFrogz", "CF") EIP712("CyberFrogz", "1") { _placeholderUri = placeholderUri; _txSigner = txSigner; } /// @notice Represents an un-minted NFT, which has not yet been recorded into the blockchain. A signed voucher can be redeemed for a real NFT using the redeem function. struct NFTVoucher { address redeemer; bool whitelisted; uint256 numberOfTokens; } function totalSupply() external view returns (uint) { return _tokenIds.current(); } /// @dev override base uri. It will be combined with token ID function _baseURI() internal view override returns (string memory) { return _baseUri; } function airdrop(address to, uint count) external onlyOwner { require(_tokenIds.current() + count <= COLLECTION_SIZE, "Exceeds collection size"); _mintTokens(to, count); } /// @notice Set hidden metadata uri function setHiddenUri(string memory uri) external onlyOwner { _placeholderUri = uri; } /// @notice Set sales status function setSaleStatus(SaleStatus status) external onlyOwner { saleStatus = status; } /// @notice Reveal metadata for all the tokens function reveal(string memory baseUri) external onlyOwner { require(!canReveal, "Already revealed"); _baseUri = baseUri; canReveal = true; } /// @notice Get token's URI. In case of delayed reveal we give user the json of the placeholer metadata. /// @param tokenId token ID function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return canReveal ? string(abi.encodePacked(_baseURI(), tokenId.toString(), ".json")) : _placeholderUri; } /// @notice Withdraw's contract's balance to the minter's address function withdraw() external onlyOwner { uint256 balance = address(this).balance; require(balance > 0, "No balance"); payable(owner()).transfer(balance); } /// @notice Redeems an NFTVoucher for an actual NFT, creating it in the process. /// @param voucher An NFTVoucher that describes the NFT to be redeemed. /// @param signature An EIP712 signature of the voucher, produced by the NFT creator. function redeem(NFTVoucher calldata voucher, bytes memory signature) external payable { require(_verify(_hash(voucher), signature), "Transaction is not authorized (invalid signature)"); require(saleStatus != SaleStatus.PAUSED, "Sales are off"); require(_tokenIds.current() != COLLECTION_SIZE, "All tokens have been minted"); require(_tokenIds.current() + voucher.numberOfTokens <= COLLECTION_SIZE, "Number of requested tokens will exceed collection size"); if(saleStatus == SaleStatus.PRESALE) { require(voucher.whitelisted, "Presale is only open to whitelisted users"); require(msg.value >= voucher.numberOfTokens * PRESALE_MINT_PRICE, "Ether value sent is not sufficient"); require(_whitelistMintedCount[voucher.redeemer] + voucher.numberOfTokens <= 2, "You've already minted all tokens available to you"); _whitelistMintedCount[voucher.redeemer] += voucher.numberOfTokens; } else { require(msg.value >= voucher.numberOfTokens * MINT_PRICE, "Ether value sent is not sufficient"); require(_mintedCount[voucher.redeemer] == 0, "You've already minted all tokens available to you"); _mintedCount[voucher.redeemer] += voucher.numberOfTokens; } _mintTokens(voucher.redeemer, voucher.numberOfTokens); } /// @dev perform actual minting of the tokens function _mintTokens(address to, uint count) internal { for(uint index = 0; index < count; index++) { _tokenIds.increment(); uint newItemId = _tokenIds.current(); _safeMint(to, newItemId); } } /// @notice Returns a hash of the given NFTVoucher, prepared using EIP712 typed data hashing rules. /// @param voucher An NFTVoucher to hash. function _hash(NFTVoucher calldata voucher) internal view returns (bytes32) { return _hashTypedDataV4(keccak256(abi.encode( keccak256("NFTVoucher(address redeemer,bool whitelisted,uint256 numberOfTokens)"), voucher.redeemer, voucher.whitelisted, voucher.numberOfTokens ))); } function _verify(bytes32 digest, bytes memory signature) internal view returns (bool) { return SignatureChecker.isValidSignatureNow(_txSigner, digest, signature); } }
_baseURI
function _baseURI() internal view override returns (string memory) { return _baseUri; }
/// @dev override base uri. It will be combined with token ID
NatSpecSingleLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 1394, 1500 ] }
8,411
CyberFrogz
contracts/CyberFrogz.sol
0xdccc916bf4a0186065f4d1e5b94176f4d17b8c42
Solidity
CyberFrogz
contract CyberFrogz is ERC721, EIP712, Ownable { using Counters for Counters.Counter; using Strings for uint256; enum SaleStatus { PAUSED, PRESALE, PUBLIC } Counters.Counter private _tokenIds; uint public constant COLLECTION_SIZE = 5555; uint public constant MINT_PRICE = 0.1 ether; uint public constant PRESALE_MINT_PRICE = 0.1 ether; SaleStatus public saleStatus = SaleStatus.PAUSED; bool public canReveal = false; string private _placeholderUri; string private _baseUri; address private immutable _txSigner; mapping(address => uint) private _mintedCount; mapping(address => uint) private _whitelistMintedCount; constructor(string memory placeholderUri, address txSigner) ERC721("CyberFrogz", "CF") EIP712("CyberFrogz", "1") { _placeholderUri = placeholderUri; _txSigner = txSigner; } /// @notice Represents an un-minted NFT, which has not yet been recorded into the blockchain. A signed voucher can be redeemed for a real NFT using the redeem function. struct NFTVoucher { address redeemer; bool whitelisted; uint256 numberOfTokens; } function totalSupply() external view returns (uint) { return _tokenIds.current(); } /// @dev override base uri. It will be combined with token ID function _baseURI() internal view override returns (string memory) { return _baseUri; } function airdrop(address to, uint count) external onlyOwner { require(_tokenIds.current() + count <= COLLECTION_SIZE, "Exceeds collection size"); _mintTokens(to, count); } /// @notice Set hidden metadata uri function setHiddenUri(string memory uri) external onlyOwner { _placeholderUri = uri; } /// @notice Set sales status function setSaleStatus(SaleStatus status) external onlyOwner { saleStatus = status; } /// @notice Reveal metadata for all the tokens function reveal(string memory baseUri) external onlyOwner { require(!canReveal, "Already revealed"); _baseUri = baseUri; canReveal = true; } /// @notice Get token's URI. In case of delayed reveal we give user the json of the placeholer metadata. /// @param tokenId token ID function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return canReveal ? string(abi.encodePacked(_baseURI(), tokenId.toString(), ".json")) : _placeholderUri; } /// @notice Withdraw's contract's balance to the minter's address function withdraw() external onlyOwner { uint256 balance = address(this).balance; require(balance > 0, "No balance"); payable(owner()).transfer(balance); } /// @notice Redeems an NFTVoucher for an actual NFT, creating it in the process. /// @param voucher An NFTVoucher that describes the NFT to be redeemed. /// @param signature An EIP712 signature of the voucher, produced by the NFT creator. function redeem(NFTVoucher calldata voucher, bytes memory signature) external payable { require(_verify(_hash(voucher), signature), "Transaction is not authorized (invalid signature)"); require(saleStatus != SaleStatus.PAUSED, "Sales are off"); require(_tokenIds.current() != COLLECTION_SIZE, "All tokens have been minted"); require(_tokenIds.current() + voucher.numberOfTokens <= COLLECTION_SIZE, "Number of requested tokens will exceed collection size"); if(saleStatus == SaleStatus.PRESALE) { require(voucher.whitelisted, "Presale is only open to whitelisted users"); require(msg.value >= voucher.numberOfTokens * PRESALE_MINT_PRICE, "Ether value sent is not sufficient"); require(_whitelistMintedCount[voucher.redeemer] + voucher.numberOfTokens <= 2, "You've already minted all tokens available to you"); _whitelistMintedCount[voucher.redeemer] += voucher.numberOfTokens; } else { require(msg.value >= voucher.numberOfTokens * MINT_PRICE, "Ether value sent is not sufficient"); require(_mintedCount[voucher.redeemer] == 0, "You've already minted all tokens available to you"); _mintedCount[voucher.redeemer] += voucher.numberOfTokens; } _mintTokens(voucher.redeemer, voucher.numberOfTokens); } /// @dev perform actual minting of the tokens function _mintTokens(address to, uint count) internal { for(uint index = 0; index < count; index++) { _tokenIds.increment(); uint newItemId = _tokenIds.current(); _safeMint(to, newItemId); } } /// @notice Returns a hash of the given NFTVoucher, prepared using EIP712 typed data hashing rules. /// @param voucher An NFTVoucher to hash. function _hash(NFTVoucher calldata voucher) internal view returns (bytes32) { return _hashTypedDataV4(keccak256(abi.encode( keccak256("NFTVoucher(address redeemer,bool whitelisted,uint256 numberOfTokens)"), voucher.redeemer, voucher.whitelisted, voucher.numberOfTokens ))); } function _verify(bytes32 digest, bytes memory signature) internal view returns (bool) { return SignatureChecker.isValidSignatureNow(_txSigner, digest, signature); } }
setHiddenUri
function setHiddenUri(string memory uri) external onlyOwner { _placeholderUri = uri; }
/// @notice Set hidden metadata uri
NatSpecSingleLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 1746, 1851 ] }
8,412
CyberFrogz
contracts/CyberFrogz.sol
0xdccc916bf4a0186065f4d1e5b94176f4d17b8c42
Solidity
CyberFrogz
contract CyberFrogz is ERC721, EIP712, Ownable { using Counters for Counters.Counter; using Strings for uint256; enum SaleStatus { PAUSED, PRESALE, PUBLIC } Counters.Counter private _tokenIds; uint public constant COLLECTION_SIZE = 5555; uint public constant MINT_PRICE = 0.1 ether; uint public constant PRESALE_MINT_PRICE = 0.1 ether; SaleStatus public saleStatus = SaleStatus.PAUSED; bool public canReveal = false; string private _placeholderUri; string private _baseUri; address private immutable _txSigner; mapping(address => uint) private _mintedCount; mapping(address => uint) private _whitelistMintedCount; constructor(string memory placeholderUri, address txSigner) ERC721("CyberFrogz", "CF") EIP712("CyberFrogz", "1") { _placeholderUri = placeholderUri; _txSigner = txSigner; } /// @notice Represents an un-minted NFT, which has not yet been recorded into the blockchain. A signed voucher can be redeemed for a real NFT using the redeem function. struct NFTVoucher { address redeemer; bool whitelisted; uint256 numberOfTokens; } function totalSupply() external view returns (uint) { return _tokenIds.current(); } /// @dev override base uri. It will be combined with token ID function _baseURI() internal view override returns (string memory) { return _baseUri; } function airdrop(address to, uint count) external onlyOwner { require(_tokenIds.current() + count <= COLLECTION_SIZE, "Exceeds collection size"); _mintTokens(to, count); } /// @notice Set hidden metadata uri function setHiddenUri(string memory uri) external onlyOwner { _placeholderUri = uri; } /// @notice Set sales status function setSaleStatus(SaleStatus status) external onlyOwner { saleStatus = status; } /// @notice Reveal metadata for all the tokens function reveal(string memory baseUri) external onlyOwner { require(!canReveal, "Already revealed"); _baseUri = baseUri; canReveal = true; } /// @notice Get token's URI. In case of delayed reveal we give user the json of the placeholer metadata. /// @param tokenId token ID function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return canReveal ? string(abi.encodePacked(_baseURI(), tokenId.toString(), ".json")) : _placeholderUri; } /// @notice Withdraw's contract's balance to the minter's address function withdraw() external onlyOwner { uint256 balance = address(this).balance; require(balance > 0, "No balance"); payable(owner()).transfer(balance); } /// @notice Redeems an NFTVoucher for an actual NFT, creating it in the process. /// @param voucher An NFTVoucher that describes the NFT to be redeemed. /// @param signature An EIP712 signature of the voucher, produced by the NFT creator. function redeem(NFTVoucher calldata voucher, bytes memory signature) external payable { require(_verify(_hash(voucher), signature), "Transaction is not authorized (invalid signature)"); require(saleStatus != SaleStatus.PAUSED, "Sales are off"); require(_tokenIds.current() != COLLECTION_SIZE, "All tokens have been minted"); require(_tokenIds.current() + voucher.numberOfTokens <= COLLECTION_SIZE, "Number of requested tokens will exceed collection size"); if(saleStatus == SaleStatus.PRESALE) { require(voucher.whitelisted, "Presale is only open to whitelisted users"); require(msg.value >= voucher.numberOfTokens * PRESALE_MINT_PRICE, "Ether value sent is not sufficient"); require(_whitelistMintedCount[voucher.redeemer] + voucher.numberOfTokens <= 2, "You've already minted all tokens available to you"); _whitelistMintedCount[voucher.redeemer] += voucher.numberOfTokens; } else { require(msg.value >= voucher.numberOfTokens * MINT_PRICE, "Ether value sent is not sufficient"); require(_mintedCount[voucher.redeemer] == 0, "You've already minted all tokens available to you"); _mintedCount[voucher.redeemer] += voucher.numberOfTokens; } _mintTokens(voucher.redeemer, voucher.numberOfTokens); } /// @dev perform actual minting of the tokens function _mintTokens(address to, uint count) internal { for(uint index = 0; index < count; index++) { _tokenIds.increment(); uint newItemId = _tokenIds.current(); _safeMint(to, newItemId); } } /// @notice Returns a hash of the given NFTVoucher, prepared using EIP712 typed data hashing rules. /// @param voucher An NFTVoucher to hash. function _hash(NFTVoucher calldata voucher) internal view returns (bytes32) { return _hashTypedDataV4(keccak256(abi.encode( keccak256("NFTVoucher(address redeemer,bool whitelisted,uint256 numberOfTokens)"), voucher.redeemer, voucher.whitelisted, voucher.numberOfTokens ))); } function _verify(bytes32 digest, bytes memory signature) internal view returns (bool) { return SignatureChecker.isValidSignatureNow(_txSigner, digest, signature); } }
setSaleStatus
function setSaleStatus(SaleStatus status) external onlyOwner { saleStatus = status; }
/// @notice Set sales status
NatSpecSingleLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 1888, 1980 ] }
8,413
CyberFrogz
contracts/CyberFrogz.sol
0xdccc916bf4a0186065f4d1e5b94176f4d17b8c42
Solidity
CyberFrogz
contract CyberFrogz is ERC721, EIP712, Ownable { using Counters for Counters.Counter; using Strings for uint256; enum SaleStatus { PAUSED, PRESALE, PUBLIC } Counters.Counter private _tokenIds; uint public constant COLLECTION_SIZE = 5555; uint public constant MINT_PRICE = 0.1 ether; uint public constant PRESALE_MINT_PRICE = 0.1 ether; SaleStatus public saleStatus = SaleStatus.PAUSED; bool public canReveal = false; string private _placeholderUri; string private _baseUri; address private immutable _txSigner; mapping(address => uint) private _mintedCount; mapping(address => uint) private _whitelistMintedCount; constructor(string memory placeholderUri, address txSigner) ERC721("CyberFrogz", "CF") EIP712("CyberFrogz", "1") { _placeholderUri = placeholderUri; _txSigner = txSigner; } /// @notice Represents an un-minted NFT, which has not yet been recorded into the blockchain. A signed voucher can be redeemed for a real NFT using the redeem function. struct NFTVoucher { address redeemer; bool whitelisted; uint256 numberOfTokens; } function totalSupply() external view returns (uint) { return _tokenIds.current(); } /// @dev override base uri. It will be combined with token ID function _baseURI() internal view override returns (string memory) { return _baseUri; } function airdrop(address to, uint count) external onlyOwner { require(_tokenIds.current() + count <= COLLECTION_SIZE, "Exceeds collection size"); _mintTokens(to, count); } /// @notice Set hidden metadata uri function setHiddenUri(string memory uri) external onlyOwner { _placeholderUri = uri; } /// @notice Set sales status function setSaleStatus(SaleStatus status) external onlyOwner { saleStatus = status; } /// @notice Reveal metadata for all the tokens function reveal(string memory baseUri) external onlyOwner { require(!canReveal, "Already revealed"); _baseUri = baseUri; canReveal = true; } /// @notice Get token's URI. In case of delayed reveal we give user the json of the placeholer metadata. /// @param tokenId token ID function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return canReveal ? string(abi.encodePacked(_baseURI(), tokenId.toString(), ".json")) : _placeholderUri; } /// @notice Withdraw's contract's balance to the minter's address function withdraw() external onlyOwner { uint256 balance = address(this).balance; require(balance > 0, "No balance"); payable(owner()).transfer(balance); } /// @notice Redeems an NFTVoucher for an actual NFT, creating it in the process. /// @param voucher An NFTVoucher that describes the NFT to be redeemed. /// @param signature An EIP712 signature of the voucher, produced by the NFT creator. function redeem(NFTVoucher calldata voucher, bytes memory signature) external payable { require(_verify(_hash(voucher), signature), "Transaction is not authorized (invalid signature)"); require(saleStatus != SaleStatus.PAUSED, "Sales are off"); require(_tokenIds.current() != COLLECTION_SIZE, "All tokens have been minted"); require(_tokenIds.current() + voucher.numberOfTokens <= COLLECTION_SIZE, "Number of requested tokens will exceed collection size"); if(saleStatus == SaleStatus.PRESALE) { require(voucher.whitelisted, "Presale is only open to whitelisted users"); require(msg.value >= voucher.numberOfTokens * PRESALE_MINT_PRICE, "Ether value sent is not sufficient"); require(_whitelistMintedCount[voucher.redeemer] + voucher.numberOfTokens <= 2, "You've already minted all tokens available to you"); _whitelistMintedCount[voucher.redeemer] += voucher.numberOfTokens; } else { require(msg.value >= voucher.numberOfTokens * MINT_PRICE, "Ether value sent is not sufficient"); require(_mintedCount[voucher.redeemer] == 0, "You've already minted all tokens available to you"); _mintedCount[voucher.redeemer] += voucher.numberOfTokens; } _mintTokens(voucher.redeemer, voucher.numberOfTokens); } /// @dev perform actual minting of the tokens function _mintTokens(address to, uint count) internal { for(uint index = 0; index < count; index++) { _tokenIds.increment(); uint newItemId = _tokenIds.current(); _safeMint(to, newItemId); } } /// @notice Returns a hash of the given NFTVoucher, prepared using EIP712 typed data hashing rules. /// @param voucher An NFTVoucher to hash. function _hash(NFTVoucher calldata voucher) internal view returns (bytes32) { return _hashTypedDataV4(keccak256(abi.encode( keccak256("NFTVoucher(address redeemer,bool whitelisted,uint256 numberOfTokens)"), voucher.redeemer, voucher.whitelisted, voucher.numberOfTokens ))); } function _verify(bytes32 digest, bytes memory signature) internal view returns (bool) { return SignatureChecker.isValidSignatureNow(_txSigner, digest, signature); } }
reveal
function reveal(string memory baseUri) external onlyOwner { require(!canReveal, "Already revealed"); _baseUri = baseUri; canReveal = true; }
/// @notice Reveal metadata for all the tokens
NatSpecSingleLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 2035, 2212 ] }
8,414
CyberFrogz
contracts/CyberFrogz.sol
0xdccc916bf4a0186065f4d1e5b94176f4d17b8c42
Solidity
CyberFrogz
contract CyberFrogz is ERC721, EIP712, Ownable { using Counters for Counters.Counter; using Strings for uint256; enum SaleStatus { PAUSED, PRESALE, PUBLIC } Counters.Counter private _tokenIds; uint public constant COLLECTION_SIZE = 5555; uint public constant MINT_PRICE = 0.1 ether; uint public constant PRESALE_MINT_PRICE = 0.1 ether; SaleStatus public saleStatus = SaleStatus.PAUSED; bool public canReveal = false; string private _placeholderUri; string private _baseUri; address private immutable _txSigner; mapping(address => uint) private _mintedCount; mapping(address => uint) private _whitelistMintedCount; constructor(string memory placeholderUri, address txSigner) ERC721("CyberFrogz", "CF") EIP712("CyberFrogz", "1") { _placeholderUri = placeholderUri; _txSigner = txSigner; } /// @notice Represents an un-minted NFT, which has not yet been recorded into the blockchain. A signed voucher can be redeemed for a real NFT using the redeem function. struct NFTVoucher { address redeemer; bool whitelisted; uint256 numberOfTokens; } function totalSupply() external view returns (uint) { return _tokenIds.current(); } /// @dev override base uri. It will be combined with token ID function _baseURI() internal view override returns (string memory) { return _baseUri; } function airdrop(address to, uint count) external onlyOwner { require(_tokenIds.current() + count <= COLLECTION_SIZE, "Exceeds collection size"); _mintTokens(to, count); } /// @notice Set hidden metadata uri function setHiddenUri(string memory uri) external onlyOwner { _placeholderUri = uri; } /// @notice Set sales status function setSaleStatus(SaleStatus status) external onlyOwner { saleStatus = status; } /// @notice Reveal metadata for all the tokens function reveal(string memory baseUri) external onlyOwner { require(!canReveal, "Already revealed"); _baseUri = baseUri; canReveal = true; } /// @notice Get token's URI. In case of delayed reveal we give user the json of the placeholer metadata. /// @param tokenId token ID function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return canReveal ? string(abi.encodePacked(_baseURI(), tokenId.toString(), ".json")) : _placeholderUri; } /// @notice Withdraw's contract's balance to the minter's address function withdraw() external onlyOwner { uint256 balance = address(this).balance; require(balance > 0, "No balance"); payable(owner()).transfer(balance); } /// @notice Redeems an NFTVoucher for an actual NFT, creating it in the process. /// @param voucher An NFTVoucher that describes the NFT to be redeemed. /// @param signature An EIP712 signature of the voucher, produced by the NFT creator. function redeem(NFTVoucher calldata voucher, bytes memory signature) external payable { require(_verify(_hash(voucher), signature), "Transaction is not authorized (invalid signature)"); require(saleStatus != SaleStatus.PAUSED, "Sales are off"); require(_tokenIds.current() != COLLECTION_SIZE, "All tokens have been minted"); require(_tokenIds.current() + voucher.numberOfTokens <= COLLECTION_SIZE, "Number of requested tokens will exceed collection size"); if(saleStatus == SaleStatus.PRESALE) { require(voucher.whitelisted, "Presale is only open to whitelisted users"); require(msg.value >= voucher.numberOfTokens * PRESALE_MINT_PRICE, "Ether value sent is not sufficient"); require(_whitelistMintedCount[voucher.redeemer] + voucher.numberOfTokens <= 2, "You've already minted all tokens available to you"); _whitelistMintedCount[voucher.redeemer] += voucher.numberOfTokens; } else { require(msg.value >= voucher.numberOfTokens * MINT_PRICE, "Ether value sent is not sufficient"); require(_mintedCount[voucher.redeemer] == 0, "You've already minted all tokens available to you"); _mintedCount[voucher.redeemer] += voucher.numberOfTokens; } _mintTokens(voucher.redeemer, voucher.numberOfTokens); } /// @dev perform actual minting of the tokens function _mintTokens(address to, uint count) internal { for(uint index = 0; index < count; index++) { _tokenIds.increment(); uint newItemId = _tokenIds.current(); _safeMint(to, newItemId); } } /// @notice Returns a hash of the given NFTVoucher, prepared using EIP712 typed data hashing rules. /// @param voucher An NFTVoucher to hash. function _hash(NFTVoucher calldata voucher) internal view returns (bytes32) { return _hashTypedDataV4(keccak256(abi.encode( keccak256("NFTVoucher(address redeemer,bool whitelisted,uint256 numberOfTokens)"), voucher.redeemer, voucher.whitelisted, voucher.numberOfTokens ))); } function _verify(bytes32 digest, bytes memory signature) internal view returns (bool) { return SignatureChecker.isValidSignatureNow(_txSigner, digest, signature); } }
tokenURI
function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return canReveal ? string(abi.encodePacked(_baseURI(), tokenId.toString(), ".json")) : _placeholderUri; }
/// @notice Get token's URI. In case of delayed reveal we give user the json of the placeholer metadata. /// @param tokenId token ID
NatSpecSingleLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 2358, 2680 ] }
8,415
CyberFrogz
contracts/CyberFrogz.sol
0xdccc916bf4a0186065f4d1e5b94176f4d17b8c42
Solidity
CyberFrogz
contract CyberFrogz is ERC721, EIP712, Ownable { using Counters for Counters.Counter; using Strings for uint256; enum SaleStatus { PAUSED, PRESALE, PUBLIC } Counters.Counter private _tokenIds; uint public constant COLLECTION_SIZE = 5555; uint public constant MINT_PRICE = 0.1 ether; uint public constant PRESALE_MINT_PRICE = 0.1 ether; SaleStatus public saleStatus = SaleStatus.PAUSED; bool public canReveal = false; string private _placeholderUri; string private _baseUri; address private immutable _txSigner; mapping(address => uint) private _mintedCount; mapping(address => uint) private _whitelistMintedCount; constructor(string memory placeholderUri, address txSigner) ERC721("CyberFrogz", "CF") EIP712("CyberFrogz", "1") { _placeholderUri = placeholderUri; _txSigner = txSigner; } /// @notice Represents an un-minted NFT, which has not yet been recorded into the blockchain. A signed voucher can be redeemed for a real NFT using the redeem function. struct NFTVoucher { address redeemer; bool whitelisted; uint256 numberOfTokens; } function totalSupply() external view returns (uint) { return _tokenIds.current(); } /// @dev override base uri. It will be combined with token ID function _baseURI() internal view override returns (string memory) { return _baseUri; } function airdrop(address to, uint count) external onlyOwner { require(_tokenIds.current() + count <= COLLECTION_SIZE, "Exceeds collection size"); _mintTokens(to, count); } /// @notice Set hidden metadata uri function setHiddenUri(string memory uri) external onlyOwner { _placeholderUri = uri; } /// @notice Set sales status function setSaleStatus(SaleStatus status) external onlyOwner { saleStatus = status; } /// @notice Reveal metadata for all the tokens function reveal(string memory baseUri) external onlyOwner { require(!canReveal, "Already revealed"); _baseUri = baseUri; canReveal = true; } /// @notice Get token's URI. In case of delayed reveal we give user the json of the placeholer metadata. /// @param tokenId token ID function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return canReveal ? string(abi.encodePacked(_baseURI(), tokenId.toString(), ".json")) : _placeholderUri; } /// @notice Withdraw's contract's balance to the minter's address function withdraw() external onlyOwner { uint256 balance = address(this).balance; require(balance > 0, "No balance"); payable(owner()).transfer(balance); } /// @notice Redeems an NFTVoucher for an actual NFT, creating it in the process. /// @param voucher An NFTVoucher that describes the NFT to be redeemed. /// @param signature An EIP712 signature of the voucher, produced by the NFT creator. function redeem(NFTVoucher calldata voucher, bytes memory signature) external payable { require(_verify(_hash(voucher), signature), "Transaction is not authorized (invalid signature)"); require(saleStatus != SaleStatus.PAUSED, "Sales are off"); require(_tokenIds.current() != COLLECTION_SIZE, "All tokens have been minted"); require(_tokenIds.current() + voucher.numberOfTokens <= COLLECTION_SIZE, "Number of requested tokens will exceed collection size"); if(saleStatus == SaleStatus.PRESALE) { require(voucher.whitelisted, "Presale is only open to whitelisted users"); require(msg.value >= voucher.numberOfTokens * PRESALE_MINT_PRICE, "Ether value sent is not sufficient"); require(_whitelistMintedCount[voucher.redeemer] + voucher.numberOfTokens <= 2, "You've already minted all tokens available to you"); _whitelistMintedCount[voucher.redeemer] += voucher.numberOfTokens; } else { require(msg.value >= voucher.numberOfTokens * MINT_PRICE, "Ether value sent is not sufficient"); require(_mintedCount[voucher.redeemer] == 0, "You've already minted all tokens available to you"); _mintedCount[voucher.redeemer] += voucher.numberOfTokens; } _mintTokens(voucher.redeemer, voucher.numberOfTokens); } /// @dev perform actual minting of the tokens function _mintTokens(address to, uint count) internal { for(uint index = 0; index < count; index++) { _tokenIds.increment(); uint newItemId = _tokenIds.current(); _safeMint(to, newItemId); } } /// @notice Returns a hash of the given NFTVoucher, prepared using EIP712 typed data hashing rules. /// @param voucher An NFTVoucher to hash. function _hash(NFTVoucher calldata voucher) internal view returns (bytes32) { return _hashTypedDataV4(keccak256(abi.encode( keccak256("NFTVoucher(address redeemer,bool whitelisted,uint256 numberOfTokens)"), voucher.redeemer, voucher.whitelisted, voucher.numberOfTokens ))); } function _verify(bytes32 digest, bytes memory signature) internal view returns (bool) { return SignatureChecker.isValidSignatureNow(_txSigner, digest, signature); } }
withdraw
function withdraw() external onlyOwner { uint256 balance = address(this).balance; require(balance > 0, "No balance"); payable(owner()).transfer(balance); }
/// @notice Withdraw's contract's balance to the minter's address
NatSpecSingleLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 2754, 2948 ] }
8,416
CyberFrogz
contracts/CyberFrogz.sol
0xdccc916bf4a0186065f4d1e5b94176f4d17b8c42
Solidity
CyberFrogz
contract CyberFrogz is ERC721, EIP712, Ownable { using Counters for Counters.Counter; using Strings for uint256; enum SaleStatus { PAUSED, PRESALE, PUBLIC } Counters.Counter private _tokenIds; uint public constant COLLECTION_SIZE = 5555; uint public constant MINT_PRICE = 0.1 ether; uint public constant PRESALE_MINT_PRICE = 0.1 ether; SaleStatus public saleStatus = SaleStatus.PAUSED; bool public canReveal = false; string private _placeholderUri; string private _baseUri; address private immutable _txSigner; mapping(address => uint) private _mintedCount; mapping(address => uint) private _whitelistMintedCount; constructor(string memory placeholderUri, address txSigner) ERC721("CyberFrogz", "CF") EIP712("CyberFrogz", "1") { _placeholderUri = placeholderUri; _txSigner = txSigner; } /// @notice Represents an un-minted NFT, which has not yet been recorded into the blockchain. A signed voucher can be redeemed for a real NFT using the redeem function. struct NFTVoucher { address redeemer; bool whitelisted; uint256 numberOfTokens; } function totalSupply() external view returns (uint) { return _tokenIds.current(); } /// @dev override base uri. It will be combined with token ID function _baseURI() internal view override returns (string memory) { return _baseUri; } function airdrop(address to, uint count) external onlyOwner { require(_tokenIds.current() + count <= COLLECTION_SIZE, "Exceeds collection size"); _mintTokens(to, count); } /// @notice Set hidden metadata uri function setHiddenUri(string memory uri) external onlyOwner { _placeholderUri = uri; } /// @notice Set sales status function setSaleStatus(SaleStatus status) external onlyOwner { saleStatus = status; } /// @notice Reveal metadata for all the tokens function reveal(string memory baseUri) external onlyOwner { require(!canReveal, "Already revealed"); _baseUri = baseUri; canReveal = true; } /// @notice Get token's URI. In case of delayed reveal we give user the json of the placeholer metadata. /// @param tokenId token ID function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return canReveal ? string(abi.encodePacked(_baseURI(), tokenId.toString(), ".json")) : _placeholderUri; } /// @notice Withdraw's contract's balance to the minter's address function withdraw() external onlyOwner { uint256 balance = address(this).balance; require(balance > 0, "No balance"); payable(owner()).transfer(balance); } /// @notice Redeems an NFTVoucher for an actual NFT, creating it in the process. /// @param voucher An NFTVoucher that describes the NFT to be redeemed. /// @param signature An EIP712 signature of the voucher, produced by the NFT creator. function redeem(NFTVoucher calldata voucher, bytes memory signature) external payable { require(_verify(_hash(voucher), signature), "Transaction is not authorized (invalid signature)"); require(saleStatus != SaleStatus.PAUSED, "Sales are off"); require(_tokenIds.current() != COLLECTION_SIZE, "All tokens have been minted"); require(_tokenIds.current() + voucher.numberOfTokens <= COLLECTION_SIZE, "Number of requested tokens will exceed collection size"); if(saleStatus == SaleStatus.PRESALE) { require(voucher.whitelisted, "Presale is only open to whitelisted users"); require(msg.value >= voucher.numberOfTokens * PRESALE_MINT_PRICE, "Ether value sent is not sufficient"); require(_whitelistMintedCount[voucher.redeemer] + voucher.numberOfTokens <= 2, "You've already minted all tokens available to you"); _whitelistMintedCount[voucher.redeemer] += voucher.numberOfTokens; } else { require(msg.value >= voucher.numberOfTokens * MINT_PRICE, "Ether value sent is not sufficient"); require(_mintedCount[voucher.redeemer] == 0, "You've already minted all tokens available to you"); _mintedCount[voucher.redeemer] += voucher.numberOfTokens; } _mintTokens(voucher.redeemer, voucher.numberOfTokens); } /// @dev perform actual minting of the tokens function _mintTokens(address to, uint count) internal { for(uint index = 0; index < count; index++) { _tokenIds.increment(); uint newItemId = _tokenIds.current(); _safeMint(to, newItemId); } } /// @notice Returns a hash of the given NFTVoucher, prepared using EIP712 typed data hashing rules. /// @param voucher An NFTVoucher to hash. function _hash(NFTVoucher calldata voucher) internal view returns (bytes32) { return _hashTypedDataV4(keccak256(abi.encode( keccak256("NFTVoucher(address redeemer,bool whitelisted,uint256 numberOfTokens)"), voucher.redeemer, voucher.whitelisted, voucher.numberOfTokens ))); } function _verify(bytes32 digest, bytes memory signature) internal view returns (bool) { return SignatureChecker.isValidSignatureNow(_txSigner, digest, signature); } }
redeem
function redeem(NFTVoucher calldata voucher, bytes memory signature) external payable { require(_verify(_hash(voucher), signature), "Transaction is not authorized (invalid signature)"); require(saleStatus != SaleStatus.PAUSED, "Sales are off"); require(_tokenIds.current() != COLLECTION_SIZE, "All tokens have been minted"); require(_tokenIds.current() + voucher.numberOfTokens <= COLLECTION_SIZE, "Number of requested tokens will exceed collection size"); if(saleStatus == SaleStatus.PRESALE) { require(voucher.whitelisted, "Presale is only open to whitelisted users"); require(msg.value >= voucher.numberOfTokens * PRESALE_MINT_PRICE, "Ether value sent is not sufficient"); require(_whitelistMintedCount[voucher.redeemer] + voucher.numberOfTokens <= 2, "You've already minted all tokens available to you"); _whitelistMintedCount[voucher.redeemer] += voucher.numberOfTokens; } else { require(msg.value >= voucher.numberOfTokens * MINT_PRICE, "Ether value sent is not sufficient"); require(_mintedCount[voucher.redeemer] == 0, "You've already minted all tokens available to you"); _mintedCount[voucher.redeemer] += voucher.numberOfTokens; } _mintTokens(voucher.redeemer, voucher.numberOfTokens); }
/// @notice Redeems an NFTVoucher for an actual NFT, creating it in the process. /// @param voucher An NFTVoucher that describes the NFT to be redeemed. /// @param signature An EIP712 signature of the voucher, produced by the NFT creator.
NatSpecSingleLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 3205, 4590 ] }
8,417
CyberFrogz
contracts/CyberFrogz.sol
0xdccc916bf4a0186065f4d1e5b94176f4d17b8c42
Solidity
CyberFrogz
contract CyberFrogz is ERC721, EIP712, Ownable { using Counters for Counters.Counter; using Strings for uint256; enum SaleStatus { PAUSED, PRESALE, PUBLIC } Counters.Counter private _tokenIds; uint public constant COLLECTION_SIZE = 5555; uint public constant MINT_PRICE = 0.1 ether; uint public constant PRESALE_MINT_PRICE = 0.1 ether; SaleStatus public saleStatus = SaleStatus.PAUSED; bool public canReveal = false; string private _placeholderUri; string private _baseUri; address private immutable _txSigner; mapping(address => uint) private _mintedCount; mapping(address => uint) private _whitelistMintedCount; constructor(string memory placeholderUri, address txSigner) ERC721("CyberFrogz", "CF") EIP712("CyberFrogz", "1") { _placeholderUri = placeholderUri; _txSigner = txSigner; } /// @notice Represents an un-minted NFT, which has not yet been recorded into the blockchain. A signed voucher can be redeemed for a real NFT using the redeem function. struct NFTVoucher { address redeemer; bool whitelisted; uint256 numberOfTokens; } function totalSupply() external view returns (uint) { return _tokenIds.current(); } /// @dev override base uri. It will be combined with token ID function _baseURI() internal view override returns (string memory) { return _baseUri; } function airdrop(address to, uint count) external onlyOwner { require(_tokenIds.current() + count <= COLLECTION_SIZE, "Exceeds collection size"); _mintTokens(to, count); } /// @notice Set hidden metadata uri function setHiddenUri(string memory uri) external onlyOwner { _placeholderUri = uri; } /// @notice Set sales status function setSaleStatus(SaleStatus status) external onlyOwner { saleStatus = status; } /// @notice Reveal metadata for all the tokens function reveal(string memory baseUri) external onlyOwner { require(!canReveal, "Already revealed"); _baseUri = baseUri; canReveal = true; } /// @notice Get token's URI. In case of delayed reveal we give user the json of the placeholer metadata. /// @param tokenId token ID function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return canReveal ? string(abi.encodePacked(_baseURI(), tokenId.toString(), ".json")) : _placeholderUri; } /// @notice Withdraw's contract's balance to the minter's address function withdraw() external onlyOwner { uint256 balance = address(this).balance; require(balance > 0, "No balance"); payable(owner()).transfer(balance); } /// @notice Redeems an NFTVoucher for an actual NFT, creating it in the process. /// @param voucher An NFTVoucher that describes the NFT to be redeemed. /// @param signature An EIP712 signature of the voucher, produced by the NFT creator. function redeem(NFTVoucher calldata voucher, bytes memory signature) external payable { require(_verify(_hash(voucher), signature), "Transaction is not authorized (invalid signature)"); require(saleStatus != SaleStatus.PAUSED, "Sales are off"); require(_tokenIds.current() != COLLECTION_SIZE, "All tokens have been minted"); require(_tokenIds.current() + voucher.numberOfTokens <= COLLECTION_SIZE, "Number of requested tokens will exceed collection size"); if(saleStatus == SaleStatus.PRESALE) { require(voucher.whitelisted, "Presale is only open to whitelisted users"); require(msg.value >= voucher.numberOfTokens * PRESALE_MINT_PRICE, "Ether value sent is not sufficient"); require(_whitelistMintedCount[voucher.redeemer] + voucher.numberOfTokens <= 2, "You've already minted all tokens available to you"); _whitelistMintedCount[voucher.redeemer] += voucher.numberOfTokens; } else { require(msg.value >= voucher.numberOfTokens * MINT_PRICE, "Ether value sent is not sufficient"); require(_mintedCount[voucher.redeemer] == 0, "You've already minted all tokens available to you"); _mintedCount[voucher.redeemer] += voucher.numberOfTokens; } _mintTokens(voucher.redeemer, voucher.numberOfTokens); } /// @dev perform actual minting of the tokens function _mintTokens(address to, uint count) internal { for(uint index = 0; index < count; index++) { _tokenIds.increment(); uint newItemId = _tokenIds.current(); _safeMint(to, newItemId); } } /// @notice Returns a hash of the given NFTVoucher, prepared using EIP712 typed data hashing rules. /// @param voucher An NFTVoucher to hash. function _hash(NFTVoucher calldata voucher) internal view returns (bytes32) { return _hashTypedDataV4(keccak256(abi.encode( keccak256("NFTVoucher(address redeemer,bool whitelisted,uint256 numberOfTokens)"), voucher.redeemer, voucher.whitelisted, voucher.numberOfTokens ))); } function _verify(bytes32 digest, bytes memory signature) internal view returns (bool) { return SignatureChecker.isValidSignatureNow(_txSigner, digest, signature); } }
_mintTokens
function _mintTokens(address to, uint count) internal { for(uint index = 0; index < count; index++) { _tokenIds.increment(); uint newItemId = _tokenIds.current(); _safeMint(to, newItemId); } }
/// @dev perform actual minting of the tokens
NatSpecSingleLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 4644, 4907 ] }
8,418
CyberFrogz
contracts/CyberFrogz.sol
0xdccc916bf4a0186065f4d1e5b94176f4d17b8c42
Solidity
CyberFrogz
contract CyberFrogz is ERC721, EIP712, Ownable { using Counters for Counters.Counter; using Strings for uint256; enum SaleStatus { PAUSED, PRESALE, PUBLIC } Counters.Counter private _tokenIds; uint public constant COLLECTION_SIZE = 5555; uint public constant MINT_PRICE = 0.1 ether; uint public constant PRESALE_MINT_PRICE = 0.1 ether; SaleStatus public saleStatus = SaleStatus.PAUSED; bool public canReveal = false; string private _placeholderUri; string private _baseUri; address private immutable _txSigner; mapping(address => uint) private _mintedCount; mapping(address => uint) private _whitelistMintedCount; constructor(string memory placeholderUri, address txSigner) ERC721("CyberFrogz", "CF") EIP712("CyberFrogz", "1") { _placeholderUri = placeholderUri; _txSigner = txSigner; } /// @notice Represents an un-minted NFT, which has not yet been recorded into the blockchain. A signed voucher can be redeemed for a real NFT using the redeem function. struct NFTVoucher { address redeemer; bool whitelisted; uint256 numberOfTokens; } function totalSupply() external view returns (uint) { return _tokenIds.current(); } /// @dev override base uri. It will be combined with token ID function _baseURI() internal view override returns (string memory) { return _baseUri; } function airdrop(address to, uint count) external onlyOwner { require(_tokenIds.current() + count <= COLLECTION_SIZE, "Exceeds collection size"); _mintTokens(to, count); } /// @notice Set hidden metadata uri function setHiddenUri(string memory uri) external onlyOwner { _placeholderUri = uri; } /// @notice Set sales status function setSaleStatus(SaleStatus status) external onlyOwner { saleStatus = status; } /// @notice Reveal metadata for all the tokens function reveal(string memory baseUri) external onlyOwner { require(!canReveal, "Already revealed"); _baseUri = baseUri; canReveal = true; } /// @notice Get token's URI. In case of delayed reveal we give user the json of the placeholer metadata. /// @param tokenId token ID function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return canReveal ? string(abi.encodePacked(_baseURI(), tokenId.toString(), ".json")) : _placeholderUri; } /// @notice Withdraw's contract's balance to the minter's address function withdraw() external onlyOwner { uint256 balance = address(this).balance; require(balance > 0, "No balance"); payable(owner()).transfer(balance); } /// @notice Redeems an NFTVoucher for an actual NFT, creating it in the process. /// @param voucher An NFTVoucher that describes the NFT to be redeemed. /// @param signature An EIP712 signature of the voucher, produced by the NFT creator. function redeem(NFTVoucher calldata voucher, bytes memory signature) external payable { require(_verify(_hash(voucher), signature), "Transaction is not authorized (invalid signature)"); require(saleStatus != SaleStatus.PAUSED, "Sales are off"); require(_tokenIds.current() != COLLECTION_SIZE, "All tokens have been minted"); require(_tokenIds.current() + voucher.numberOfTokens <= COLLECTION_SIZE, "Number of requested tokens will exceed collection size"); if(saleStatus == SaleStatus.PRESALE) { require(voucher.whitelisted, "Presale is only open to whitelisted users"); require(msg.value >= voucher.numberOfTokens * PRESALE_MINT_PRICE, "Ether value sent is not sufficient"); require(_whitelistMintedCount[voucher.redeemer] + voucher.numberOfTokens <= 2, "You've already minted all tokens available to you"); _whitelistMintedCount[voucher.redeemer] += voucher.numberOfTokens; } else { require(msg.value >= voucher.numberOfTokens * MINT_PRICE, "Ether value sent is not sufficient"); require(_mintedCount[voucher.redeemer] == 0, "You've already minted all tokens available to you"); _mintedCount[voucher.redeemer] += voucher.numberOfTokens; } _mintTokens(voucher.redeemer, voucher.numberOfTokens); } /// @dev perform actual minting of the tokens function _mintTokens(address to, uint count) internal { for(uint index = 0; index < count; index++) { _tokenIds.increment(); uint newItemId = _tokenIds.current(); _safeMint(to, newItemId); } } /// @notice Returns a hash of the given NFTVoucher, prepared using EIP712 typed data hashing rules. /// @param voucher An NFTVoucher to hash. function _hash(NFTVoucher calldata voucher) internal view returns (bytes32) { return _hashTypedDataV4(keccak256(abi.encode( keccak256("NFTVoucher(address redeemer,bool whitelisted,uint256 numberOfTokens)"), voucher.redeemer, voucher.whitelisted, voucher.numberOfTokens ))); } function _verify(bytes32 digest, bytes memory signature) internal view returns (bool) { return SignatureChecker.isValidSignatureNow(_txSigner, digest, signature); } }
_hash
function _hash(NFTVoucher calldata voucher) internal view returns (bytes32) { return _hashTypedDataV4(keccak256(abi.encode( keccak256("NFTVoucher(address redeemer,bool whitelisted,uint256 numberOfTokens)"), voucher.redeemer, voucher.whitelisted, voucher.numberOfTokens ))); }
/// @notice Returns a hash of the given NFTVoucher, prepared using EIP712 typed data hashing rules. /// @param voucher An NFTVoucher to hash.
NatSpecSingleLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 5062, 5427 ] }
8,419
MainSale
MainSale.sol
0x2c8154b76f68f9b69de0d6d079c340e939451d8a
Solidity
MainSale
contract MainSale is Ownable { ERC20 public token; ERC20 public BuyBackContract; using SafeMath for uint; address public backEndOperator = msg.sender; address team = 0x550cBC2C3Ac03f8f1d950FEf755Cd664fc498036; // 10 % - founders address bounty = 0x8118317911B0De31502aC978e1dD38e9EeE92538; // 2 % - bounty mapping(address=>bool) public whitelist; mapping(address => uint256) public investedEther; mapping(address => uint8) public typeOfInvestors; uint256 public startMainSale = 1539561600; // Monday, 15-Oct-18 00:00:00 UTC uint256 public endMainSale = 1544831999; // Friday, 14-Dec-18 23:59:59 UTC uint256 public stage1Sale = startMainSale + 14 days; // 0- 7 days uint256 public stage2Sale = startMainSale + 28 days; // 8 - 14 days uint256 public stage3Sale = startMainSale + 42 days; // 15 - 21 days uint256 public investors; uint256 public weisRaised; uint256 public buyPrice; // 1 USD uint256 public dollarPrice; uint256 public soldTokensMainSale; uint256 public softcapMainSale = 18500000*1e18; // 18,500,000 ANG - !!! в зачет пойдут бонусные uint256 public hardCapMainSale = 103500000*1e18; // 103,500,000 ANG - !!! в зачет пойдут бонусные event Authorized(address wlCandidate, uint timestamp, uint8 investorType); event Revoked(address wlCandidate, uint timestamp); event UpdateDollar(uint256 time, uint256 _rate); event Refund(uint256 sum, address investor); modifier backEnd() { require(msg.sender == backEndOperator || msg.sender == owner); _; } constructor(ERC20 _token, uint256 usdETH) public { token = _token; dollarPrice = usdETH; buyPrice = (1e18/dollarPrice); // 1 usd } function setStartMainSale(uint256 newStartMainSale) public onlyOwner { startMainSale = newStartMainSale; } function setEndMainSale(uint256 newEndMainSale) public onlyOwner { endMainSale = newEndMainSale; } function setBackEndAddress(address newBackEndOperator) public onlyOwner { backEndOperator = newBackEndOperator; } function setBuyBackAddress(ERC20 newBuyBackAddress) public onlyOwner { BuyBackContract = newBuyBackAddress; } function setBuyPrice(uint256 _dollar) public onlyOwner { dollarPrice = _dollar; buyPrice = (1e18/dollarPrice); // 1 usd emit UpdateDollar(now, dollarPrice); } /******************************************************************************* * Whitelist's section */ function authorize(address wlCandidate, uint8 investorType) public backEnd { require(wlCandidate != address(0x0)); require(!isWhitelisted(wlCandidate)); require(investors == 1 || investorType == 2); whitelist[wlCandidate] = true; investors++; if (investorType == 1) { typeOfInvestors[wlCandidate] = 1; } else { typeOfInvestors[wlCandidate] = 2; } emit Authorized(wlCandidate, now, investorType); } function revoke(address wlCandidate) public onlyOwner { whitelist[wlCandidate] = false; investors--; emit Revoked(wlCandidate, now); } function isWhitelisted(address wlCandidate) internal view returns(bool) { return whitelist[wlCandidate]; } /******************************************************************************* * Payable's section */ function isMainSale() public constant returns(bool) { return now >= startMainSale && now <= endMainSale; } function () public payable { require(isWhitelisted(msg.sender)); require(isMainSale()); mainSale(msg.sender, msg.value); require(soldTokensMainSale<=hardCapMainSale); investedEther[msg.sender] = investedEther[msg.sender].add(msg.value); } function mainSale(address _investor, uint256 _value) internal { uint256 tokens = _value.mul(1e18).div(buyPrice); uint256 tokensByDate = tokens.mul(bonusDate()).div(100); tokens = tokens.add(tokensByDate); token.mintFromICO(_investor, tokens); BuyBackContract.buyTokenICO(_investor, tokens);//Set count token for periods ICO soldTokensMainSale = soldTokensMainSale.add(tokens); // only sold uint256 tokensTeam = tokens.mul(5).div(44); // 10 % token.mintFromICO(team, tokensTeam); uint256 tokensBoynty = tokens.div(44); // 2 % token.mintFromICO(bounty, tokensBoynty); weisRaised = weisRaised.add(_value); } function bonusDate() private view returns (uint256){ if (now > startMainSale && now < stage1Sale) { // 0 - 14 days preSale return 30; } else if (now > stage1Sale && now < stage2Sale) { // 15 - 28 days preSale return 20; } else if (now > stage2Sale && now < stage3Sale) { // 29 - 42 days preSale return 10; } else if (now > stage3Sale && now < endMainSale) { // 43 - endSale return 6; } else { return 0; } } function mintManual(address receiver, uint256 _tokens) public backEnd { token.mintFromICO(receiver, _tokens); soldTokensMainSale = soldTokensMainSale.add(_tokens); BuyBackContract.buyTokenICO(receiver, _tokens);//Set count token for periods ICO uint256 tokensTeam = _tokens.mul(5).div(44); // 10 % token.mintFromICO(team, tokensTeam); uint256 tokensBoynty = _tokens.div(44); // 2 % token.mintFromICO(bounty, tokensBoynty); } function transferEthFromContract(address _to, uint256 amount) public onlyOwner { _to.transfer(amount); } function refundPreSale() public { require(soldTokensMainSale < soldTokensMainSale && now > endMainSale); uint256 rate = investedEther[msg.sender]; require(investedEther[msg.sender] >= 0); investedEther[msg.sender] = 0; msg.sender.transfer(rate); weisRaised = weisRaised.sub(rate); emit Refund(rate, msg.sender); } }
/** * @title MainCrowdSale * @dev https://github.com/elephant-marketing/*/
NatSpecMultiLine
authorize
function authorize(address wlCandidate, uint8 investorType) public backEnd { require(wlCandidate != address(0x0)); require(!isWhitelisted(wlCandidate)); require(investors == 1 || investorType == 2); whitelist[wlCandidate] = true; investors++; if (investorType == 1) { typeOfInvestors[wlCandidate] = 1; } else { typeOfInvestors[wlCandidate] = 2; } emit Authorized(wlCandidate, now, investorType); }
/******************************************************************************* * Whitelist's section */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://7b7921e890523d45c3ead92a6484902f0fc5e9bb96cdb6b0fbc928eadef19245
{ "func_code_index": [ 2641, 3116 ] }
8,420
MainSale
MainSale.sol
0x2c8154b76f68f9b69de0d6d079c340e939451d8a
Solidity
MainSale
contract MainSale is Ownable { ERC20 public token; ERC20 public BuyBackContract; using SafeMath for uint; address public backEndOperator = msg.sender; address team = 0x550cBC2C3Ac03f8f1d950FEf755Cd664fc498036; // 10 % - founders address bounty = 0x8118317911B0De31502aC978e1dD38e9EeE92538; // 2 % - bounty mapping(address=>bool) public whitelist; mapping(address => uint256) public investedEther; mapping(address => uint8) public typeOfInvestors; uint256 public startMainSale = 1539561600; // Monday, 15-Oct-18 00:00:00 UTC uint256 public endMainSale = 1544831999; // Friday, 14-Dec-18 23:59:59 UTC uint256 public stage1Sale = startMainSale + 14 days; // 0- 7 days uint256 public stage2Sale = startMainSale + 28 days; // 8 - 14 days uint256 public stage3Sale = startMainSale + 42 days; // 15 - 21 days uint256 public investors; uint256 public weisRaised; uint256 public buyPrice; // 1 USD uint256 public dollarPrice; uint256 public soldTokensMainSale; uint256 public softcapMainSale = 18500000*1e18; // 18,500,000 ANG - !!! в зачет пойдут бонусные uint256 public hardCapMainSale = 103500000*1e18; // 103,500,000 ANG - !!! в зачет пойдут бонусные event Authorized(address wlCandidate, uint timestamp, uint8 investorType); event Revoked(address wlCandidate, uint timestamp); event UpdateDollar(uint256 time, uint256 _rate); event Refund(uint256 sum, address investor); modifier backEnd() { require(msg.sender == backEndOperator || msg.sender == owner); _; } constructor(ERC20 _token, uint256 usdETH) public { token = _token; dollarPrice = usdETH; buyPrice = (1e18/dollarPrice); // 1 usd } function setStartMainSale(uint256 newStartMainSale) public onlyOwner { startMainSale = newStartMainSale; } function setEndMainSale(uint256 newEndMainSale) public onlyOwner { endMainSale = newEndMainSale; } function setBackEndAddress(address newBackEndOperator) public onlyOwner { backEndOperator = newBackEndOperator; } function setBuyBackAddress(ERC20 newBuyBackAddress) public onlyOwner { BuyBackContract = newBuyBackAddress; } function setBuyPrice(uint256 _dollar) public onlyOwner { dollarPrice = _dollar; buyPrice = (1e18/dollarPrice); // 1 usd emit UpdateDollar(now, dollarPrice); } /******************************************************************************* * Whitelist's section */ function authorize(address wlCandidate, uint8 investorType) public backEnd { require(wlCandidate != address(0x0)); require(!isWhitelisted(wlCandidate)); require(investors == 1 || investorType == 2); whitelist[wlCandidate] = true; investors++; if (investorType == 1) { typeOfInvestors[wlCandidate] = 1; } else { typeOfInvestors[wlCandidate] = 2; } emit Authorized(wlCandidate, now, investorType); } function revoke(address wlCandidate) public onlyOwner { whitelist[wlCandidate] = false; investors--; emit Revoked(wlCandidate, now); } function isWhitelisted(address wlCandidate) internal view returns(bool) { return whitelist[wlCandidate]; } /******************************************************************************* * Payable's section */ function isMainSale() public constant returns(bool) { return now >= startMainSale && now <= endMainSale; } function () public payable { require(isWhitelisted(msg.sender)); require(isMainSale()); mainSale(msg.sender, msg.value); require(soldTokensMainSale<=hardCapMainSale); investedEther[msg.sender] = investedEther[msg.sender].add(msg.value); } function mainSale(address _investor, uint256 _value) internal { uint256 tokens = _value.mul(1e18).div(buyPrice); uint256 tokensByDate = tokens.mul(bonusDate()).div(100); tokens = tokens.add(tokensByDate); token.mintFromICO(_investor, tokens); BuyBackContract.buyTokenICO(_investor, tokens);//Set count token for periods ICO soldTokensMainSale = soldTokensMainSale.add(tokens); // only sold uint256 tokensTeam = tokens.mul(5).div(44); // 10 % token.mintFromICO(team, tokensTeam); uint256 tokensBoynty = tokens.div(44); // 2 % token.mintFromICO(bounty, tokensBoynty); weisRaised = weisRaised.add(_value); } function bonusDate() private view returns (uint256){ if (now > startMainSale && now < stage1Sale) { // 0 - 14 days preSale return 30; } else if (now > stage1Sale && now < stage2Sale) { // 15 - 28 days preSale return 20; } else if (now > stage2Sale && now < stage3Sale) { // 29 - 42 days preSale return 10; } else if (now > stage3Sale && now < endMainSale) { // 43 - endSale return 6; } else { return 0; } } function mintManual(address receiver, uint256 _tokens) public backEnd { token.mintFromICO(receiver, _tokens); soldTokensMainSale = soldTokensMainSale.add(_tokens); BuyBackContract.buyTokenICO(receiver, _tokens);//Set count token for periods ICO uint256 tokensTeam = _tokens.mul(5).div(44); // 10 % token.mintFromICO(team, tokensTeam); uint256 tokensBoynty = _tokens.div(44); // 2 % token.mintFromICO(bounty, tokensBoynty); } function transferEthFromContract(address _to, uint256 amount) public onlyOwner { _to.transfer(amount); } function refundPreSale() public { require(soldTokensMainSale < soldTokensMainSale && now > endMainSale); uint256 rate = investedEther[msg.sender]; require(investedEther[msg.sender] >= 0); investedEther[msg.sender] = 0; msg.sender.transfer(rate); weisRaised = weisRaised.sub(rate); emit Refund(rate, msg.sender); } }
/** * @title MainCrowdSale * @dev https://github.com/elephant-marketing/*/
NatSpecMultiLine
isMainSale
function isMainSale() public constant returns(bool) { return now >= startMainSale && now <= endMainSale; }
/******************************************************************************* * Payable's section */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://7b7921e890523d45c3ead92a6484902f0fc5e9bb96cdb6b0fbc928eadef19245
{ "func_code_index": [ 3531, 3648 ] }
8,421
MexaCoin
MexaCoin.sol
0xdea8e7d3b9e422073a69615b998b34533b7bf898
Solidity
Ownable
contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://04111d1f568ec95779355af636ec353af628df58bdacfea0d06838231cd882be
{ "func_code_index": [ 587, 743 ] }
8,422
MexaCoin
MexaCoin.sol
0xdea8e7d3b9e422073a69615b998b34533b7bf898
Solidity
Pausable
contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } }
/** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */
NatSpecMultiLine
pause
function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); }
/** * @dev called by the owner to pause, triggers stopped state */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://04111d1f568ec95779355af636ec353af628df58bdacfea0d06838231cd882be
{ "func_code_index": [ 513, 609 ] }
8,423
MexaCoin
MexaCoin.sol
0xdea8e7d3b9e422073a69615b998b34533b7bf898
Solidity
Pausable
contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } }
/** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */
NatSpecMultiLine
unpause
function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); }
/** * @dev called by the owner to unpause, returns to normal state */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://04111d1f568ec95779355af636ec353af628df58bdacfea0d06838231cd882be
{ "func_code_index": [ 693, 791 ] }
8,424
MexaCoin
MexaCoin.sol
0xdea8e7d3b9e422073a69615b998b34533b7bf898
Solidity
BasicToken
contract BasicToken is Ownable, ERC20Basic { using SafeMath for uint; mapping(address => uint) public balances; // additional variables for use if transaction fees ever became necessary uint public basisPointsRate = 0; uint public maximumFee = 0; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { require(!(msg.data.length < size + 4)); _; } /** * @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, uint _value) public onlyPayloadSize(2 * 32) { uint fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } uint sendAmount = _value.sub(fee); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(sendAmount); if (fee > 0) { balances[owner] = balances[owner].add(fee); emit Transfer(msg.sender, owner, fee); } emit Transfer(msg.sender, _to, sendAmount); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
transfer
function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) { uint fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } uint sendAmount = _value.sub(fee); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(sendAmount); if (fee > 0) { balances[owner] = balances[owner].add(fee); emit Transfer(msg.sender, owner, fee); } emit Transfer(msg.sender, _to, sendAmount); }
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://04111d1f568ec95779355af636ec353af628df58bdacfea0d06838231cd882be
{ "func_code_index": [ 626, 1214 ] }
8,425
MexaCoin
MexaCoin.sol
0xdea8e7d3b9e422073a69615b998b34533b7bf898
Solidity
BasicToken
contract BasicToken is Ownable, ERC20Basic { using SafeMath for uint; mapping(address => uint) public balances; // additional variables for use if transaction fees ever became necessary uint public basisPointsRate = 0; uint public maximumFee = 0; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { require(!(msg.data.length < size + 4)); _; } /** * @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, uint _value) public onlyPayloadSize(2 * 32) { uint fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } uint sendAmount = _value.sub(fee); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(sendAmount); if (fee > 0) { balances[owner] = balances[owner].add(fee); emit Transfer(msg.sender, owner, fee); } emit Transfer(msg.sender, _to, sendAmount); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
balanceOf
function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; }
/** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://04111d1f568ec95779355af636ec353af628df58bdacfea0d06838231cd882be
{ "func_code_index": [ 1427, 1548 ] }
8,426
MexaCoin
MexaCoin.sol
0xdea8e7d3b9e422073a69615b998b34533b7bf898
Solidity
StandardToken
contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) public allowed; uint public constant MAX_UINT = 2**256 - 1; /** * @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 uint the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; uint fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } if (_allowance < MAX_UINT) { allowed[_from][msg.sender] = _allowance.sub(_value); } uint sendAmount = _value.sub(fee); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(sendAmount); if (fee > 0) { balances[owner] = balances[owner].add(fee); emit Transfer(_from, owner, fee); } emit Transfer(_from, _to, sendAmount); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens than 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 uint specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint remaining) { return allowed[_owner][_spender]; } }
/** * @title Standard ERC20 token * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based oncode by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
transferFrom
function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; uint fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } if (_allowance < MAX_UINT) { allowed[_from][msg.sender] = _allowance.sub(_value); } uint sendAmount = _value.sub(fee); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(sendAmount); if (fee > 0) { balances[owner] = balances[owner].add(fee); emit Transfer(_from, owner, fee); } emit Transfer(_from, _to, sendAmount); }
/** * @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 uint the amount of tokens to be transferred */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://04111d1f568ec95779355af636ec353af628df58bdacfea0d06838231cd882be
{ "func_code_index": [ 451, 1367 ] }
8,427
MexaCoin
MexaCoin.sol
0xdea8e7d3b9e422073a69615b998b34533b7bf898
Solidity
StandardToken
contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) public allowed; uint public constant MAX_UINT = 2**256 - 1; /** * @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 uint the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; uint fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } if (_allowance < MAX_UINT) { allowed[_from][msg.sender] = _allowance.sub(_value); } uint sendAmount = _value.sub(fee); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(sendAmount); if (fee > 0) { balances[owner] = balances[owner].add(fee); emit Transfer(_from, owner, fee); } emit Transfer(_from, _to, sendAmount); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens than 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 uint specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint remaining) { return allowed[_owner][_spender]; } }
/** * @title Standard ERC20 token * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based oncode by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
approve
function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); }
/** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://04111d1f568ec95779355af636ec353af628df58bdacfea0d06838231cd882be
{ "func_code_index": [ 1609, 2192 ] }
8,428
MexaCoin
MexaCoin.sol
0xdea8e7d3b9e422073a69615b998b34533b7bf898
Solidity
StandardToken
contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) public allowed; uint public constant MAX_UINT = 2**256 - 1; /** * @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 uint the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; uint fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } if (_allowance < MAX_UINT) { allowed[_from][msg.sender] = _allowance.sub(_value); } uint sendAmount = _value.sub(fee); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(sendAmount); if (fee > 0) { balances[owner] = balances[owner].add(fee); emit Transfer(_from, owner, fee); } emit Transfer(_from, _to, sendAmount); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens than 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 uint specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint remaining) { return allowed[_owner][_spender]; } }
/** * @title Standard ERC20 token * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based oncode by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
allowance
function allowance(address _owner, address _spender) public constant returns (uint remaining) { return allowed[_owner][_spender]; }
/** * @dev Function to check the amount of tokens than 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 uint specifying the amount of tokens still available for the spender. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://04111d1f568ec95779355af636ec353af628df58bdacfea0d06838231cd882be
{ "func_code_index": [ 2520, 2670 ] }
8,429
MexaCoin
MexaCoin.sol
0xdea8e7d3b9e422073a69615b998b34533b7bf898
Solidity
UpgradedStandardToken
contract UpgradedStandardToken is StandardToken{ // those methods are called by the legacy contract // and they must ensure msg.sender to be the contract address function transferByLegacy(address from, address to, uint value) public; function transferFromByLegacy(address sender, address from, address spender, uint value) public; function approveByLegacy(address from, address spender, uint value) public; }
transferByLegacy
function transferByLegacy(address from, address to, uint value) public;
// those methods are called by the legacy contract // and they must ensure msg.sender to be the contract address
LineComment
v0.4.23+commit.124ca40d
bzzr://04111d1f568ec95779355af636ec353af628df58bdacfea0d06838231cd882be
{ "func_code_index": [ 173, 249 ] }
8,430
MexaCoin
MexaCoin.sol
0xdea8e7d3b9e422073a69615b998b34533b7bf898
Solidity
MexaCoin
contract MexaCoin is Pausable, StandardToken, BlackList { string public name; string public symbol; uint public decimals; address public upgradedAddress; bool public deprecated; // Inicializa el contrato con el suministro inicial de monedas al creador // // @param _initialSupply Suministro inicial de monedas // @param _name Establece el nombre de la moneda // @param _symbol Establece el simbolo de la moneda // @param _decimals Establece el numero de decimales constructor (uint _initialSupply, string _name, string _symbol, uint _decimals) public { _totalSupply = _initialSupply; name = _name; symbol = _symbol; decimals = _decimals; balances[owner] = _initialSupply; deprecated = false; } // Transferencias entre direcciones // Requiere que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _to Direccion a la que se envian las monedas // @param _value Cantidad de monedas a enviar function transfer(address _to, uint _value) public whenNotPaused { require(!isBlackListed[msg.sender]); require(!isBlackListed[_to]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value); } else { return super.transfer(_to, _value); } } // Refleja el balance de una direccion // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param who Direccion a consultar function balanceOf(address who) public constant returns (uint) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).balanceOf(who); } else { return super.balanceOf(who); } } // Transferencias desde direcciones a nombre de terceros (concesiones) // Require que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _from Direccion de la que se envian las monedas // @param _to Direccion a la que se envian las monedas // @param _value Cantidad de monedas a enviar function transferFrom(address _from, address _to, uint _value) public whenNotPaused { require(!isBlackListed[_from]); require(!isBlackListed[_to]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value); } else { return super.transferFrom(_from, _to, _value); } } // Permite genera concesiones a direcciones de terceros especificando la direccion y la cantidad de monedas a conceder // Require que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _spender Direccion a la que se le conceden las monedas // @param _value Cantidad de monedas a conceder function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) whenNotPaused { require(!isBlackListed[msg.sender]); require(!isBlackListed[_spender]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value); } else { return super.approve(_spender, _value); } } // Refleja cantidad de moendas restantes en concesion // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _owner Direccion de quien concede las monedas // @param _spender Direccion que posee la concesion function allowance(address _owner, address _spender) public constant returns (uint remaining) { if (deprecated) { return StandardToken(upgradedAddress).allowance(_owner, _spender); } else { return super.allowance(_owner, _spender); } } // Suspende el actual contrato a favor de uno nuevo // // @param _upgradedAddress Direccion del nuevo contrato function deprecate(address _upgradedAddress) public onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; emit Deprecate(_upgradedAddress); } // Refleja la cantidad total de monedas generada por el contrato // function totalSupply() public constant returns (uint) { if (deprecated) { return StandardToken(upgradedAddress).totalSupply(); } else { return _totalSupply; } } // Genera nuevas monedas y las deposita en la direccion del creador // // @param _amount Numero de monedas a generar function issue(uint amount) public onlyOwner { require(_totalSupply + amount > _totalSupply); require(balances[owner] + amount > balances[owner]); balances[owner] += amount; _totalSupply += amount; emit Issue(amount); } // Retiro de monedas // Las moendas son retiradas de la cuenta del creador // El balance en la cuenta debe ser suficiente para completar la transaccion de lo contrario se generara un error // @param _amount Nuemro de monedas a retirar function redeem(uint amount) public onlyOwner { require(_totalSupply >= amount); require(balances[owner] >= amount); _totalSupply -= amount; balances[owner] -= amount; emit Redeem(amount); } // Establece el valor de las cuotas en caso de existir // // @param newBasisPoints Cuota base // @param newMaxFee Cuota maxima function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner { // Asegura el valor maximo que no podran sobrepasar las cuotas require(newBasisPoints < 50); require(newMaxFee < 1000); basisPointsRate = newBasisPoints; maximumFee = newMaxFee.mul(10**decimals); emit Params(basisPointsRate, maximumFee); } // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Issue(uint amount); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Redeem(uint amount); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Deprecate(address newAddress); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Params(uint feeBasisPoints, uint maxFee); }
transfer
function transfer(address _to, uint _value) public whenNotPaused { require(!isBlackListed[msg.sender]); require(!isBlackListed[_to]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value); } else { return super.transfer(_to, _value); } }
// Transferencias entre direcciones // Requiere que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _to Direccion a la que se envian las monedas // @param _value Cantidad de monedas a enviar
LineComment
v0.4.23+commit.124ca40d
bzzr://04111d1f568ec95779355af636ec353af628df58bdacfea0d06838231cd882be
{ "func_code_index": [ 1275, 1645 ] }
8,431
MexaCoin
MexaCoin.sol
0xdea8e7d3b9e422073a69615b998b34533b7bf898
Solidity
MexaCoin
contract MexaCoin is Pausable, StandardToken, BlackList { string public name; string public symbol; uint public decimals; address public upgradedAddress; bool public deprecated; // Inicializa el contrato con el suministro inicial de monedas al creador // // @param _initialSupply Suministro inicial de monedas // @param _name Establece el nombre de la moneda // @param _symbol Establece el simbolo de la moneda // @param _decimals Establece el numero de decimales constructor (uint _initialSupply, string _name, string _symbol, uint _decimals) public { _totalSupply = _initialSupply; name = _name; symbol = _symbol; decimals = _decimals; balances[owner] = _initialSupply; deprecated = false; } // Transferencias entre direcciones // Requiere que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _to Direccion a la que se envian las monedas // @param _value Cantidad de monedas a enviar function transfer(address _to, uint _value) public whenNotPaused { require(!isBlackListed[msg.sender]); require(!isBlackListed[_to]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value); } else { return super.transfer(_to, _value); } } // Refleja el balance de una direccion // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param who Direccion a consultar function balanceOf(address who) public constant returns (uint) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).balanceOf(who); } else { return super.balanceOf(who); } } // Transferencias desde direcciones a nombre de terceros (concesiones) // Require que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _from Direccion de la que se envian las monedas // @param _to Direccion a la que se envian las monedas // @param _value Cantidad de monedas a enviar function transferFrom(address _from, address _to, uint _value) public whenNotPaused { require(!isBlackListed[_from]); require(!isBlackListed[_to]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value); } else { return super.transferFrom(_from, _to, _value); } } // Permite genera concesiones a direcciones de terceros especificando la direccion y la cantidad de monedas a conceder // Require que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _spender Direccion a la que se le conceden las monedas // @param _value Cantidad de monedas a conceder function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) whenNotPaused { require(!isBlackListed[msg.sender]); require(!isBlackListed[_spender]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value); } else { return super.approve(_spender, _value); } } // Refleja cantidad de moendas restantes en concesion // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _owner Direccion de quien concede las monedas // @param _spender Direccion que posee la concesion function allowance(address _owner, address _spender) public constant returns (uint remaining) { if (deprecated) { return StandardToken(upgradedAddress).allowance(_owner, _spender); } else { return super.allowance(_owner, _spender); } } // Suspende el actual contrato a favor de uno nuevo // // @param _upgradedAddress Direccion del nuevo contrato function deprecate(address _upgradedAddress) public onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; emit Deprecate(_upgradedAddress); } // Refleja la cantidad total de monedas generada por el contrato // function totalSupply() public constant returns (uint) { if (deprecated) { return StandardToken(upgradedAddress).totalSupply(); } else { return _totalSupply; } } // Genera nuevas monedas y las deposita en la direccion del creador // // @param _amount Numero de monedas a generar function issue(uint amount) public onlyOwner { require(_totalSupply + amount > _totalSupply); require(balances[owner] + amount > balances[owner]); balances[owner] += amount; _totalSupply += amount; emit Issue(amount); } // Retiro de monedas // Las moendas son retiradas de la cuenta del creador // El balance en la cuenta debe ser suficiente para completar la transaccion de lo contrario se generara un error // @param _amount Nuemro de monedas a retirar function redeem(uint amount) public onlyOwner { require(_totalSupply >= amount); require(balances[owner] >= amount); _totalSupply -= amount; balances[owner] -= amount; emit Redeem(amount); } // Establece el valor de las cuotas en caso de existir // // @param newBasisPoints Cuota base // @param newMaxFee Cuota maxima function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner { // Asegura el valor maximo que no podran sobrepasar las cuotas require(newBasisPoints < 50); require(newMaxFee < 1000); basisPointsRate = newBasisPoints; maximumFee = newMaxFee.mul(10**decimals); emit Params(basisPointsRate, maximumFee); } // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Issue(uint amount); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Redeem(uint amount); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Deprecate(address newAddress); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Params(uint feeBasisPoints, uint maxFee); }
balanceOf
function balanceOf(address who) public constant returns (uint) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).balanceOf(who); } else { return super.balanceOf(who); } }
// Refleja el balance de una direccion // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param who Direccion a consultar
LineComment
v0.4.23+commit.124ca40d
bzzr://04111d1f568ec95779355af636ec353af628df58bdacfea0d06838231cd882be
{ "func_code_index": [ 1843, 2092 ] }
8,432
MexaCoin
MexaCoin.sol
0xdea8e7d3b9e422073a69615b998b34533b7bf898
Solidity
MexaCoin
contract MexaCoin is Pausable, StandardToken, BlackList { string public name; string public symbol; uint public decimals; address public upgradedAddress; bool public deprecated; // Inicializa el contrato con el suministro inicial de monedas al creador // // @param _initialSupply Suministro inicial de monedas // @param _name Establece el nombre de la moneda // @param _symbol Establece el simbolo de la moneda // @param _decimals Establece el numero de decimales constructor (uint _initialSupply, string _name, string _symbol, uint _decimals) public { _totalSupply = _initialSupply; name = _name; symbol = _symbol; decimals = _decimals; balances[owner] = _initialSupply; deprecated = false; } // Transferencias entre direcciones // Requiere que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _to Direccion a la que se envian las monedas // @param _value Cantidad de monedas a enviar function transfer(address _to, uint _value) public whenNotPaused { require(!isBlackListed[msg.sender]); require(!isBlackListed[_to]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value); } else { return super.transfer(_to, _value); } } // Refleja el balance de una direccion // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param who Direccion a consultar function balanceOf(address who) public constant returns (uint) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).balanceOf(who); } else { return super.balanceOf(who); } } // Transferencias desde direcciones a nombre de terceros (concesiones) // Require que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _from Direccion de la que se envian las monedas // @param _to Direccion a la que se envian las monedas // @param _value Cantidad de monedas a enviar function transferFrom(address _from, address _to, uint _value) public whenNotPaused { require(!isBlackListed[_from]); require(!isBlackListed[_to]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value); } else { return super.transferFrom(_from, _to, _value); } } // Permite genera concesiones a direcciones de terceros especificando la direccion y la cantidad de monedas a conceder // Require que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _spender Direccion a la que se le conceden las monedas // @param _value Cantidad de monedas a conceder function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) whenNotPaused { require(!isBlackListed[msg.sender]); require(!isBlackListed[_spender]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value); } else { return super.approve(_spender, _value); } } // Refleja cantidad de moendas restantes en concesion // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _owner Direccion de quien concede las monedas // @param _spender Direccion que posee la concesion function allowance(address _owner, address _spender) public constant returns (uint remaining) { if (deprecated) { return StandardToken(upgradedAddress).allowance(_owner, _spender); } else { return super.allowance(_owner, _spender); } } // Suspende el actual contrato a favor de uno nuevo // // @param _upgradedAddress Direccion del nuevo contrato function deprecate(address _upgradedAddress) public onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; emit Deprecate(_upgradedAddress); } // Refleja la cantidad total de monedas generada por el contrato // function totalSupply() public constant returns (uint) { if (deprecated) { return StandardToken(upgradedAddress).totalSupply(); } else { return _totalSupply; } } // Genera nuevas monedas y las deposita en la direccion del creador // // @param _amount Numero de monedas a generar function issue(uint amount) public onlyOwner { require(_totalSupply + amount > _totalSupply); require(balances[owner] + amount > balances[owner]); balances[owner] += amount; _totalSupply += amount; emit Issue(amount); } // Retiro de monedas // Las moendas son retiradas de la cuenta del creador // El balance en la cuenta debe ser suficiente para completar la transaccion de lo contrario se generara un error // @param _amount Nuemro de monedas a retirar function redeem(uint amount) public onlyOwner { require(_totalSupply >= amount); require(balances[owner] >= amount); _totalSupply -= amount; balances[owner] -= amount; emit Redeem(amount); } // Establece el valor de las cuotas en caso de existir // // @param newBasisPoints Cuota base // @param newMaxFee Cuota maxima function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner { // Asegura el valor maximo que no podran sobrepasar las cuotas require(newBasisPoints < 50); require(newMaxFee < 1000); basisPointsRate = newBasisPoints; maximumFee = newMaxFee.mul(10**decimals); emit Params(basisPointsRate, maximumFee); } // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Issue(uint amount); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Redeem(uint amount); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Deprecate(address newAddress); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Params(uint feeBasisPoints, uint maxFee); }
transferFrom
function transferFrom(address _from, address _to, uint _value) public whenNotPaused { require(!isBlackListed[_from]); require(!isBlackListed[_to]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value); } else { return super.transferFrom(_from, _to, _value); } }
// Transferencias desde direcciones a nombre de terceros (concesiones) // Require que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _from Direccion de la que se envian las monedas // @param _to Direccion a la que se envian las monedas // @param _value Cantidad de monedas a enviar
LineComment
v0.4.23+commit.124ca40d
bzzr://04111d1f568ec95779355af636ec353af628df58bdacfea0d06838231cd882be
{ "func_code_index": [ 2624, 3030 ] }
8,433
MexaCoin
MexaCoin.sol
0xdea8e7d3b9e422073a69615b998b34533b7bf898
Solidity
MexaCoin
contract MexaCoin is Pausable, StandardToken, BlackList { string public name; string public symbol; uint public decimals; address public upgradedAddress; bool public deprecated; // Inicializa el contrato con el suministro inicial de monedas al creador // // @param _initialSupply Suministro inicial de monedas // @param _name Establece el nombre de la moneda // @param _symbol Establece el simbolo de la moneda // @param _decimals Establece el numero de decimales constructor (uint _initialSupply, string _name, string _symbol, uint _decimals) public { _totalSupply = _initialSupply; name = _name; symbol = _symbol; decimals = _decimals; balances[owner] = _initialSupply; deprecated = false; } // Transferencias entre direcciones // Requiere que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _to Direccion a la que se envian las monedas // @param _value Cantidad de monedas a enviar function transfer(address _to, uint _value) public whenNotPaused { require(!isBlackListed[msg.sender]); require(!isBlackListed[_to]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value); } else { return super.transfer(_to, _value); } } // Refleja el balance de una direccion // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param who Direccion a consultar function balanceOf(address who) public constant returns (uint) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).balanceOf(who); } else { return super.balanceOf(who); } } // Transferencias desde direcciones a nombre de terceros (concesiones) // Require que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _from Direccion de la que se envian las monedas // @param _to Direccion a la que se envian las monedas // @param _value Cantidad de monedas a enviar function transferFrom(address _from, address _to, uint _value) public whenNotPaused { require(!isBlackListed[_from]); require(!isBlackListed[_to]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value); } else { return super.transferFrom(_from, _to, _value); } } // Permite genera concesiones a direcciones de terceros especificando la direccion y la cantidad de monedas a conceder // Require que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _spender Direccion a la que se le conceden las monedas // @param _value Cantidad de monedas a conceder function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) whenNotPaused { require(!isBlackListed[msg.sender]); require(!isBlackListed[_spender]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value); } else { return super.approve(_spender, _value); } } // Refleja cantidad de moendas restantes en concesion // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _owner Direccion de quien concede las monedas // @param _spender Direccion que posee la concesion function allowance(address _owner, address _spender) public constant returns (uint remaining) { if (deprecated) { return StandardToken(upgradedAddress).allowance(_owner, _spender); } else { return super.allowance(_owner, _spender); } } // Suspende el actual contrato a favor de uno nuevo // // @param _upgradedAddress Direccion del nuevo contrato function deprecate(address _upgradedAddress) public onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; emit Deprecate(_upgradedAddress); } // Refleja la cantidad total de monedas generada por el contrato // function totalSupply() public constant returns (uint) { if (deprecated) { return StandardToken(upgradedAddress).totalSupply(); } else { return _totalSupply; } } // Genera nuevas monedas y las deposita en la direccion del creador // // @param _amount Numero de monedas a generar function issue(uint amount) public onlyOwner { require(_totalSupply + amount > _totalSupply); require(balances[owner] + amount > balances[owner]); balances[owner] += amount; _totalSupply += amount; emit Issue(amount); } // Retiro de monedas // Las moendas son retiradas de la cuenta del creador // El balance en la cuenta debe ser suficiente para completar la transaccion de lo contrario se generara un error // @param _amount Nuemro de monedas a retirar function redeem(uint amount) public onlyOwner { require(_totalSupply >= amount); require(balances[owner] >= amount); _totalSupply -= amount; balances[owner] -= amount; emit Redeem(amount); } // Establece el valor de las cuotas en caso de existir // // @param newBasisPoints Cuota base // @param newMaxFee Cuota maxima function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner { // Asegura el valor maximo que no podran sobrepasar las cuotas require(newBasisPoints < 50); require(newMaxFee < 1000); basisPointsRate = newBasisPoints; maximumFee = newMaxFee.mul(10**decimals); emit Params(basisPointsRate, maximumFee); } // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Issue(uint amount); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Redeem(uint amount); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Deprecate(address newAddress); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Params(uint feeBasisPoints, uint maxFee); }
approve
function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) whenNotPaused { require(!isBlackListed[msg.sender]); require(!isBlackListed[_spender]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value); } else { return super.approve(_spender, _value); } }
// Permite genera concesiones a direcciones de terceros especificando la direccion y la cantidad de monedas a conceder // Require que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _spender Direccion a la que se le conceden las monedas // @param _value Cantidad de monedas a conceder
LineComment
v0.4.23+commit.124ca40d
bzzr://04111d1f568ec95779355af636ec353af628df58bdacfea0d06838231cd882be
{ "func_code_index": [ 3538, 3949 ] }
8,434
MexaCoin
MexaCoin.sol
0xdea8e7d3b9e422073a69615b998b34533b7bf898
Solidity
MexaCoin
contract MexaCoin is Pausable, StandardToken, BlackList { string public name; string public symbol; uint public decimals; address public upgradedAddress; bool public deprecated; // Inicializa el contrato con el suministro inicial de monedas al creador // // @param _initialSupply Suministro inicial de monedas // @param _name Establece el nombre de la moneda // @param _symbol Establece el simbolo de la moneda // @param _decimals Establece el numero de decimales constructor (uint _initialSupply, string _name, string _symbol, uint _decimals) public { _totalSupply = _initialSupply; name = _name; symbol = _symbol; decimals = _decimals; balances[owner] = _initialSupply; deprecated = false; } // Transferencias entre direcciones // Requiere que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _to Direccion a la que se envian las monedas // @param _value Cantidad de monedas a enviar function transfer(address _to, uint _value) public whenNotPaused { require(!isBlackListed[msg.sender]); require(!isBlackListed[_to]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value); } else { return super.transfer(_to, _value); } } // Refleja el balance de una direccion // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param who Direccion a consultar function balanceOf(address who) public constant returns (uint) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).balanceOf(who); } else { return super.balanceOf(who); } } // Transferencias desde direcciones a nombre de terceros (concesiones) // Require que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _from Direccion de la que se envian las monedas // @param _to Direccion a la que se envian las monedas // @param _value Cantidad de monedas a enviar function transferFrom(address _from, address _to, uint _value) public whenNotPaused { require(!isBlackListed[_from]); require(!isBlackListed[_to]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value); } else { return super.transferFrom(_from, _to, _value); } } // Permite genera concesiones a direcciones de terceros especificando la direccion y la cantidad de monedas a conceder // Require que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _spender Direccion a la que se le conceden las monedas // @param _value Cantidad de monedas a conceder function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) whenNotPaused { require(!isBlackListed[msg.sender]); require(!isBlackListed[_spender]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value); } else { return super.approve(_spender, _value); } } // Refleja cantidad de moendas restantes en concesion // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _owner Direccion de quien concede las monedas // @param _spender Direccion que posee la concesion function allowance(address _owner, address _spender) public constant returns (uint remaining) { if (deprecated) { return StandardToken(upgradedAddress).allowance(_owner, _spender); } else { return super.allowance(_owner, _spender); } } // Suspende el actual contrato a favor de uno nuevo // // @param _upgradedAddress Direccion del nuevo contrato function deprecate(address _upgradedAddress) public onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; emit Deprecate(_upgradedAddress); } // Refleja la cantidad total de monedas generada por el contrato // function totalSupply() public constant returns (uint) { if (deprecated) { return StandardToken(upgradedAddress).totalSupply(); } else { return _totalSupply; } } // Genera nuevas monedas y las deposita en la direccion del creador // // @param _amount Numero de monedas a generar function issue(uint amount) public onlyOwner { require(_totalSupply + amount > _totalSupply); require(balances[owner] + amount > balances[owner]); balances[owner] += amount; _totalSupply += amount; emit Issue(amount); } // Retiro de monedas // Las moendas son retiradas de la cuenta del creador // El balance en la cuenta debe ser suficiente para completar la transaccion de lo contrario se generara un error // @param _amount Nuemro de monedas a retirar function redeem(uint amount) public onlyOwner { require(_totalSupply >= amount); require(balances[owner] >= amount); _totalSupply -= amount; balances[owner] -= amount; emit Redeem(amount); } // Establece el valor de las cuotas en caso de existir // // @param newBasisPoints Cuota base // @param newMaxFee Cuota maxima function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner { // Asegura el valor maximo que no podran sobrepasar las cuotas require(newBasisPoints < 50); require(newMaxFee < 1000); basisPointsRate = newBasisPoints; maximumFee = newMaxFee.mul(10**decimals); emit Params(basisPointsRate, maximumFee); } // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Issue(uint amount); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Redeem(uint amount); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Deprecate(address newAddress); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Params(uint feeBasisPoints, uint maxFee); }
allowance
function allowance(address _owner, address _spender) public constant returns (uint remaining) { if (deprecated) { return StandardToken(upgradedAddress).allowance(_owner, _spender); } else { return super.allowance(_owner, _spender); } }
// Refleja cantidad de moendas restantes en concesion // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _owner Direccion de quien concede las monedas // @param _spender Direccion que posee la concesion
LineComment
v0.4.23+commit.124ca40d
bzzr://04111d1f568ec95779355af636ec353af628df58bdacfea0d06838231cd882be
{ "func_code_index": [ 4245, 4543 ] }
8,435
MexaCoin
MexaCoin.sol
0xdea8e7d3b9e422073a69615b998b34533b7bf898
Solidity
MexaCoin
contract MexaCoin is Pausable, StandardToken, BlackList { string public name; string public symbol; uint public decimals; address public upgradedAddress; bool public deprecated; // Inicializa el contrato con el suministro inicial de monedas al creador // // @param _initialSupply Suministro inicial de monedas // @param _name Establece el nombre de la moneda // @param _symbol Establece el simbolo de la moneda // @param _decimals Establece el numero de decimales constructor (uint _initialSupply, string _name, string _symbol, uint _decimals) public { _totalSupply = _initialSupply; name = _name; symbol = _symbol; decimals = _decimals; balances[owner] = _initialSupply; deprecated = false; } // Transferencias entre direcciones // Requiere que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _to Direccion a la que se envian las monedas // @param _value Cantidad de monedas a enviar function transfer(address _to, uint _value) public whenNotPaused { require(!isBlackListed[msg.sender]); require(!isBlackListed[_to]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value); } else { return super.transfer(_to, _value); } } // Refleja el balance de una direccion // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param who Direccion a consultar function balanceOf(address who) public constant returns (uint) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).balanceOf(who); } else { return super.balanceOf(who); } } // Transferencias desde direcciones a nombre de terceros (concesiones) // Require que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _from Direccion de la que se envian las monedas // @param _to Direccion a la que se envian las monedas // @param _value Cantidad de monedas a enviar function transferFrom(address _from, address _to, uint _value) public whenNotPaused { require(!isBlackListed[_from]); require(!isBlackListed[_to]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value); } else { return super.transferFrom(_from, _to, _value); } } // Permite genera concesiones a direcciones de terceros especificando la direccion y la cantidad de monedas a conceder // Require que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _spender Direccion a la que se le conceden las monedas // @param _value Cantidad de monedas a conceder function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) whenNotPaused { require(!isBlackListed[msg.sender]); require(!isBlackListed[_spender]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value); } else { return super.approve(_spender, _value); } } // Refleja cantidad de moendas restantes en concesion // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _owner Direccion de quien concede las monedas // @param _spender Direccion que posee la concesion function allowance(address _owner, address _spender) public constant returns (uint remaining) { if (deprecated) { return StandardToken(upgradedAddress).allowance(_owner, _spender); } else { return super.allowance(_owner, _spender); } } // Suspende el actual contrato a favor de uno nuevo // // @param _upgradedAddress Direccion del nuevo contrato function deprecate(address _upgradedAddress) public onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; emit Deprecate(_upgradedAddress); } // Refleja la cantidad total de monedas generada por el contrato // function totalSupply() public constant returns (uint) { if (deprecated) { return StandardToken(upgradedAddress).totalSupply(); } else { return _totalSupply; } } // Genera nuevas monedas y las deposita en la direccion del creador // // @param _amount Numero de monedas a generar function issue(uint amount) public onlyOwner { require(_totalSupply + amount > _totalSupply); require(balances[owner] + amount > balances[owner]); balances[owner] += amount; _totalSupply += amount; emit Issue(amount); } // Retiro de monedas // Las moendas son retiradas de la cuenta del creador // El balance en la cuenta debe ser suficiente para completar la transaccion de lo contrario se generara un error // @param _amount Nuemro de monedas a retirar function redeem(uint amount) public onlyOwner { require(_totalSupply >= amount); require(balances[owner] >= amount); _totalSupply -= amount; balances[owner] -= amount; emit Redeem(amount); } // Establece el valor de las cuotas en caso de existir // // @param newBasisPoints Cuota base // @param newMaxFee Cuota maxima function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner { // Asegura el valor maximo que no podran sobrepasar las cuotas require(newBasisPoints < 50); require(newMaxFee < 1000); basisPointsRate = newBasisPoints; maximumFee = newMaxFee.mul(10**decimals); emit Params(basisPointsRate, maximumFee); } // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Issue(uint amount); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Redeem(uint amount); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Deprecate(address newAddress); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Params(uint feeBasisPoints, uint maxFee); }
deprecate
function deprecate(address _upgradedAddress) public onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; emit Deprecate(_upgradedAddress); }
// Suspende el actual contrato a favor de uno nuevo // // @param _upgradedAddress Direccion del nuevo contrato
LineComment
v0.4.23+commit.124ca40d
bzzr://04111d1f568ec95779355af636ec353af628df58bdacfea0d06838231cd882be
{ "func_code_index": [ 4673, 4864 ] }
8,436
MexaCoin
MexaCoin.sol
0xdea8e7d3b9e422073a69615b998b34533b7bf898
Solidity
MexaCoin
contract MexaCoin is Pausable, StandardToken, BlackList { string public name; string public symbol; uint public decimals; address public upgradedAddress; bool public deprecated; // Inicializa el contrato con el suministro inicial de monedas al creador // // @param _initialSupply Suministro inicial de monedas // @param _name Establece el nombre de la moneda // @param _symbol Establece el simbolo de la moneda // @param _decimals Establece el numero de decimales constructor (uint _initialSupply, string _name, string _symbol, uint _decimals) public { _totalSupply = _initialSupply; name = _name; symbol = _symbol; decimals = _decimals; balances[owner] = _initialSupply; deprecated = false; } // Transferencias entre direcciones // Requiere que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _to Direccion a la que se envian las monedas // @param _value Cantidad de monedas a enviar function transfer(address _to, uint _value) public whenNotPaused { require(!isBlackListed[msg.sender]); require(!isBlackListed[_to]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value); } else { return super.transfer(_to, _value); } } // Refleja el balance de una direccion // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param who Direccion a consultar function balanceOf(address who) public constant returns (uint) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).balanceOf(who); } else { return super.balanceOf(who); } } // Transferencias desde direcciones a nombre de terceros (concesiones) // Require que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _from Direccion de la que se envian las monedas // @param _to Direccion a la que se envian las monedas // @param _value Cantidad de monedas a enviar function transferFrom(address _from, address _to, uint _value) public whenNotPaused { require(!isBlackListed[_from]); require(!isBlackListed[_to]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value); } else { return super.transferFrom(_from, _to, _value); } } // Permite genera concesiones a direcciones de terceros especificando la direccion y la cantidad de monedas a conceder // Require que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _spender Direccion a la que se le conceden las monedas // @param _value Cantidad de monedas a conceder function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) whenNotPaused { require(!isBlackListed[msg.sender]); require(!isBlackListed[_spender]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value); } else { return super.approve(_spender, _value); } } // Refleja cantidad de moendas restantes en concesion // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _owner Direccion de quien concede las monedas // @param _spender Direccion que posee la concesion function allowance(address _owner, address _spender) public constant returns (uint remaining) { if (deprecated) { return StandardToken(upgradedAddress).allowance(_owner, _spender); } else { return super.allowance(_owner, _spender); } } // Suspende el actual contrato a favor de uno nuevo // // @param _upgradedAddress Direccion del nuevo contrato function deprecate(address _upgradedAddress) public onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; emit Deprecate(_upgradedAddress); } // Refleja la cantidad total de monedas generada por el contrato // function totalSupply() public constant returns (uint) { if (deprecated) { return StandardToken(upgradedAddress).totalSupply(); } else { return _totalSupply; } } // Genera nuevas monedas y las deposita en la direccion del creador // // @param _amount Numero de monedas a generar function issue(uint amount) public onlyOwner { require(_totalSupply + amount > _totalSupply); require(balances[owner] + amount > balances[owner]); balances[owner] += amount; _totalSupply += amount; emit Issue(amount); } // Retiro de monedas // Las moendas son retiradas de la cuenta del creador // El balance en la cuenta debe ser suficiente para completar la transaccion de lo contrario se generara un error // @param _amount Nuemro de monedas a retirar function redeem(uint amount) public onlyOwner { require(_totalSupply >= amount); require(balances[owner] >= amount); _totalSupply -= amount; balances[owner] -= amount; emit Redeem(amount); } // Establece el valor de las cuotas en caso de existir // // @param newBasisPoints Cuota base // @param newMaxFee Cuota maxima function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner { // Asegura el valor maximo que no podran sobrepasar las cuotas require(newBasisPoints < 50); require(newMaxFee < 1000); basisPointsRate = newBasisPoints; maximumFee = newMaxFee.mul(10**decimals); emit Params(basisPointsRate, maximumFee); } // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Issue(uint amount); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Redeem(uint amount); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Deprecate(address newAddress); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Params(uint feeBasisPoints, uint maxFee); }
totalSupply
function totalSupply() public constant returns (uint) { if (deprecated) { return StandardToken(upgradedAddress).totalSupply(); } else { return _totalSupply; } }
// Refleja la cantidad total de monedas generada por el contrato //
LineComment
v0.4.23+commit.124ca40d
bzzr://04111d1f568ec95779355af636ec353af628df58bdacfea0d06838231cd882be
{ "func_code_index": [ 4945, 5168 ] }
8,437
MexaCoin
MexaCoin.sol
0xdea8e7d3b9e422073a69615b998b34533b7bf898
Solidity
MexaCoin
contract MexaCoin is Pausable, StandardToken, BlackList { string public name; string public symbol; uint public decimals; address public upgradedAddress; bool public deprecated; // Inicializa el contrato con el suministro inicial de monedas al creador // // @param _initialSupply Suministro inicial de monedas // @param _name Establece el nombre de la moneda // @param _symbol Establece el simbolo de la moneda // @param _decimals Establece el numero de decimales constructor (uint _initialSupply, string _name, string _symbol, uint _decimals) public { _totalSupply = _initialSupply; name = _name; symbol = _symbol; decimals = _decimals; balances[owner] = _initialSupply; deprecated = false; } // Transferencias entre direcciones // Requiere que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _to Direccion a la que se envian las monedas // @param _value Cantidad de monedas a enviar function transfer(address _to, uint _value) public whenNotPaused { require(!isBlackListed[msg.sender]); require(!isBlackListed[_to]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value); } else { return super.transfer(_to, _value); } } // Refleja el balance de una direccion // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param who Direccion a consultar function balanceOf(address who) public constant returns (uint) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).balanceOf(who); } else { return super.balanceOf(who); } } // Transferencias desde direcciones a nombre de terceros (concesiones) // Require que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _from Direccion de la que se envian las monedas // @param _to Direccion a la que se envian las monedas // @param _value Cantidad de monedas a enviar function transferFrom(address _from, address _to, uint _value) public whenNotPaused { require(!isBlackListed[_from]); require(!isBlackListed[_to]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value); } else { return super.transferFrom(_from, _to, _value); } } // Permite genera concesiones a direcciones de terceros especificando la direccion y la cantidad de monedas a conceder // Require que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _spender Direccion a la que se le conceden las monedas // @param _value Cantidad de monedas a conceder function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) whenNotPaused { require(!isBlackListed[msg.sender]); require(!isBlackListed[_spender]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value); } else { return super.approve(_spender, _value); } } // Refleja cantidad de moendas restantes en concesion // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _owner Direccion de quien concede las monedas // @param _spender Direccion que posee la concesion function allowance(address _owner, address _spender) public constant returns (uint remaining) { if (deprecated) { return StandardToken(upgradedAddress).allowance(_owner, _spender); } else { return super.allowance(_owner, _spender); } } // Suspende el actual contrato a favor de uno nuevo // // @param _upgradedAddress Direccion del nuevo contrato function deprecate(address _upgradedAddress) public onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; emit Deprecate(_upgradedAddress); } // Refleja la cantidad total de monedas generada por el contrato // function totalSupply() public constant returns (uint) { if (deprecated) { return StandardToken(upgradedAddress).totalSupply(); } else { return _totalSupply; } } // Genera nuevas monedas y las deposita en la direccion del creador // // @param _amount Numero de monedas a generar function issue(uint amount) public onlyOwner { require(_totalSupply + amount > _totalSupply); require(balances[owner] + amount > balances[owner]); balances[owner] += amount; _totalSupply += amount; emit Issue(amount); } // Retiro de monedas // Las moendas son retiradas de la cuenta del creador // El balance en la cuenta debe ser suficiente para completar la transaccion de lo contrario se generara un error // @param _amount Nuemro de monedas a retirar function redeem(uint amount) public onlyOwner { require(_totalSupply >= amount); require(balances[owner] >= amount); _totalSupply -= amount; balances[owner] -= amount; emit Redeem(amount); } // Establece el valor de las cuotas en caso de existir // // @param newBasisPoints Cuota base // @param newMaxFee Cuota maxima function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner { // Asegura el valor maximo que no podran sobrepasar las cuotas require(newBasisPoints < 50); require(newMaxFee < 1000); basisPointsRate = newBasisPoints; maximumFee = newMaxFee.mul(10**decimals); emit Params(basisPointsRate, maximumFee); } // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Issue(uint amount); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Redeem(uint amount); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Deprecate(address newAddress); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Params(uint feeBasisPoints, uint maxFee); }
issue
function issue(uint amount) public onlyOwner { require(_totalSupply + amount > _totalSupply); require(balances[owner] + amount > balances[owner]); balances[owner] += amount; _totalSupply += amount; emit Issue(amount); }
// Genera nuevas monedas y las deposita en la direccion del creador // // @param _amount Numero de monedas a generar
LineComment
v0.4.23+commit.124ca40d
bzzr://04111d1f568ec95779355af636ec353af628df58bdacfea0d06838231cd882be
{ "func_code_index": [ 5313, 5589 ] }
8,438
MexaCoin
MexaCoin.sol
0xdea8e7d3b9e422073a69615b998b34533b7bf898
Solidity
MexaCoin
contract MexaCoin is Pausable, StandardToken, BlackList { string public name; string public symbol; uint public decimals; address public upgradedAddress; bool public deprecated; // Inicializa el contrato con el suministro inicial de monedas al creador // // @param _initialSupply Suministro inicial de monedas // @param _name Establece el nombre de la moneda // @param _symbol Establece el simbolo de la moneda // @param _decimals Establece el numero de decimales constructor (uint _initialSupply, string _name, string _symbol, uint _decimals) public { _totalSupply = _initialSupply; name = _name; symbol = _symbol; decimals = _decimals; balances[owner] = _initialSupply; deprecated = false; } // Transferencias entre direcciones // Requiere que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _to Direccion a la que se envian las monedas // @param _value Cantidad de monedas a enviar function transfer(address _to, uint _value) public whenNotPaused { require(!isBlackListed[msg.sender]); require(!isBlackListed[_to]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value); } else { return super.transfer(_to, _value); } } // Refleja el balance de una direccion // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param who Direccion a consultar function balanceOf(address who) public constant returns (uint) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).balanceOf(who); } else { return super.balanceOf(who); } } // Transferencias desde direcciones a nombre de terceros (concesiones) // Require que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _from Direccion de la que se envian las monedas // @param _to Direccion a la que se envian las monedas // @param _value Cantidad de monedas a enviar function transferFrom(address _from, address _to, uint _value) public whenNotPaused { require(!isBlackListed[_from]); require(!isBlackListed[_to]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value); } else { return super.transferFrom(_from, _to, _value); } } // Permite genera concesiones a direcciones de terceros especificando la direccion y la cantidad de monedas a conceder // Require que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _spender Direccion a la que se le conceden las monedas // @param _value Cantidad de monedas a conceder function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) whenNotPaused { require(!isBlackListed[msg.sender]); require(!isBlackListed[_spender]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value); } else { return super.approve(_spender, _value); } } // Refleja cantidad de moendas restantes en concesion // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _owner Direccion de quien concede las monedas // @param _spender Direccion que posee la concesion function allowance(address _owner, address _spender) public constant returns (uint remaining) { if (deprecated) { return StandardToken(upgradedAddress).allowance(_owner, _spender); } else { return super.allowance(_owner, _spender); } } // Suspende el actual contrato a favor de uno nuevo // // @param _upgradedAddress Direccion del nuevo contrato function deprecate(address _upgradedAddress) public onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; emit Deprecate(_upgradedAddress); } // Refleja la cantidad total de monedas generada por el contrato // function totalSupply() public constant returns (uint) { if (deprecated) { return StandardToken(upgradedAddress).totalSupply(); } else { return _totalSupply; } } // Genera nuevas monedas y las deposita en la direccion del creador // // @param _amount Numero de monedas a generar function issue(uint amount) public onlyOwner { require(_totalSupply + amount > _totalSupply); require(balances[owner] + amount > balances[owner]); balances[owner] += amount; _totalSupply += amount; emit Issue(amount); } // Retiro de monedas // Las moendas son retiradas de la cuenta del creador // El balance en la cuenta debe ser suficiente para completar la transaccion de lo contrario se generara un error // @param _amount Nuemro de monedas a retirar function redeem(uint amount) public onlyOwner { require(_totalSupply >= amount); require(balances[owner] >= amount); _totalSupply -= amount; balances[owner] -= amount; emit Redeem(amount); } // Establece el valor de las cuotas en caso de existir // // @param newBasisPoints Cuota base // @param newMaxFee Cuota maxima function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner { // Asegura el valor maximo que no podran sobrepasar las cuotas require(newBasisPoints < 50); require(newMaxFee < 1000); basisPointsRate = newBasisPoints; maximumFee = newMaxFee.mul(10**decimals); emit Params(basisPointsRate, maximumFee); } // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Issue(uint amount); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Redeem(uint amount); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Deprecate(address newAddress); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Params(uint feeBasisPoints, uint maxFee); }
redeem
function redeem(uint amount) public onlyOwner { require(_totalSupply >= amount); require(balances[owner] >= amount); _totalSupply -= amount; balances[owner] -= amount; emit Redeem(amount); }
// Retiro de monedas // Las moendas son retiradas de la cuenta del creador // El balance en la cuenta debe ser suficiente para completar la transaccion de lo contrario se generara un error // @param _amount Nuemro de monedas a retirar
LineComment
v0.4.23+commit.124ca40d
bzzr://04111d1f568ec95779355af636ec353af628df58bdacfea0d06838231cd882be
{ "func_code_index": [ 5857, 6104 ] }
8,439
MexaCoin
MexaCoin.sol
0xdea8e7d3b9e422073a69615b998b34533b7bf898
Solidity
MexaCoin
contract MexaCoin is Pausable, StandardToken, BlackList { string public name; string public symbol; uint public decimals; address public upgradedAddress; bool public deprecated; // Inicializa el contrato con el suministro inicial de monedas al creador // // @param _initialSupply Suministro inicial de monedas // @param _name Establece el nombre de la moneda // @param _symbol Establece el simbolo de la moneda // @param _decimals Establece el numero de decimales constructor (uint _initialSupply, string _name, string _symbol, uint _decimals) public { _totalSupply = _initialSupply; name = _name; symbol = _symbol; decimals = _decimals; balances[owner] = _initialSupply; deprecated = false; } // Transferencias entre direcciones // Requiere que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _to Direccion a la que se envian las monedas // @param _value Cantidad de monedas a enviar function transfer(address _to, uint _value) public whenNotPaused { require(!isBlackListed[msg.sender]); require(!isBlackListed[_to]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value); } else { return super.transfer(_to, _value); } } // Refleja el balance de una direccion // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param who Direccion a consultar function balanceOf(address who) public constant returns (uint) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).balanceOf(who); } else { return super.balanceOf(who); } } // Transferencias desde direcciones a nombre de terceros (concesiones) // Require que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _from Direccion de la que se envian las monedas // @param _to Direccion a la que se envian las monedas // @param _value Cantidad de monedas a enviar function transferFrom(address _from, address _to, uint _value) public whenNotPaused { require(!isBlackListed[_from]); require(!isBlackListed[_to]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value); } else { return super.transferFrom(_from, _to, _value); } } // Permite genera concesiones a direcciones de terceros especificando la direccion y la cantidad de monedas a conceder // Require que ni el emisor ni el receptor esten en la lista negra // Suspende actividades cuando el contrato se encuentra en pausa // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _spender Direccion a la que se le conceden las monedas // @param _value Cantidad de monedas a conceder function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) whenNotPaused { require(!isBlackListed[msg.sender]); require(!isBlackListed[_spender]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value); } else { return super.approve(_spender, _value); } } // Refleja cantidad de moendas restantes en concesion // Utiliza ERC20.sol para actualizar el contrato si el actual llega a ser obsoleto // // @param _owner Direccion de quien concede las monedas // @param _spender Direccion que posee la concesion function allowance(address _owner, address _spender) public constant returns (uint remaining) { if (deprecated) { return StandardToken(upgradedAddress).allowance(_owner, _spender); } else { return super.allowance(_owner, _spender); } } // Suspende el actual contrato a favor de uno nuevo // // @param _upgradedAddress Direccion del nuevo contrato function deprecate(address _upgradedAddress) public onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; emit Deprecate(_upgradedAddress); } // Refleja la cantidad total de monedas generada por el contrato // function totalSupply() public constant returns (uint) { if (deprecated) { return StandardToken(upgradedAddress).totalSupply(); } else { return _totalSupply; } } // Genera nuevas monedas y las deposita en la direccion del creador // // @param _amount Numero de monedas a generar function issue(uint amount) public onlyOwner { require(_totalSupply + amount > _totalSupply); require(balances[owner] + amount > balances[owner]); balances[owner] += amount; _totalSupply += amount; emit Issue(amount); } // Retiro de monedas // Las moendas son retiradas de la cuenta del creador // El balance en la cuenta debe ser suficiente para completar la transaccion de lo contrario se generara un error // @param _amount Nuemro de monedas a retirar function redeem(uint amount) public onlyOwner { require(_totalSupply >= amount); require(balances[owner] >= amount); _totalSupply -= amount; balances[owner] -= amount; emit Redeem(amount); } // Establece el valor de las cuotas en caso de existir // // @param newBasisPoints Cuota base // @param newMaxFee Cuota maxima function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner { // Asegura el valor maximo que no podran sobrepasar las cuotas require(newBasisPoints < 50); require(newMaxFee < 1000); basisPointsRate = newBasisPoints; maximumFee = newMaxFee.mul(10**decimals); emit Params(basisPointsRate, maximumFee); } // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Issue(uint amount); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Redeem(uint amount); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Deprecate(address newAddress); // Genera un evento publico en el Blockchain que notificara a los clientes cuando nuevas moendas sean generadas event Params(uint feeBasisPoints, uint maxFee); }
setParams
function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner { // Asegura el valor maximo que no podran sobrepasar las cuotas require(newBasisPoints < 50); require(newMaxFee < 1000); basisPointsRate = newBasisPoints; maximumFee = newMaxFee.mul(10**decimals); emit Params(basisPointsRate, maximumFee); }
// Establece el valor de las cuotas en caso de existir // // @param newBasisPoints Cuota base // @param newMaxFee Cuota maxima
LineComment
v0.4.23+commit.124ca40d
bzzr://04111d1f568ec95779355af636ec353af628df58bdacfea0d06838231cd882be
{ "func_code_index": [ 6269, 6651 ] }
8,440
ratDAO
contracts/ratDAO.sol
0x43a10115280634d788815cd9316df1d07c92e1c5
Solidity
ratDAO
contract ratDAO is ERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint16; using SafeMath for uint8; uint16 private _tokenId; // Team wallet address [] teamWalletList = [ 0x0CC494215f952b7cD96378D803a0D3a6CAb282b0, // Wallet 1 address 0x214Fe0B10F0b2C4ea182F25DDdA95130C250C3e1, // Wallet 2 address 0xcC27e870C2ee553c60f51582433E80D1A4ed79da, // Wallet 3 address 0x1418a130132379b99f6E3871bef9507389b2972C, // Wallet 4 address 0x77fc746a68bFa56812b96f9686495efFF6F39364 // Wallet 5 address ]; mapping (address => uint8) teamWalletPercent; // Mint Counter for Each Wallet mapping (address => uint8) addressFreeMintCountMap; // Up to 2 mapping (address => uint8) addressPreSaleCountMap; // Up to 2 mapping (address => uint8) addressPublicSaleCountMap; // Up to 5 // Minting Limitation uint16 public secretFreeMintLimit = 600; uint16 public normalFreeMintLimit = 400; uint16 public preSaleDiscountLimit = 2000; uint16 public preSaleNormalLimit = 1000; uint16 public totalLimit = 8888; /** * Mint Step flag * 0: freeMint, * 1: preSale - discount, * 2: preSale - normal, * 3: publicSale, * 4: reveal, * 5: paused */ uint8 public mintStep = 0; // Merkle Tree Root bytes32 private merkleRoot; // Mint Price uint public mintPriceDiscount = 0.048 ether; uint public mintPrice = 0.06 ether; // BaseURI (real, placeholder) string private realBaseURI = "https://gateway.pinata.cloud/ipfs/QmWvVa8sUuRuTYLHNXPUVH7CmoDvXx7Ura8gVQBBn3zXcQ/"; string private placeholderBaseURI = "https://ratdao.mypinata.cloud/ipfs/QmabSngCR5cztRiSemNnjXcv9KPtWYuBZ1Rg4ciHKfV4GN/"; uint8 private LIMIT5 = 5; uint8 private LIMIT2 = 2; constructor() ERC721("ratDAO", "RDAO") { teamWalletPercent[teamWalletList[0]] = 29; // Wallet 1 percent teamWalletPercent[teamWalletList[1]] = 29; // Wallet 2 percent teamWalletPercent[teamWalletList[2]] = 20; // Wallet 3 percent teamWalletPercent[teamWalletList[3]] = 10; // Wallet 4 percent teamWalletPercent[teamWalletList[4]] = 12; // Wallet 5 percent } event Mint (address indexed _from, uint8 _mintStep, uint _tokenId, uint _mintPrice, uint8 _mintCount, uint8 _freeMintCount, uint8 _preSaleCount, uint8 _publicSaleCount); event Setting ( uint8 _mintStep, uint256 _mintPrice, uint256 _mintPriceDiscount, uint16 _totalLimit, uint8 _limit5, uint8 _limit2); /** * Override _baseURI * mintStep: 0~3 - Unreveal * 4 - Reveal */ function _baseURI() internal view override returns (string memory) { if (mintStep == 4) // Reveal return realBaseURI; return placeholderBaseURI; } /** * Override tokenURI */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist"); return string(abi.encodePacked(_baseURI(), Strings.toString(tokenId), ".json")); } /** * Address -> leaf for MerkleTree */ function _leaf(address account) private pure returns (bytes32) { return keccak256(abi.encodePacked(account)); } /** * Verify WhiteList using MerkleTree */ function verifyWhitelist(bytes32 leaf, bytes32[] memory proof) private view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == merkleRoot; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeSecret(uint8 _mintCount) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= secretFreeMintLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; secretFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeNormal(uint8 _mintCount, bytes32[] memory _proof) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= normalFreeMintLimit); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; normalFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Presale with WhiteList * mintStep: 1: discount * 2: normal * mintCount: Up to 2 */ function mintPresale(uint8 _mintCount, bytes32[] memory _proof) external payable nonReentrant returns (uint256) { require(_mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressPreSaleCountMap[msg.sender] + _mintCount <= LIMIT2); require(( // Presale 1 mintStep == 1 && (_mintCount <= preSaleDiscountLimit) && (msg.value == (mintPriceDiscount * _mintCount)) ) || ( // Presale 2 mintStep == 2 && (_mintCount <= preSaleNormalLimit) && (msg.value == (mintPrice * _mintCount)) )); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPreSaleCountMap[msg.sender] += _mintCount; if (mintStep == 1) { preSaleDiscountLimit -= _mintCount; } else { preSaleNormalLimit -= _mintCount; } totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Public Sale * mintStep: 3 * mintCount: Up to 5 */ function mintPublic(uint8 _mintCount) external payable nonReentrant returns (uint256) { require(mintStep == 3 && _mintCount > 0 && _mintCount <= LIMIT5); require(msg.sender != address(0)); require(msg.value == (mintPrice * _mintCount)); require(addressPublicSaleCountMap[msg.sender] + _mintCount <= LIMIT5); require(_mintCount <= totalLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPublicSaleCountMap[msg.sender] += _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Set status of mintStep * mintStep: 0 - freeMint, * 1 - preSale 1: discount, * 2 - preSale 2: normal, * 3 - publicSale, * 4 - reveal, * 5 - paused */ function setMintStep(uint8 _mintStep) external onlyOwner returns (uint8) { require(_mintStep >= 0 && _mintStep <= 5); mintStep = _mintStep; emit Setting(mintStep, mintPrice, mintPriceDiscount, totalLimit, LIMIT5, LIMIT2); return mintStep; } // Get Balance function getBalance() external view onlyOwner returns (uint256) { return address(this).balance; } // Withdraw function withdraw() external onlyOwner { require(address(this).balance != 0); uint256 balance = address(this).balance; for (uint8 i = 0; i < teamWalletList.length; i++) { payable(teamWalletList[i]).transfer(balance.div(100).mul(teamWalletPercent[teamWalletList[i]])); } } /// Set Methods function setRealBaseURI(string memory _realBaseURI) external onlyOwner returns (string memory) { realBaseURI = _realBaseURI; return realBaseURI; } function setPlaceholderBaseURI(string memory _placeholderBaseURI) external onlyOwner returns (string memory) { placeholderBaseURI = _placeholderBaseURI; return placeholderBaseURI; } function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner returns (bytes32) { merkleRoot = _merkleRoot; return merkleRoot; } /** * Get TokenList by sender */ function getTokenList(address account) external view returns (uint256[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint256 count = balanceOf(selectedAccount); uint256[] memory tokenIdList = new uint256[](count); if (count == 0) return tokenIdList; uint256 cnt = 0; for (uint256 i = 1; i < (_tokenId + 1); i++) { if (_exists(i) && (ownerOf(i) == selectedAccount)) { tokenIdList[cnt++] = i; } if (cnt == count) break; } return tokenIdList; } /** * Get Setting * 0 : mintStep * 1 : mintPrice * 2 : mintPriceDiscount * 3 : totalLimit * 4 : LIMIT5 * 5 : LIMIT2 */ function getSetting() external view returns (uint256[] memory) { uint256[] memory setting = new uint256[](6); setting[0] = mintStep; setting[1] = mintPrice; setting[2] = mintPriceDiscount; setting[3] = totalLimit; setting[4] = LIMIT5; setting[5] = LIMIT2; return setting; } /** * Get Status by sender * 0 : freeMintCount * 1 : presaleCount * 2 : publicSaleCount */ function getAccountStatus(address account) external view returns (uint8[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint8[] memory status = new uint8[](3); if(balanceOf(selectedAccount) == 0) return status; status[0] = addressFreeMintCountMap[selectedAccount]; status[1] = addressPreSaleCountMap[selectedAccount]; status[2] = addressPublicSaleCountMap[selectedAccount]; return status; } }
/// @title A contract for ratDAO /// @author Phillip /// @notice NFT Minting
NatSpecSingleLine
_baseURI
function _baseURI() internal view override returns (string memory) { if (mintStep == 4) // Reveal return realBaseURI; return placeholderBaseURI; }
/** * Override _baseURI * mintStep: 0~3 - Unreveal * 4 - Reveal */
NatSpecMultiLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 3104, 3301 ] }
8,441
ratDAO
contracts/ratDAO.sol
0x43a10115280634d788815cd9316df1d07c92e1c5
Solidity
ratDAO
contract ratDAO is ERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint16; using SafeMath for uint8; uint16 private _tokenId; // Team wallet address [] teamWalletList = [ 0x0CC494215f952b7cD96378D803a0D3a6CAb282b0, // Wallet 1 address 0x214Fe0B10F0b2C4ea182F25DDdA95130C250C3e1, // Wallet 2 address 0xcC27e870C2ee553c60f51582433E80D1A4ed79da, // Wallet 3 address 0x1418a130132379b99f6E3871bef9507389b2972C, // Wallet 4 address 0x77fc746a68bFa56812b96f9686495efFF6F39364 // Wallet 5 address ]; mapping (address => uint8) teamWalletPercent; // Mint Counter for Each Wallet mapping (address => uint8) addressFreeMintCountMap; // Up to 2 mapping (address => uint8) addressPreSaleCountMap; // Up to 2 mapping (address => uint8) addressPublicSaleCountMap; // Up to 5 // Minting Limitation uint16 public secretFreeMintLimit = 600; uint16 public normalFreeMintLimit = 400; uint16 public preSaleDiscountLimit = 2000; uint16 public preSaleNormalLimit = 1000; uint16 public totalLimit = 8888; /** * Mint Step flag * 0: freeMint, * 1: preSale - discount, * 2: preSale - normal, * 3: publicSale, * 4: reveal, * 5: paused */ uint8 public mintStep = 0; // Merkle Tree Root bytes32 private merkleRoot; // Mint Price uint public mintPriceDiscount = 0.048 ether; uint public mintPrice = 0.06 ether; // BaseURI (real, placeholder) string private realBaseURI = "https://gateway.pinata.cloud/ipfs/QmWvVa8sUuRuTYLHNXPUVH7CmoDvXx7Ura8gVQBBn3zXcQ/"; string private placeholderBaseURI = "https://ratdao.mypinata.cloud/ipfs/QmabSngCR5cztRiSemNnjXcv9KPtWYuBZ1Rg4ciHKfV4GN/"; uint8 private LIMIT5 = 5; uint8 private LIMIT2 = 2; constructor() ERC721("ratDAO", "RDAO") { teamWalletPercent[teamWalletList[0]] = 29; // Wallet 1 percent teamWalletPercent[teamWalletList[1]] = 29; // Wallet 2 percent teamWalletPercent[teamWalletList[2]] = 20; // Wallet 3 percent teamWalletPercent[teamWalletList[3]] = 10; // Wallet 4 percent teamWalletPercent[teamWalletList[4]] = 12; // Wallet 5 percent } event Mint (address indexed _from, uint8 _mintStep, uint _tokenId, uint _mintPrice, uint8 _mintCount, uint8 _freeMintCount, uint8 _preSaleCount, uint8 _publicSaleCount); event Setting ( uint8 _mintStep, uint256 _mintPrice, uint256 _mintPriceDiscount, uint16 _totalLimit, uint8 _limit5, uint8 _limit2); /** * Override _baseURI * mintStep: 0~3 - Unreveal * 4 - Reveal */ function _baseURI() internal view override returns (string memory) { if (mintStep == 4) // Reveal return realBaseURI; return placeholderBaseURI; } /** * Override tokenURI */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist"); return string(abi.encodePacked(_baseURI(), Strings.toString(tokenId), ".json")); } /** * Address -> leaf for MerkleTree */ function _leaf(address account) private pure returns (bytes32) { return keccak256(abi.encodePacked(account)); } /** * Verify WhiteList using MerkleTree */ function verifyWhitelist(bytes32 leaf, bytes32[] memory proof) private view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == merkleRoot; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeSecret(uint8 _mintCount) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= secretFreeMintLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; secretFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeNormal(uint8 _mintCount, bytes32[] memory _proof) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= normalFreeMintLimit); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; normalFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Presale with WhiteList * mintStep: 1: discount * 2: normal * mintCount: Up to 2 */ function mintPresale(uint8 _mintCount, bytes32[] memory _proof) external payable nonReentrant returns (uint256) { require(_mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressPreSaleCountMap[msg.sender] + _mintCount <= LIMIT2); require(( // Presale 1 mintStep == 1 && (_mintCount <= preSaleDiscountLimit) && (msg.value == (mintPriceDiscount * _mintCount)) ) || ( // Presale 2 mintStep == 2 && (_mintCount <= preSaleNormalLimit) && (msg.value == (mintPrice * _mintCount)) )); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPreSaleCountMap[msg.sender] += _mintCount; if (mintStep == 1) { preSaleDiscountLimit -= _mintCount; } else { preSaleNormalLimit -= _mintCount; } totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Public Sale * mintStep: 3 * mintCount: Up to 5 */ function mintPublic(uint8 _mintCount) external payable nonReentrant returns (uint256) { require(mintStep == 3 && _mintCount > 0 && _mintCount <= LIMIT5); require(msg.sender != address(0)); require(msg.value == (mintPrice * _mintCount)); require(addressPublicSaleCountMap[msg.sender] + _mintCount <= LIMIT5); require(_mintCount <= totalLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPublicSaleCountMap[msg.sender] += _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Set status of mintStep * mintStep: 0 - freeMint, * 1 - preSale 1: discount, * 2 - preSale 2: normal, * 3 - publicSale, * 4 - reveal, * 5 - paused */ function setMintStep(uint8 _mintStep) external onlyOwner returns (uint8) { require(_mintStep >= 0 && _mintStep <= 5); mintStep = _mintStep; emit Setting(mintStep, mintPrice, mintPriceDiscount, totalLimit, LIMIT5, LIMIT2); return mintStep; } // Get Balance function getBalance() external view onlyOwner returns (uint256) { return address(this).balance; } // Withdraw function withdraw() external onlyOwner { require(address(this).balance != 0); uint256 balance = address(this).balance; for (uint8 i = 0; i < teamWalletList.length; i++) { payable(teamWalletList[i]).transfer(balance.div(100).mul(teamWalletPercent[teamWalletList[i]])); } } /// Set Methods function setRealBaseURI(string memory _realBaseURI) external onlyOwner returns (string memory) { realBaseURI = _realBaseURI; return realBaseURI; } function setPlaceholderBaseURI(string memory _placeholderBaseURI) external onlyOwner returns (string memory) { placeholderBaseURI = _placeholderBaseURI; return placeholderBaseURI; } function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner returns (bytes32) { merkleRoot = _merkleRoot; return merkleRoot; } /** * Get TokenList by sender */ function getTokenList(address account) external view returns (uint256[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint256 count = balanceOf(selectedAccount); uint256[] memory tokenIdList = new uint256[](count); if (count == 0) return tokenIdList; uint256 cnt = 0; for (uint256 i = 1; i < (_tokenId + 1); i++) { if (_exists(i) && (ownerOf(i) == selectedAccount)) { tokenIdList[cnt++] = i; } if (cnt == count) break; } return tokenIdList; } /** * Get Setting * 0 : mintStep * 1 : mintPrice * 2 : mintPriceDiscount * 3 : totalLimit * 4 : LIMIT5 * 5 : LIMIT2 */ function getSetting() external view returns (uint256[] memory) { uint256[] memory setting = new uint256[](6); setting[0] = mintStep; setting[1] = mintPrice; setting[2] = mintPriceDiscount; setting[3] = totalLimit; setting[4] = LIMIT5; setting[5] = LIMIT2; return setting; } /** * Get Status by sender * 0 : freeMintCount * 1 : presaleCount * 2 : publicSaleCount */ function getAccountStatus(address account) external view returns (uint8[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint8[] memory status = new uint8[](3); if(balanceOf(selectedAccount) == 0) return status; status[0] = addressFreeMintCountMap[selectedAccount]; status[1] = addressPreSaleCountMap[selectedAccount]; status[2] = addressPublicSaleCountMap[selectedAccount]; return status; } }
/// @title A contract for ratDAO /// @author Phillip /// @notice NFT Minting
NatSpecSingleLine
tokenURI
function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist"); return string(abi.encodePacked(_baseURI(), Strings.toString(tokenId), ".json")); }
/** * Override tokenURI */
NatSpecMultiLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 3348, 3591 ] }
8,442
ratDAO
contracts/ratDAO.sol
0x43a10115280634d788815cd9316df1d07c92e1c5
Solidity
ratDAO
contract ratDAO is ERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint16; using SafeMath for uint8; uint16 private _tokenId; // Team wallet address [] teamWalletList = [ 0x0CC494215f952b7cD96378D803a0D3a6CAb282b0, // Wallet 1 address 0x214Fe0B10F0b2C4ea182F25DDdA95130C250C3e1, // Wallet 2 address 0xcC27e870C2ee553c60f51582433E80D1A4ed79da, // Wallet 3 address 0x1418a130132379b99f6E3871bef9507389b2972C, // Wallet 4 address 0x77fc746a68bFa56812b96f9686495efFF6F39364 // Wallet 5 address ]; mapping (address => uint8) teamWalletPercent; // Mint Counter for Each Wallet mapping (address => uint8) addressFreeMintCountMap; // Up to 2 mapping (address => uint8) addressPreSaleCountMap; // Up to 2 mapping (address => uint8) addressPublicSaleCountMap; // Up to 5 // Minting Limitation uint16 public secretFreeMintLimit = 600; uint16 public normalFreeMintLimit = 400; uint16 public preSaleDiscountLimit = 2000; uint16 public preSaleNormalLimit = 1000; uint16 public totalLimit = 8888; /** * Mint Step flag * 0: freeMint, * 1: preSale - discount, * 2: preSale - normal, * 3: publicSale, * 4: reveal, * 5: paused */ uint8 public mintStep = 0; // Merkle Tree Root bytes32 private merkleRoot; // Mint Price uint public mintPriceDiscount = 0.048 ether; uint public mintPrice = 0.06 ether; // BaseURI (real, placeholder) string private realBaseURI = "https://gateway.pinata.cloud/ipfs/QmWvVa8sUuRuTYLHNXPUVH7CmoDvXx7Ura8gVQBBn3zXcQ/"; string private placeholderBaseURI = "https://ratdao.mypinata.cloud/ipfs/QmabSngCR5cztRiSemNnjXcv9KPtWYuBZ1Rg4ciHKfV4GN/"; uint8 private LIMIT5 = 5; uint8 private LIMIT2 = 2; constructor() ERC721("ratDAO", "RDAO") { teamWalletPercent[teamWalletList[0]] = 29; // Wallet 1 percent teamWalletPercent[teamWalletList[1]] = 29; // Wallet 2 percent teamWalletPercent[teamWalletList[2]] = 20; // Wallet 3 percent teamWalletPercent[teamWalletList[3]] = 10; // Wallet 4 percent teamWalletPercent[teamWalletList[4]] = 12; // Wallet 5 percent } event Mint (address indexed _from, uint8 _mintStep, uint _tokenId, uint _mintPrice, uint8 _mintCount, uint8 _freeMintCount, uint8 _preSaleCount, uint8 _publicSaleCount); event Setting ( uint8 _mintStep, uint256 _mintPrice, uint256 _mintPriceDiscount, uint16 _totalLimit, uint8 _limit5, uint8 _limit2); /** * Override _baseURI * mintStep: 0~3 - Unreveal * 4 - Reveal */ function _baseURI() internal view override returns (string memory) { if (mintStep == 4) // Reveal return realBaseURI; return placeholderBaseURI; } /** * Override tokenURI */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist"); return string(abi.encodePacked(_baseURI(), Strings.toString(tokenId), ".json")); } /** * Address -> leaf for MerkleTree */ function _leaf(address account) private pure returns (bytes32) { return keccak256(abi.encodePacked(account)); } /** * Verify WhiteList using MerkleTree */ function verifyWhitelist(bytes32 leaf, bytes32[] memory proof) private view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == merkleRoot; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeSecret(uint8 _mintCount) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= secretFreeMintLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; secretFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeNormal(uint8 _mintCount, bytes32[] memory _proof) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= normalFreeMintLimit); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; normalFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Presale with WhiteList * mintStep: 1: discount * 2: normal * mintCount: Up to 2 */ function mintPresale(uint8 _mintCount, bytes32[] memory _proof) external payable nonReentrant returns (uint256) { require(_mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressPreSaleCountMap[msg.sender] + _mintCount <= LIMIT2); require(( // Presale 1 mintStep == 1 && (_mintCount <= preSaleDiscountLimit) && (msg.value == (mintPriceDiscount * _mintCount)) ) || ( // Presale 2 mintStep == 2 && (_mintCount <= preSaleNormalLimit) && (msg.value == (mintPrice * _mintCount)) )); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPreSaleCountMap[msg.sender] += _mintCount; if (mintStep == 1) { preSaleDiscountLimit -= _mintCount; } else { preSaleNormalLimit -= _mintCount; } totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Public Sale * mintStep: 3 * mintCount: Up to 5 */ function mintPublic(uint8 _mintCount) external payable nonReentrant returns (uint256) { require(mintStep == 3 && _mintCount > 0 && _mintCount <= LIMIT5); require(msg.sender != address(0)); require(msg.value == (mintPrice * _mintCount)); require(addressPublicSaleCountMap[msg.sender] + _mintCount <= LIMIT5); require(_mintCount <= totalLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPublicSaleCountMap[msg.sender] += _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Set status of mintStep * mintStep: 0 - freeMint, * 1 - preSale 1: discount, * 2 - preSale 2: normal, * 3 - publicSale, * 4 - reveal, * 5 - paused */ function setMintStep(uint8 _mintStep) external onlyOwner returns (uint8) { require(_mintStep >= 0 && _mintStep <= 5); mintStep = _mintStep; emit Setting(mintStep, mintPrice, mintPriceDiscount, totalLimit, LIMIT5, LIMIT2); return mintStep; } // Get Balance function getBalance() external view onlyOwner returns (uint256) { return address(this).balance; } // Withdraw function withdraw() external onlyOwner { require(address(this).balance != 0); uint256 balance = address(this).balance; for (uint8 i = 0; i < teamWalletList.length; i++) { payable(teamWalletList[i]).transfer(balance.div(100).mul(teamWalletPercent[teamWalletList[i]])); } } /// Set Methods function setRealBaseURI(string memory _realBaseURI) external onlyOwner returns (string memory) { realBaseURI = _realBaseURI; return realBaseURI; } function setPlaceholderBaseURI(string memory _placeholderBaseURI) external onlyOwner returns (string memory) { placeholderBaseURI = _placeholderBaseURI; return placeholderBaseURI; } function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner returns (bytes32) { merkleRoot = _merkleRoot; return merkleRoot; } /** * Get TokenList by sender */ function getTokenList(address account) external view returns (uint256[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint256 count = balanceOf(selectedAccount); uint256[] memory tokenIdList = new uint256[](count); if (count == 0) return tokenIdList; uint256 cnt = 0; for (uint256 i = 1; i < (_tokenId + 1); i++) { if (_exists(i) && (ownerOf(i) == selectedAccount)) { tokenIdList[cnt++] = i; } if (cnt == count) break; } return tokenIdList; } /** * Get Setting * 0 : mintStep * 1 : mintPrice * 2 : mintPriceDiscount * 3 : totalLimit * 4 : LIMIT5 * 5 : LIMIT2 */ function getSetting() external view returns (uint256[] memory) { uint256[] memory setting = new uint256[](6); setting[0] = mintStep; setting[1] = mintPrice; setting[2] = mintPriceDiscount; setting[3] = totalLimit; setting[4] = LIMIT5; setting[5] = LIMIT2; return setting; } /** * Get Status by sender * 0 : freeMintCount * 1 : presaleCount * 2 : publicSaleCount */ function getAccountStatus(address account) external view returns (uint8[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint8[] memory status = new uint8[](3); if(balanceOf(selectedAccount) == 0) return status; status[0] = addressFreeMintCountMap[selectedAccount]; status[1] = addressPreSaleCountMap[selectedAccount]; status[2] = addressPublicSaleCountMap[selectedAccount]; return status; } }
/// @title A contract for ratDAO /// @author Phillip /// @notice NFT Minting
NatSpecSingleLine
_leaf
function _leaf(address account) private pure returns (bytes32) { return keccak256(abi.encodePacked(account)); }
/** * Address -> leaf for MerkleTree */
NatSpecMultiLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 3651, 3781 ] }
8,443
ratDAO
contracts/ratDAO.sol
0x43a10115280634d788815cd9316df1d07c92e1c5
Solidity
ratDAO
contract ratDAO is ERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint16; using SafeMath for uint8; uint16 private _tokenId; // Team wallet address [] teamWalletList = [ 0x0CC494215f952b7cD96378D803a0D3a6CAb282b0, // Wallet 1 address 0x214Fe0B10F0b2C4ea182F25DDdA95130C250C3e1, // Wallet 2 address 0xcC27e870C2ee553c60f51582433E80D1A4ed79da, // Wallet 3 address 0x1418a130132379b99f6E3871bef9507389b2972C, // Wallet 4 address 0x77fc746a68bFa56812b96f9686495efFF6F39364 // Wallet 5 address ]; mapping (address => uint8) teamWalletPercent; // Mint Counter for Each Wallet mapping (address => uint8) addressFreeMintCountMap; // Up to 2 mapping (address => uint8) addressPreSaleCountMap; // Up to 2 mapping (address => uint8) addressPublicSaleCountMap; // Up to 5 // Minting Limitation uint16 public secretFreeMintLimit = 600; uint16 public normalFreeMintLimit = 400; uint16 public preSaleDiscountLimit = 2000; uint16 public preSaleNormalLimit = 1000; uint16 public totalLimit = 8888; /** * Mint Step flag * 0: freeMint, * 1: preSale - discount, * 2: preSale - normal, * 3: publicSale, * 4: reveal, * 5: paused */ uint8 public mintStep = 0; // Merkle Tree Root bytes32 private merkleRoot; // Mint Price uint public mintPriceDiscount = 0.048 ether; uint public mintPrice = 0.06 ether; // BaseURI (real, placeholder) string private realBaseURI = "https://gateway.pinata.cloud/ipfs/QmWvVa8sUuRuTYLHNXPUVH7CmoDvXx7Ura8gVQBBn3zXcQ/"; string private placeholderBaseURI = "https://ratdao.mypinata.cloud/ipfs/QmabSngCR5cztRiSemNnjXcv9KPtWYuBZ1Rg4ciHKfV4GN/"; uint8 private LIMIT5 = 5; uint8 private LIMIT2 = 2; constructor() ERC721("ratDAO", "RDAO") { teamWalletPercent[teamWalletList[0]] = 29; // Wallet 1 percent teamWalletPercent[teamWalletList[1]] = 29; // Wallet 2 percent teamWalletPercent[teamWalletList[2]] = 20; // Wallet 3 percent teamWalletPercent[teamWalletList[3]] = 10; // Wallet 4 percent teamWalletPercent[teamWalletList[4]] = 12; // Wallet 5 percent } event Mint (address indexed _from, uint8 _mintStep, uint _tokenId, uint _mintPrice, uint8 _mintCount, uint8 _freeMintCount, uint8 _preSaleCount, uint8 _publicSaleCount); event Setting ( uint8 _mintStep, uint256 _mintPrice, uint256 _mintPriceDiscount, uint16 _totalLimit, uint8 _limit5, uint8 _limit2); /** * Override _baseURI * mintStep: 0~3 - Unreveal * 4 - Reveal */ function _baseURI() internal view override returns (string memory) { if (mintStep == 4) // Reveal return realBaseURI; return placeholderBaseURI; } /** * Override tokenURI */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist"); return string(abi.encodePacked(_baseURI(), Strings.toString(tokenId), ".json")); } /** * Address -> leaf for MerkleTree */ function _leaf(address account) private pure returns (bytes32) { return keccak256(abi.encodePacked(account)); } /** * Verify WhiteList using MerkleTree */ function verifyWhitelist(bytes32 leaf, bytes32[] memory proof) private view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == merkleRoot; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeSecret(uint8 _mintCount) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= secretFreeMintLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; secretFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeNormal(uint8 _mintCount, bytes32[] memory _proof) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= normalFreeMintLimit); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; normalFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Presale with WhiteList * mintStep: 1: discount * 2: normal * mintCount: Up to 2 */ function mintPresale(uint8 _mintCount, bytes32[] memory _proof) external payable nonReentrant returns (uint256) { require(_mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressPreSaleCountMap[msg.sender] + _mintCount <= LIMIT2); require(( // Presale 1 mintStep == 1 && (_mintCount <= preSaleDiscountLimit) && (msg.value == (mintPriceDiscount * _mintCount)) ) || ( // Presale 2 mintStep == 2 && (_mintCount <= preSaleNormalLimit) && (msg.value == (mintPrice * _mintCount)) )); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPreSaleCountMap[msg.sender] += _mintCount; if (mintStep == 1) { preSaleDiscountLimit -= _mintCount; } else { preSaleNormalLimit -= _mintCount; } totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Public Sale * mintStep: 3 * mintCount: Up to 5 */ function mintPublic(uint8 _mintCount) external payable nonReentrant returns (uint256) { require(mintStep == 3 && _mintCount > 0 && _mintCount <= LIMIT5); require(msg.sender != address(0)); require(msg.value == (mintPrice * _mintCount)); require(addressPublicSaleCountMap[msg.sender] + _mintCount <= LIMIT5); require(_mintCount <= totalLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPublicSaleCountMap[msg.sender] += _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Set status of mintStep * mintStep: 0 - freeMint, * 1 - preSale 1: discount, * 2 - preSale 2: normal, * 3 - publicSale, * 4 - reveal, * 5 - paused */ function setMintStep(uint8 _mintStep) external onlyOwner returns (uint8) { require(_mintStep >= 0 && _mintStep <= 5); mintStep = _mintStep; emit Setting(mintStep, mintPrice, mintPriceDiscount, totalLimit, LIMIT5, LIMIT2); return mintStep; } // Get Balance function getBalance() external view onlyOwner returns (uint256) { return address(this).balance; } // Withdraw function withdraw() external onlyOwner { require(address(this).balance != 0); uint256 balance = address(this).balance; for (uint8 i = 0; i < teamWalletList.length; i++) { payable(teamWalletList[i]).transfer(balance.div(100).mul(teamWalletPercent[teamWalletList[i]])); } } /// Set Methods function setRealBaseURI(string memory _realBaseURI) external onlyOwner returns (string memory) { realBaseURI = _realBaseURI; return realBaseURI; } function setPlaceholderBaseURI(string memory _placeholderBaseURI) external onlyOwner returns (string memory) { placeholderBaseURI = _placeholderBaseURI; return placeholderBaseURI; } function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner returns (bytes32) { merkleRoot = _merkleRoot; return merkleRoot; } /** * Get TokenList by sender */ function getTokenList(address account) external view returns (uint256[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint256 count = balanceOf(selectedAccount); uint256[] memory tokenIdList = new uint256[](count); if (count == 0) return tokenIdList; uint256 cnt = 0; for (uint256 i = 1; i < (_tokenId + 1); i++) { if (_exists(i) && (ownerOf(i) == selectedAccount)) { tokenIdList[cnt++] = i; } if (cnt == count) break; } return tokenIdList; } /** * Get Setting * 0 : mintStep * 1 : mintPrice * 2 : mintPriceDiscount * 3 : totalLimit * 4 : LIMIT5 * 5 : LIMIT2 */ function getSetting() external view returns (uint256[] memory) { uint256[] memory setting = new uint256[](6); setting[0] = mintStep; setting[1] = mintPrice; setting[2] = mintPriceDiscount; setting[3] = totalLimit; setting[4] = LIMIT5; setting[5] = LIMIT2; return setting; } /** * Get Status by sender * 0 : freeMintCount * 1 : presaleCount * 2 : publicSaleCount */ function getAccountStatus(address account) external view returns (uint8[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint8[] memory status = new uint8[](3); if(balanceOf(selectedAccount) == 0) return status; status[0] = addressFreeMintCountMap[selectedAccount]; status[1] = addressPreSaleCountMap[selectedAccount]; status[2] = addressPublicSaleCountMap[selectedAccount]; return status; } }
/// @title A contract for ratDAO /// @author Phillip /// @notice NFT Minting
NatSpecSingleLine
verifyWhitelist
function verifyWhitelist(bytes32 leaf, bytes32[] memory proof) private view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == merkleRoot; }
/** * Verify WhiteList using MerkleTree */
NatSpecMultiLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 3844, 4644 ] }
8,444
ratDAO
contracts/ratDAO.sol
0x43a10115280634d788815cd9316df1d07c92e1c5
Solidity
ratDAO
contract ratDAO is ERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint16; using SafeMath for uint8; uint16 private _tokenId; // Team wallet address [] teamWalletList = [ 0x0CC494215f952b7cD96378D803a0D3a6CAb282b0, // Wallet 1 address 0x214Fe0B10F0b2C4ea182F25DDdA95130C250C3e1, // Wallet 2 address 0xcC27e870C2ee553c60f51582433E80D1A4ed79da, // Wallet 3 address 0x1418a130132379b99f6E3871bef9507389b2972C, // Wallet 4 address 0x77fc746a68bFa56812b96f9686495efFF6F39364 // Wallet 5 address ]; mapping (address => uint8) teamWalletPercent; // Mint Counter for Each Wallet mapping (address => uint8) addressFreeMintCountMap; // Up to 2 mapping (address => uint8) addressPreSaleCountMap; // Up to 2 mapping (address => uint8) addressPublicSaleCountMap; // Up to 5 // Minting Limitation uint16 public secretFreeMintLimit = 600; uint16 public normalFreeMintLimit = 400; uint16 public preSaleDiscountLimit = 2000; uint16 public preSaleNormalLimit = 1000; uint16 public totalLimit = 8888; /** * Mint Step flag * 0: freeMint, * 1: preSale - discount, * 2: preSale - normal, * 3: publicSale, * 4: reveal, * 5: paused */ uint8 public mintStep = 0; // Merkle Tree Root bytes32 private merkleRoot; // Mint Price uint public mintPriceDiscount = 0.048 ether; uint public mintPrice = 0.06 ether; // BaseURI (real, placeholder) string private realBaseURI = "https://gateway.pinata.cloud/ipfs/QmWvVa8sUuRuTYLHNXPUVH7CmoDvXx7Ura8gVQBBn3zXcQ/"; string private placeholderBaseURI = "https://ratdao.mypinata.cloud/ipfs/QmabSngCR5cztRiSemNnjXcv9KPtWYuBZ1Rg4ciHKfV4GN/"; uint8 private LIMIT5 = 5; uint8 private LIMIT2 = 2; constructor() ERC721("ratDAO", "RDAO") { teamWalletPercent[teamWalletList[0]] = 29; // Wallet 1 percent teamWalletPercent[teamWalletList[1]] = 29; // Wallet 2 percent teamWalletPercent[teamWalletList[2]] = 20; // Wallet 3 percent teamWalletPercent[teamWalletList[3]] = 10; // Wallet 4 percent teamWalletPercent[teamWalletList[4]] = 12; // Wallet 5 percent } event Mint (address indexed _from, uint8 _mintStep, uint _tokenId, uint _mintPrice, uint8 _mintCount, uint8 _freeMintCount, uint8 _preSaleCount, uint8 _publicSaleCount); event Setting ( uint8 _mintStep, uint256 _mintPrice, uint256 _mintPriceDiscount, uint16 _totalLimit, uint8 _limit5, uint8 _limit2); /** * Override _baseURI * mintStep: 0~3 - Unreveal * 4 - Reveal */ function _baseURI() internal view override returns (string memory) { if (mintStep == 4) // Reveal return realBaseURI; return placeholderBaseURI; } /** * Override tokenURI */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist"); return string(abi.encodePacked(_baseURI(), Strings.toString(tokenId), ".json")); } /** * Address -> leaf for MerkleTree */ function _leaf(address account) private pure returns (bytes32) { return keccak256(abi.encodePacked(account)); } /** * Verify WhiteList using MerkleTree */ function verifyWhitelist(bytes32 leaf, bytes32[] memory proof) private view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == merkleRoot; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeSecret(uint8 _mintCount) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= secretFreeMintLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; secretFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeNormal(uint8 _mintCount, bytes32[] memory _proof) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= normalFreeMintLimit); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; normalFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Presale with WhiteList * mintStep: 1: discount * 2: normal * mintCount: Up to 2 */ function mintPresale(uint8 _mintCount, bytes32[] memory _proof) external payable nonReentrant returns (uint256) { require(_mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressPreSaleCountMap[msg.sender] + _mintCount <= LIMIT2); require(( // Presale 1 mintStep == 1 && (_mintCount <= preSaleDiscountLimit) && (msg.value == (mintPriceDiscount * _mintCount)) ) || ( // Presale 2 mintStep == 2 && (_mintCount <= preSaleNormalLimit) && (msg.value == (mintPrice * _mintCount)) )); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPreSaleCountMap[msg.sender] += _mintCount; if (mintStep == 1) { preSaleDiscountLimit -= _mintCount; } else { preSaleNormalLimit -= _mintCount; } totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Public Sale * mintStep: 3 * mintCount: Up to 5 */ function mintPublic(uint8 _mintCount) external payable nonReentrant returns (uint256) { require(mintStep == 3 && _mintCount > 0 && _mintCount <= LIMIT5); require(msg.sender != address(0)); require(msg.value == (mintPrice * _mintCount)); require(addressPublicSaleCountMap[msg.sender] + _mintCount <= LIMIT5); require(_mintCount <= totalLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPublicSaleCountMap[msg.sender] += _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Set status of mintStep * mintStep: 0 - freeMint, * 1 - preSale 1: discount, * 2 - preSale 2: normal, * 3 - publicSale, * 4 - reveal, * 5 - paused */ function setMintStep(uint8 _mintStep) external onlyOwner returns (uint8) { require(_mintStep >= 0 && _mintStep <= 5); mintStep = _mintStep; emit Setting(mintStep, mintPrice, mintPriceDiscount, totalLimit, LIMIT5, LIMIT2); return mintStep; } // Get Balance function getBalance() external view onlyOwner returns (uint256) { return address(this).balance; } // Withdraw function withdraw() external onlyOwner { require(address(this).balance != 0); uint256 balance = address(this).balance; for (uint8 i = 0; i < teamWalletList.length; i++) { payable(teamWalletList[i]).transfer(balance.div(100).mul(teamWalletPercent[teamWalletList[i]])); } } /// Set Methods function setRealBaseURI(string memory _realBaseURI) external onlyOwner returns (string memory) { realBaseURI = _realBaseURI; return realBaseURI; } function setPlaceholderBaseURI(string memory _placeholderBaseURI) external onlyOwner returns (string memory) { placeholderBaseURI = _placeholderBaseURI; return placeholderBaseURI; } function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner returns (bytes32) { merkleRoot = _merkleRoot; return merkleRoot; } /** * Get TokenList by sender */ function getTokenList(address account) external view returns (uint256[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint256 count = balanceOf(selectedAccount); uint256[] memory tokenIdList = new uint256[](count); if (count == 0) return tokenIdList; uint256 cnt = 0; for (uint256 i = 1; i < (_tokenId + 1); i++) { if (_exists(i) && (ownerOf(i) == selectedAccount)) { tokenIdList[cnt++] = i; } if (cnt == count) break; } return tokenIdList; } /** * Get Setting * 0 : mintStep * 1 : mintPrice * 2 : mintPriceDiscount * 3 : totalLimit * 4 : LIMIT5 * 5 : LIMIT2 */ function getSetting() external view returns (uint256[] memory) { uint256[] memory setting = new uint256[](6); setting[0] = mintStep; setting[1] = mintPrice; setting[2] = mintPriceDiscount; setting[3] = totalLimit; setting[4] = LIMIT5; setting[5] = LIMIT2; return setting; } /** * Get Status by sender * 0 : freeMintCount * 1 : presaleCount * 2 : publicSaleCount */ function getAccountStatus(address account) external view returns (uint8[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint8[] memory status = new uint8[](3); if(balanceOf(selectedAccount) == 0) return status; status[0] = addressFreeMintCountMap[selectedAccount]; status[1] = addressPreSaleCountMap[selectedAccount]; status[2] = addressPublicSaleCountMap[selectedAccount]; return status; } }
/// @title A contract for ratDAO /// @author Phillip /// @notice NFT Minting
NatSpecSingleLine
mintFreeSecret
function mintFreeSecret(uint8 _mintCount) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= secretFreeMintLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; secretFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; }
/** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */
NatSpecMultiLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 4742, 5752 ] }
8,445
ratDAO
contracts/ratDAO.sol
0x43a10115280634d788815cd9316df1d07c92e1c5
Solidity
ratDAO
contract ratDAO is ERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint16; using SafeMath for uint8; uint16 private _tokenId; // Team wallet address [] teamWalletList = [ 0x0CC494215f952b7cD96378D803a0D3a6CAb282b0, // Wallet 1 address 0x214Fe0B10F0b2C4ea182F25DDdA95130C250C3e1, // Wallet 2 address 0xcC27e870C2ee553c60f51582433E80D1A4ed79da, // Wallet 3 address 0x1418a130132379b99f6E3871bef9507389b2972C, // Wallet 4 address 0x77fc746a68bFa56812b96f9686495efFF6F39364 // Wallet 5 address ]; mapping (address => uint8) teamWalletPercent; // Mint Counter for Each Wallet mapping (address => uint8) addressFreeMintCountMap; // Up to 2 mapping (address => uint8) addressPreSaleCountMap; // Up to 2 mapping (address => uint8) addressPublicSaleCountMap; // Up to 5 // Minting Limitation uint16 public secretFreeMintLimit = 600; uint16 public normalFreeMintLimit = 400; uint16 public preSaleDiscountLimit = 2000; uint16 public preSaleNormalLimit = 1000; uint16 public totalLimit = 8888; /** * Mint Step flag * 0: freeMint, * 1: preSale - discount, * 2: preSale - normal, * 3: publicSale, * 4: reveal, * 5: paused */ uint8 public mintStep = 0; // Merkle Tree Root bytes32 private merkleRoot; // Mint Price uint public mintPriceDiscount = 0.048 ether; uint public mintPrice = 0.06 ether; // BaseURI (real, placeholder) string private realBaseURI = "https://gateway.pinata.cloud/ipfs/QmWvVa8sUuRuTYLHNXPUVH7CmoDvXx7Ura8gVQBBn3zXcQ/"; string private placeholderBaseURI = "https://ratdao.mypinata.cloud/ipfs/QmabSngCR5cztRiSemNnjXcv9KPtWYuBZ1Rg4ciHKfV4GN/"; uint8 private LIMIT5 = 5; uint8 private LIMIT2 = 2; constructor() ERC721("ratDAO", "RDAO") { teamWalletPercent[teamWalletList[0]] = 29; // Wallet 1 percent teamWalletPercent[teamWalletList[1]] = 29; // Wallet 2 percent teamWalletPercent[teamWalletList[2]] = 20; // Wallet 3 percent teamWalletPercent[teamWalletList[3]] = 10; // Wallet 4 percent teamWalletPercent[teamWalletList[4]] = 12; // Wallet 5 percent } event Mint (address indexed _from, uint8 _mintStep, uint _tokenId, uint _mintPrice, uint8 _mintCount, uint8 _freeMintCount, uint8 _preSaleCount, uint8 _publicSaleCount); event Setting ( uint8 _mintStep, uint256 _mintPrice, uint256 _mintPriceDiscount, uint16 _totalLimit, uint8 _limit5, uint8 _limit2); /** * Override _baseURI * mintStep: 0~3 - Unreveal * 4 - Reveal */ function _baseURI() internal view override returns (string memory) { if (mintStep == 4) // Reveal return realBaseURI; return placeholderBaseURI; } /** * Override tokenURI */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist"); return string(abi.encodePacked(_baseURI(), Strings.toString(tokenId), ".json")); } /** * Address -> leaf for MerkleTree */ function _leaf(address account) private pure returns (bytes32) { return keccak256(abi.encodePacked(account)); } /** * Verify WhiteList using MerkleTree */ function verifyWhitelist(bytes32 leaf, bytes32[] memory proof) private view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == merkleRoot; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeSecret(uint8 _mintCount) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= secretFreeMintLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; secretFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeNormal(uint8 _mintCount, bytes32[] memory _proof) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= normalFreeMintLimit); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; normalFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Presale with WhiteList * mintStep: 1: discount * 2: normal * mintCount: Up to 2 */ function mintPresale(uint8 _mintCount, bytes32[] memory _proof) external payable nonReentrant returns (uint256) { require(_mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressPreSaleCountMap[msg.sender] + _mintCount <= LIMIT2); require(( // Presale 1 mintStep == 1 && (_mintCount <= preSaleDiscountLimit) && (msg.value == (mintPriceDiscount * _mintCount)) ) || ( // Presale 2 mintStep == 2 && (_mintCount <= preSaleNormalLimit) && (msg.value == (mintPrice * _mintCount)) )); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPreSaleCountMap[msg.sender] += _mintCount; if (mintStep == 1) { preSaleDiscountLimit -= _mintCount; } else { preSaleNormalLimit -= _mintCount; } totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Public Sale * mintStep: 3 * mintCount: Up to 5 */ function mintPublic(uint8 _mintCount) external payable nonReentrant returns (uint256) { require(mintStep == 3 && _mintCount > 0 && _mintCount <= LIMIT5); require(msg.sender != address(0)); require(msg.value == (mintPrice * _mintCount)); require(addressPublicSaleCountMap[msg.sender] + _mintCount <= LIMIT5); require(_mintCount <= totalLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPublicSaleCountMap[msg.sender] += _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Set status of mintStep * mintStep: 0 - freeMint, * 1 - preSale 1: discount, * 2 - preSale 2: normal, * 3 - publicSale, * 4 - reveal, * 5 - paused */ function setMintStep(uint8 _mintStep) external onlyOwner returns (uint8) { require(_mintStep >= 0 && _mintStep <= 5); mintStep = _mintStep; emit Setting(mintStep, mintPrice, mintPriceDiscount, totalLimit, LIMIT5, LIMIT2); return mintStep; } // Get Balance function getBalance() external view onlyOwner returns (uint256) { return address(this).balance; } // Withdraw function withdraw() external onlyOwner { require(address(this).balance != 0); uint256 balance = address(this).balance; for (uint8 i = 0; i < teamWalletList.length; i++) { payable(teamWalletList[i]).transfer(balance.div(100).mul(teamWalletPercent[teamWalletList[i]])); } } /// Set Methods function setRealBaseURI(string memory _realBaseURI) external onlyOwner returns (string memory) { realBaseURI = _realBaseURI; return realBaseURI; } function setPlaceholderBaseURI(string memory _placeholderBaseURI) external onlyOwner returns (string memory) { placeholderBaseURI = _placeholderBaseURI; return placeholderBaseURI; } function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner returns (bytes32) { merkleRoot = _merkleRoot; return merkleRoot; } /** * Get TokenList by sender */ function getTokenList(address account) external view returns (uint256[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint256 count = balanceOf(selectedAccount); uint256[] memory tokenIdList = new uint256[](count); if (count == 0) return tokenIdList; uint256 cnt = 0; for (uint256 i = 1; i < (_tokenId + 1); i++) { if (_exists(i) && (ownerOf(i) == selectedAccount)) { tokenIdList[cnt++] = i; } if (cnt == count) break; } return tokenIdList; } /** * Get Setting * 0 : mintStep * 1 : mintPrice * 2 : mintPriceDiscount * 3 : totalLimit * 4 : LIMIT5 * 5 : LIMIT2 */ function getSetting() external view returns (uint256[] memory) { uint256[] memory setting = new uint256[](6); setting[0] = mintStep; setting[1] = mintPrice; setting[2] = mintPriceDiscount; setting[3] = totalLimit; setting[4] = LIMIT5; setting[5] = LIMIT2; return setting; } /** * Get Status by sender * 0 : freeMintCount * 1 : presaleCount * 2 : publicSaleCount */ function getAccountStatus(address account) external view returns (uint8[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint8[] memory status = new uint8[](3); if(balanceOf(selectedAccount) == 0) return status; status[0] = addressFreeMintCountMap[selectedAccount]; status[1] = addressPreSaleCountMap[selectedAccount]; status[2] = addressPublicSaleCountMap[selectedAccount]; return status; } }
/// @title A contract for ratDAO /// @author Phillip /// @notice NFT Minting
NatSpecSingleLine
mintFreeNormal
function mintFreeNormal(uint8 _mintCount, bytes32[] memory _proof) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= normalFreeMintLimit); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; normalFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; }
/** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */
NatSpecMultiLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 5850, 6948 ] }
8,446
ratDAO
contracts/ratDAO.sol
0x43a10115280634d788815cd9316df1d07c92e1c5
Solidity
ratDAO
contract ratDAO is ERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint16; using SafeMath for uint8; uint16 private _tokenId; // Team wallet address [] teamWalletList = [ 0x0CC494215f952b7cD96378D803a0D3a6CAb282b0, // Wallet 1 address 0x214Fe0B10F0b2C4ea182F25DDdA95130C250C3e1, // Wallet 2 address 0xcC27e870C2ee553c60f51582433E80D1A4ed79da, // Wallet 3 address 0x1418a130132379b99f6E3871bef9507389b2972C, // Wallet 4 address 0x77fc746a68bFa56812b96f9686495efFF6F39364 // Wallet 5 address ]; mapping (address => uint8) teamWalletPercent; // Mint Counter for Each Wallet mapping (address => uint8) addressFreeMintCountMap; // Up to 2 mapping (address => uint8) addressPreSaleCountMap; // Up to 2 mapping (address => uint8) addressPublicSaleCountMap; // Up to 5 // Minting Limitation uint16 public secretFreeMintLimit = 600; uint16 public normalFreeMintLimit = 400; uint16 public preSaleDiscountLimit = 2000; uint16 public preSaleNormalLimit = 1000; uint16 public totalLimit = 8888; /** * Mint Step flag * 0: freeMint, * 1: preSale - discount, * 2: preSale - normal, * 3: publicSale, * 4: reveal, * 5: paused */ uint8 public mintStep = 0; // Merkle Tree Root bytes32 private merkleRoot; // Mint Price uint public mintPriceDiscount = 0.048 ether; uint public mintPrice = 0.06 ether; // BaseURI (real, placeholder) string private realBaseURI = "https://gateway.pinata.cloud/ipfs/QmWvVa8sUuRuTYLHNXPUVH7CmoDvXx7Ura8gVQBBn3zXcQ/"; string private placeholderBaseURI = "https://ratdao.mypinata.cloud/ipfs/QmabSngCR5cztRiSemNnjXcv9KPtWYuBZ1Rg4ciHKfV4GN/"; uint8 private LIMIT5 = 5; uint8 private LIMIT2 = 2; constructor() ERC721("ratDAO", "RDAO") { teamWalletPercent[teamWalletList[0]] = 29; // Wallet 1 percent teamWalletPercent[teamWalletList[1]] = 29; // Wallet 2 percent teamWalletPercent[teamWalletList[2]] = 20; // Wallet 3 percent teamWalletPercent[teamWalletList[3]] = 10; // Wallet 4 percent teamWalletPercent[teamWalletList[4]] = 12; // Wallet 5 percent } event Mint (address indexed _from, uint8 _mintStep, uint _tokenId, uint _mintPrice, uint8 _mintCount, uint8 _freeMintCount, uint8 _preSaleCount, uint8 _publicSaleCount); event Setting ( uint8 _mintStep, uint256 _mintPrice, uint256 _mintPriceDiscount, uint16 _totalLimit, uint8 _limit5, uint8 _limit2); /** * Override _baseURI * mintStep: 0~3 - Unreveal * 4 - Reveal */ function _baseURI() internal view override returns (string memory) { if (mintStep == 4) // Reveal return realBaseURI; return placeholderBaseURI; } /** * Override tokenURI */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist"); return string(abi.encodePacked(_baseURI(), Strings.toString(tokenId), ".json")); } /** * Address -> leaf for MerkleTree */ function _leaf(address account) private pure returns (bytes32) { return keccak256(abi.encodePacked(account)); } /** * Verify WhiteList using MerkleTree */ function verifyWhitelist(bytes32 leaf, bytes32[] memory proof) private view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == merkleRoot; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeSecret(uint8 _mintCount) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= secretFreeMintLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; secretFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeNormal(uint8 _mintCount, bytes32[] memory _proof) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= normalFreeMintLimit); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; normalFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Presale with WhiteList * mintStep: 1: discount * 2: normal * mintCount: Up to 2 */ function mintPresale(uint8 _mintCount, bytes32[] memory _proof) external payable nonReentrant returns (uint256) { require(_mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressPreSaleCountMap[msg.sender] + _mintCount <= LIMIT2); require(( // Presale 1 mintStep == 1 && (_mintCount <= preSaleDiscountLimit) && (msg.value == (mintPriceDiscount * _mintCount)) ) || ( // Presale 2 mintStep == 2 && (_mintCount <= preSaleNormalLimit) && (msg.value == (mintPrice * _mintCount)) )); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPreSaleCountMap[msg.sender] += _mintCount; if (mintStep == 1) { preSaleDiscountLimit -= _mintCount; } else { preSaleNormalLimit -= _mintCount; } totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Public Sale * mintStep: 3 * mintCount: Up to 5 */ function mintPublic(uint8 _mintCount) external payable nonReentrant returns (uint256) { require(mintStep == 3 && _mintCount > 0 && _mintCount <= LIMIT5); require(msg.sender != address(0)); require(msg.value == (mintPrice * _mintCount)); require(addressPublicSaleCountMap[msg.sender] + _mintCount <= LIMIT5); require(_mintCount <= totalLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPublicSaleCountMap[msg.sender] += _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Set status of mintStep * mintStep: 0 - freeMint, * 1 - preSale 1: discount, * 2 - preSale 2: normal, * 3 - publicSale, * 4 - reveal, * 5 - paused */ function setMintStep(uint8 _mintStep) external onlyOwner returns (uint8) { require(_mintStep >= 0 && _mintStep <= 5); mintStep = _mintStep; emit Setting(mintStep, mintPrice, mintPriceDiscount, totalLimit, LIMIT5, LIMIT2); return mintStep; } // Get Balance function getBalance() external view onlyOwner returns (uint256) { return address(this).balance; } // Withdraw function withdraw() external onlyOwner { require(address(this).balance != 0); uint256 balance = address(this).balance; for (uint8 i = 0; i < teamWalletList.length; i++) { payable(teamWalletList[i]).transfer(balance.div(100).mul(teamWalletPercent[teamWalletList[i]])); } } /// Set Methods function setRealBaseURI(string memory _realBaseURI) external onlyOwner returns (string memory) { realBaseURI = _realBaseURI; return realBaseURI; } function setPlaceholderBaseURI(string memory _placeholderBaseURI) external onlyOwner returns (string memory) { placeholderBaseURI = _placeholderBaseURI; return placeholderBaseURI; } function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner returns (bytes32) { merkleRoot = _merkleRoot; return merkleRoot; } /** * Get TokenList by sender */ function getTokenList(address account) external view returns (uint256[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint256 count = balanceOf(selectedAccount); uint256[] memory tokenIdList = new uint256[](count); if (count == 0) return tokenIdList; uint256 cnt = 0; for (uint256 i = 1; i < (_tokenId + 1); i++) { if (_exists(i) && (ownerOf(i) == selectedAccount)) { tokenIdList[cnt++] = i; } if (cnt == count) break; } return tokenIdList; } /** * Get Setting * 0 : mintStep * 1 : mintPrice * 2 : mintPriceDiscount * 3 : totalLimit * 4 : LIMIT5 * 5 : LIMIT2 */ function getSetting() external view returns (uint256[] memory) { uint256[] memory setting = new uint256[](6); setting[0] = mintStep; setting[1] = mintPrice; setting[2] = mintPriceDiscount; setting[3] = totalLimit; setting[4] = LIMIT5; setting[5] = LIMIT2; return setting; } /** * Get Status by sender * 0 : freeMintCount * 1 : presaleCount * 2 : publicSaleCount */ function getAccountStatus(address account) external view returns (uint8[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint8[] memory status = new uint8[](3); if(balanceOf(selectedAccount) == 0) return status; status[0] = addressFreeMintCountMap[selectedAccount]; status[1] = addressPreSaleCountMap[selectedAccount]; status[2] = addressPublicSaleCountMap[selectedAccount]; return status; } }
/// @title A contract for ratDAO /// @author Phillip /// @notice NFT Minting
NatSpecSingleLine
mintPresale
function mintPresale(uint8 _mintCount, bytes32[] memory _proof) external payable nonReentrant returns (uint256) { require(_mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressPreSaleCountMap[msg.sender] + _mintCount <= LIMIT2); require(( // Presale 1 mintStep == 1 && (_mintCount <= preSaleDiscountLimit) && (msg.value == (mintPriceDiscount * _mintCount)) ) || ( // Presale 2 mintStep == 2 && (_mintCount <= preSaleNormalLimit) && (msg.value == (mintPrice * _mintCount)) )); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPreSaleCountMap[msg.sender] += _mintCount; if (mintStep == 1) { preSaleDiscountLimit -= _mintCount; } else { preSaleNormalLimit -= _mintCount; } totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; }
/** * Presale with WhiteList * mintStep: 1: discount * 2: normal * mintCount: Up to 2 */
NatSpecMultiLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 7093, 8683 ] }
8,447
ratDAO
contracts/ratDAO.sol
0x43a10115280634d788815cd9316df1d07c92e1c5
Solidity
ratDAO
contract ratDAO is ERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint16; using SafeMath for uint8; uint16 private _tokenId; // Team wallet address [] teamWalletList = [ 0x0CC494215f952b7cD96378D803a0D3a6CAb282b0, // Wallet 1 address 0x214Fe0B10F0b2C4ea182F25DDdA95130C250C3e1, // Wallet 2 address 0xcC27e870C2ee553c60f51582433E80D1A4ed79da, // Wallet 3 address 0x1418a130132379b99f6E3871bef9507389b2972C, // Wallet 4 address 0x77fc746a68bFa56812b96f9686495efFF6F39364 // Wallet 5 address ]; mapping (address => uint8) teamWalletPercent; // Mint Counter for Each Wallet mapping (address => uint8) addressFreeMintCountMap; // Up to 2 mapping (address => uint8) addressPreSaleCountMap; // Up to 2 mapping (address => uint8) addressPublicSaleCountMap; // Up to 5 // Minting Limitation uint16 public secretFreeMintLimit = 600; uint16 public normalFreeMintLimit = 400; uint16 public preSaleDiscountLimit = 2000; uint16 public preSaleNormalLimit = 1000; uint16 public totalLimit = 8888; /** * Mint Step flag * 0: freeMint, * 1: preSale - discount, * 2: preSale - normal, * 3: publicSale, * 4: reveal, * 5: paused */ uint8 public mintStep = 0; // Merkle Tree Root bytes32 private merkleRoot; // Mint Price uint public mintPriceDiscount = 0.048 ether; uint public mintPrice = 0.06 ether; // BaseURI (real, placeholder) string private realBaseURI = "https://gateway.pinata.cloud/ipfs/QmWvVa8sUuRuTYLHNXPUVH7CmoDvXx7Ura8gVQBBn3zXcQ/"; string private placeholderBaseURI = "https://ratdao.mypinata.cloud/ipfs/QmabSngCR5cztRiSemNnjXcv9KPtWYuBZ1Rg4ciHKfV4GN/"; uint8 private LIMIT5 = 5; uint8 private LIMIT2 = 2; constructor() ERC721("ratDAO", "RDAO") { teamWalletPercent[teamWalletList[0]] = 29; // Wallet 1 percent teamWalletPercent[teamWalletList[1]] = 29; // Wallet 2 percent teamWalletPercent[teamWalletList[2]] = 20; // Wallet 3 percent teamWalletPercent[teamWalletList[3]] = 10; // Wallet 4 percent teamWalletPercent[teamWalletList[4]] = 12; // Wallet 5 percent } event Mint (address indexed _from, uint8 _mintStep, uint _tokenId, uint _mintPrice, uint8 _mintCount, uint8 _freeMintCount, uint8 _preSaleCount, uint8 _publicSaleCount); event Setting ( uint8 _mintStep, uint256 _mintPrice, uint256 _mintPriceDiscount, uint16 _totalLimit, uint8 _limit5, uint8 _limit2); /** * Override _baseURI * mintStep: 0~3 - Unreveal * 4 - Reveal */ function _baseURI() internal view override returns (string memory) { if (mintStep == 4) // Reveal return realBaseURI; return placeholderBaseURI; } /** * Override tokenURI */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist"); return string(abi.encodePacked(_baseURI(), Strings.toString(tokenId), ".json")); } /** * Address -> leaf for MerkleTree */ function _leaf(address account) private pure returns (bytes32) { return keccak256(abi.encodePacked(account)); } /** * Verify WhiteList using MerkleTree */ function verifyWhitelist(bytes32 leaf, bytes32[] memory proof) private view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == merkleRoot; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeSecret(uint8 _mintCount) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= secretFreeMintLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; secretFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeNormal(uint8 _mintCount, bytes32[] memory _proof) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= normalFreeMintLimit); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; normalFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Presale with WhiteList * mintStep: 1: discount * 2: normal * mintCount: Up to 2 */ function mintPresale(uint8 _mintCount, bytes32[] memory _proof) external payable nonReentrant returns (uint256) { require(_mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressPreSaleCountMap[msg.sender] + _mintCount <= LIMIT2); require(( // Presale 1 mintStep == 1 && (_mintCount <= preSaleDiscountLimit) && (msg.value == (mintPriceDiscount * _mintCount)) ) || ( // Presale 2 mintStep == 2 && (_mintCount <= preSaleNormalLimit) && (msg.value == (mintPrice * _mintCount)) )); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPreSaleCountMap[msg.sender] += _mintCount; if (mintStep == 1) { preSaleDiscountLimit -= _mintCount; } else { preSaleNormalLimit -= _mintCount; } totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Public Sale * mintStep: 3 * mintCount: Up to 5 */ function mintPublic(uint8 _mintCount) external payable nonReentrant returns (uint256) { require(mintStep == 3 && _mintCount > 0 && _mintCount <= LIMIT5); require(msg.sender != address(0)); require(msg.value == (mintPrice * _mintCount)); require(addressPublicSaleCountMap[msg.sender] + _mintCount <= LIMIT5); require(_mintCount <= totalLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPublicSaleCountMap[msg.sender] += _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Set status of mintStep * mintStep: 0 - freeMint, * 1 - preSale 1: discount, * 2 - preSale 2: normal, * 3 - publicSale, * 4 - reveal, * 5 - paused */ function setMintStep(uint8 _mintStep) external onlyOwner returns (uint8) { require(_mintStep >= 0 && _mintStep <= 5); mintStep = _mintStep; emit Setting(mintStep, mintPrice, mintPriceDiscount, totalLimit, LIMIT5, LIMIT2); return mintStep; } // Get Balance function getBalance() external view onlyOwner returns (uint256) { return address(this).balance; } // Withdraw function withdraw() external onlyOwner { require(address(this).balance != 0); uint256 balance = address(this).balance; for (uint8 i = 0; i < teamWalletList.length; i++) { payable(teamWalletList[i]).transfer(balance.div(100).mul(teamWalletPercent[teamWalletList[i]])); } } /// Set Methods function setRealBaseURI(string memory _realBaseURI) external onlyOwner returns (string memory) { realBaseURI = _realBaseURI; return realBaseURI; } function setPlaceholderBaseURI(string memory _placeholderBaseURI) external onlyOwner returns (string memory) { placeholderBaseURI = _placeholderBaseURI; return placeholderBaseURI; } function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner returns (bytes32) { merkleRoot = _merkleRoot; return merkleRoot; } /** * Get TokenList by sender */ function getTokenList(address account) external view returns (uint256[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint256 count = balanceOf(selectedAccount); uint256[] memory tokenIdList = new uint256[](count); if (count == 0) return tokenIdList; uint256 cnt = 0; for (uint256 i = 1; i < (_tokenId + 1); i++) { if (_exists(i) && (ownerOf(i) == selectedAccount)) { tokenIdList[cnt++] = i; } if (cnt == count) break; } return tokenIdList; } /** * Get Setting * 0 : mintStep * 1 : mintPrice * 2 : mintPriceDiscount * 3 : totalLimit * 4 : LIMIT5 * 5 : LIMIT2 */ function getSetting() external view returns (uint256[] memory) { uint256[] memory setting = new uint256[](6); setting[0] = mintStep; setting[1] = mintPrice; setting[2] = mintPriceDiscount; setting[3] = totalLimit; setting[4] = LIMIT5; setting[5] = LIMIT2; return setting; } /** * Get Status by sender * 0 : freeMintCount * 1 : presaleCount * 2 : publicSaleCount */ function getAccountStatus(address account) external view returns (uint8[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint8[] memory status = new uint8[](3); if(balanceOf(selectedAccount) == 0) return status; status[0] = addressFreeMintCountMap[selectedAccount]; status[1] = addressPreSaleCountMap[selectedAccount]; status[2] = addressPublicSaleCountMap[selectedAccount]; return status; } }
/// @title A contract for ratDAO /// @author Phillip /// @notice NFT Minting
NatSpecSingleLine
mintPublic
function mintPublic(uint8 _mintCount) external payable nonReentrant returns (uint256) { require(mintStep == 3 && _mintCount > 0 && _mintCount <= LIMIT5); require(msg.sender != address(0)); require(msg.value == (mintPrice * _mintCount)); require(addressPublicSaleCountMap[msg.sender] + _mintCount <= LIMIT5); require(_mintCount <= totalLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPublicSaleCountMap[msg.sender] += _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; }
/** * Public Sale * mintStep: 3 * mintCount: Up to 5 */
NatSpecMultiLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 8776, 9800 ] }
8,448
ratDAO
contracts/ratDAO.sol
0x43a10115280634d788815cd9316df1d07c92e1c5
Solidity
ratDAO
contract ratDAO is ERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint16; using SafeMath for uint8; uint16 private _tokenId; // Team wallet address [] teamWalletList = [ 0x0CC494215f952b7cD96378D803a0D3a6CAb282b0, // Wallet 1 address 0x214Fe0B10F0b2C4ea182F25DDdA95130C250C3e1, // Wallet 2 address 0xcC27e870C2ee553c60f51582433E80D1A4ed79da, // Wallet 3 address 0x1418a130132379b99f6E3871bef9507389b2972C, // Wallet 4 address 0x77fc746a68bFa56812b96f9686495efFF6F39364 // Wallet 5 address ]; mapping (address => uint8) teamWalletPercent; // Mint Counter for Each Wallet mapping (address => uint8) addressFreeMintCountMap; // Up to 2 mapping (address => uint8) addressPreSaleCountMap; // Up to 2 mapping (address => uint8) addressPublicSaleCountMap; // Up to 5 // Minting Limitation uint16 public secretFreeMintLimit = 600; uint16 public normalFreeMintLimit = 400; uint16 public preSaleDiscountLimit = 2000; uint16 public preSaleNormalLimit = 1000; uint16 public totalLimit = 8888; /** * Mint Step flag * 0: freeMint, * 1: preSale - discount, * 2: preSale - normal, * 3: publicSale, * 4: reveal, * 5: paused */ uint8 public mintStep = 0; // Merkle Tree Root bytes32 private merkleRoot; // Mint Price uint public mintPriceDiscount = 0.048 ether; uint public mintPrice = 0.06 ether; // BaseURI (real, placeholder) string private realBaseURI = "https://gateway.pinata.cloud/ipfs/QmWvVa8sUuRuTYLHNXPUVH7CmoDvXx7Ura8gVQBBn3zXcQ/"; string private placeholderBaseURI = "https://ratdao.mypinata.cloud/ipfs/QmabSngCR5cztRiSemNnjXcv9KPtWYuBZ1Rg4ciHKfV4GN/"; uint8 private LIMIT5 = 5; uint8 private LIMIT2 = 2; constructor() ERC721("ratDAO", "RDAO") { teamWalletPercent[teamWalletList[0]] = 29; // Wallet 1 percent teamWalletPercent[teamWalletList[1]] = 29; // Wallet 2 percent teamWalletPercent[teamWalletList[2]] = 20; // Wallet 3 percent teamWalletPercent[teamWalletList[3]] = 10; // Wallet 4 percent teamWalletPercent[teamWalletList[4]] = 12; // Wallet 5 percent } event Mint (address indexed _from, uint8 _mintStep, uint _tokenId, uint _mintPrice, uint8 _mintCount, uint8 _freeMintCount, uint8 _preSaleCount, uint8 _publicSaleCount); event Setting ( uint8 _mintStep, uint256 _mintPrice, uint256 _mintPriceDiscount, uint16 _totalLimit, uint8 _limit5, uint8 _limit2); /** * Override _baseURI * mintStep: 0~3 - Unreveal * 4 - Reveal */ function _baseURI() internal view override returns (string memory) { if (mintStep == 4) // Reveal return realBaseURI; return placeholderBaseURI; } /** * Override tokenURI */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist"); return string(abi.encodePacked(_baseURI(), Strings.toString(tokenId), ".json")); } /** * Address -> leaf for MerkleTree */ function _leaf(address account) private pure returns (bytes32) { return keccak256(abi.encodePacked(account)); } /** * Verify WhiteList using MerkleTree */ function verifyWhitelist(bytes32 leaf, bytes32[] memory proof) private view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == merkleRoot; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeSecret(uint8 _mintCount) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= secretFreeMintLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; secretFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeNormal(uint8 _mintCount, bytes32[] memory _proof) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= normalFreeMintLimit); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; normalFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Presale with WhiteList * mintStep: 1: discount * 2: normal * mintCount: Up to 2 */ function mintPresale(uint8 _mintCount, bytes32[] memory _proof) external payable nonReentrant returns (uint256) { require(_mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressPreSaleCountMap[msg.sender] + _mintCount <= LIMIT2); require(( // Presale 1 mintStep == 1 && (_mintCount <= preSaleDiscountLimit) && (msg.value == (mintPriceDiscount * _mintCount)) ) || ( // Presale 2 mintStep == 2 && (_mintCount <= preSaleNormalLimit) && (msg.value == (mintPrice * _mintCount)) )); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPreSaleCountMap[msg.sender] += _mintCount; if (mintStep == 1) { preSaleDiscountLimit -= _mintCount; } else { preSaleNormalLimit -= _mintCount; } totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Public Sale * mintStep: 3 * mintCount: Up to 5 */ function mintPublic(uint8 _mintCount) external payable nonReentrant returns (uint256) { require(mintStep == 3 && _mintCount > 0 && _mintCount <= LIMIT5); require(msg.sender != address(0)); require(msg.value == (mintPrice * _mintCount)); require(addressPublicSaleCountMap[msg.sender] + _mintCount <= LIMIT5); require(_mintCount <= totalLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPublicSaleCountMap[msg.sender] += _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Set status of mintStep * mintStep: 0 - freeMint, * 1 - preSale 1: discount, * 2 - preSale 2: normal, * 3 - publicSale, * 4 - reveal, * 5 - paused */ function setMintStep(uint8 _mintStep) external onlyOwner returns (uint8) { require(_mintStep >= 0 && _mintStep <= 5); mintStep = _mintStep; emit Setting(mintStep, mintPrice, mintPriceDiscount, totalLimit, LIMIT5, LIMIT2); return mintStep; } // Get Balance function getBalance() external view onlyOwner returns (uint256) { return address(this).balance; } // Withdraw function withdraw() external onlyOwner { require(address(this).balance != 0); uint256 balance = address(this).balance; for (uint8 i = 0; i < teamWalletList.length; i++) { payable(teamWalletList[i]).transfer(balance.div(100).mul(teamWalletPercent[teamWalletList[i]])); } } /// Set Methods function setRealBaseURI(string memory _realBaseURI) external onlyOwner returns (string memory) { realBaseURI = _realBaseURI; return realBaseURI; } function setPlaceholderBaseURI(string memory _placeholderBaseURI) external onlyOwner returns (string memory) { placeholderBaseURI = _placeholderBaseURI; return placeholderBaseURI; } function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner returns (bytes32) { merkleRoot = _merkleRoot; return merkleRoot; } /** * Get TokenList by sender */ function getTokenList(address account) external view returns (uint256[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint256 count = balanceOf(selectedAccount); uint256[] memory tokenIdList = new uint256[](count); if (count == 0) return tokenIdList; uint256 cnt = 0; for (uint256 i = 1; i < (_tokenId + 1); i++) { if (_exists(i) && (ownerOf(i) == selectedAccount)) { tokenIdList[cnt++] = i; } if (cnt == count) break; } return tokenIdList; } /** * Get Setting * 0 : mintStep * 1 : mintPrice * 2 : mintPriceDiscount * 3 : totalLimit * 4 : LIMIT5 * 5 : LIMIT2 */ function getSetting() external view returns (uint256[] memory) { uint256[] memory setting = new uint256[](6); setting[0] = mintStep; setting[1] = mintPrice; setting[2] = mintPriceDiscount; setting[3] = totalLimit; setting[4] = LIMIT5; setting[5] = LIMIT2; return setting; } /** * Get Status by sender * 0 : freeMintCount * 1 : presaleCount * 2 : publicSaleCount */ function getAccountStatus(address account) external view returns (uint8[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint8[] memory status = new uint8[](3); if(balanceOf(selectedAccount) == 0) return status; status[0] = addressFreeMintCountMap[selectedAccount]; status[1] = addressPreSaleCountMap[selectedAccount]; status[2] = addressPublicSaleCountMap[selectedAccount]; return status; } }
/// @title A contract for ratDAO /// @author Phillip /// @notice NFT Minting
NatSpecSingleLine
setMintStep
function setMintStep(uint8 _mintStep) external onlyOwner returns (uint8) { require(_mintStep >= 0 && _mintStep <= 5); mintStep = _mintStep; emit Setting(mintStep, mintPrice, mintPriceDiscount, totalLimit, LIMIT5, LIMIT2); return mintStep; }
/** * Set status of mintStep * mintStep: 0 - freeMint, * 1 - preSale 1: discount, * 2 - preSale 2: normal, * 3 - publicSale, * 4 - reveal, * 5 - paused */
NatSpecMultiLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 10080, 10366 ] }
8,449
ratDAO
contracts/ratDAO.sol
0x43a10115280634d788815cd9316df1d07c92e1c5
Solidity
ratDAO
contract ratDAO is ERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint16; using SafeMath for uint8; uint16 private _tokenId; // Team wallet address [] teamWalletList = [ 0x0CC494215f952b7cD96378D803a0D3a6CAb282b0, // Wallet 1 address 0x214Fe0B10F0b2C4ea182F25DDdA95130C250C3e1, // Wallet 2 address 0xcC27e870C2ee553c60f51582433E80D1A4ed79da, // Wallet 3 address 0x1418a130132379b99f6E3871bef9507389b2972C, // Wallet 4 address 0x77fc746a68bFa56812b96f9686495efFF6F39364 // Wallet 5 address ]; mapping (address => uint8) teamWalletPercent; // Mint Counter for Each Wallet mapping (address => uint8) addressFreeMintCountMap; // Up to 2 mapping (address => uint8) addressPreSaleCountMap; // Up to 2 mapping (address => uint8) addressPublicSaleCountMap; // Up to 5 // Minting Limitation uint16 public secretFreeMintLimit = 600; uint16 public normalFreeMintLimit = 400; uint16 public preSaleDiscountLimit = 2000; uint16 public preSaleNormalLimit = 1000; uint16 public totalLimit = 8888; /** * Mint Step flag * 0: freeMint, * 1: preSale - discount, * 2: preSale - normal, * 3: publicSale, * 4: reveal, * 5: paused */ uint8 public mintStep = 0; // Merkle Tree Root bytes32 private merkleRoot; // Mint Price uint public mintPriceDiscount = 0.048 ether; uint public mintPrice = 0.06 ether; // BaseURI (real, placeholder) string private realBaseURI = "https://gateway.pinata.cloud/ipfs/QmWvVa8sUuRuTYLHNXPUVH7CmoDvXx7Ura8gVQBBn3zXcQ/"; string private placeholderBaseURI = "https://ratdao.mypinata.cloud/ipfs/QmabSngCR5cztRiSemNnjXcv9KPtWYuBZ1Rg4ciHKfV4GN/"; uint8 private LIMIT5 = 5; uint8 private LIMIT2 = 2; constructor() ERC721("ratDAO", "RDAO") { teamWalletPercent[teamWalletList[0]] = 29; // Wallet 1 percent teamWalletPercent[teamWalletList[1]] = 29; // Wallet 2 percent teamWalletPercent[teamWalletList[2]] = 20; // Wallet 3 percent teamWalletPercent[teamWalletList[3]] = 10; // Wallet 4 percent teamWalletPercent[teamWalletList[4]] = 12; // Wallet 5 percent } event Mint (address indexed _from, uint8 _mintStep, uint _tokenId, uint _mintPrice, uint8 _mintCount, uint8 _freeMintCount, uint8 _preSaleCount, uint8 _publicSaleCount); event Setting ( uint8 _mintStep, uint256 _mintPrice, uint256 _mintPriceDiscount, uint16 _totalLimit, uint8 _limit5, uint8 _limit2); /** * Override _baseURI * mintStep: 0~3 - Unreveal * 4 - Reveal */ function _baseURI() internal view override returns (string memory) { if (mintStep == 4) // Reveal return realBaseURI; return placeholderBaseURI; } /** * Override tokenURI */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist"); return string(abi.encodePacked(_baseURI(), Strings.toString(tokenId), ".json")); } /** * Address -> leaf for MerkleTree */ function _leaf(address account) private pure returns (bytes32) { return keccak256(abi.encodePacked(account)); } /** * Verify WhiteList using MerkleTree */ function verifyWhitelist(bytes32 leaf, bytes32[] memory proof) private view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == merkleRoot; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeSecret(uint8 _mintCount) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= secretFreeMintLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; secretFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeNormal(uint8 _mintCount, bytes32[] memory _proof) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= normalFreeMintLimit); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; normalFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Presale with WhiteList * mintStep: 1: discount * 2: normal * mintCount: Up to 2 */ function mintPresale(uint8 _mintCount, bytes32[] memory _proof) external payable nonReentrant returns (uint256) { require(_mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressPreSaleCountMap[msg.sender] + _mintCount <= LIMIT2); require(( // Presale 1 mintStep == 1 && (_mintCount <= preSaleDiscountLimit) && (msg.value == (mintPriceDiscount * _mintCount)) ) || ( // Presale 2 mintStep == 2 && (_mintCount <= preSaleNormalLimit) && (msg.value == (mintPrice * _mintCount)) )); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPreSaleCountMap[msg.sender] += _mintCount; if (mintStep == 1) { preSaleDiscountLimit -= _mintCount; } else { preSaleNormalLimit -= _mintCount; } totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Public Sale * mintStep: 3 * mintCount: Up to 5 */ function mintPublic(uint8 _mintCount) external payable nonReentrant returns (uint256) { require(mintStep == 3 && _mintCount > 0 && _mintCount <= LIMIT5); require(msg.sender != address(0)); require(msg.value == (mintPrice * _mintCount)); require(addressPublicSaleCountMap[msg.sender] + _mintCount <= LIMIT5); require(_mintCount <= totalLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPublicSaleCountMap[msg.sender] += _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Set status of mintStep * mintStep: 0 - freeMint, * 1 - preSale 1: discount, * 2 - preSale 2: normal, * 3 - publicSale, * 4 - reveal, * 5 - paused */ function setMintStep(uint8 _mintStep) external onlyOwner returns (uint8) { require(_mintStep >= 0 && _mintStep <= 5); mintStep = _mintStep; emit Setting(mintStep, mintPrice, mintPriceDiscount, totalLimit, LIMIT5, LIMIT2); return mintStep; } // Get Balance function getBalance() external view onlyOwner returns (uint256) { return address(this).balance; } // Withdraw function withdraw() external onlyOwner { require(address(this).balance != 0); uint256 balance = address(this).balance; for (uint8 i = 0; i < teamWalletList.length; i++) { payable(teamWalletList[i]).transfer(balance.div(100).mul(teamWalletPercent[teamWalletList[i]])); } } /// Set Methods function setRealBaseURI(string memory _realBaseURI) external onlyOwner returns (string memory) { realBaseURI = _realBaseURI; return realBaseURI; } function setPlaceholderBaseURI(string memory _placeholderBaseURI) external onlyOwner returns (string memory) { placeholderBaseURI = _placeholderBaseURI; return placeholderBaseURI; } function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner returns (bytes32) { merkleRoot = _merkleRoot; return merkleRoot; } /** * Get TokenList by sender */ function getTokenList(address account) external view returns (uint256[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint256 count = balanceOf(selectedAccount); uint256[] memory tokenIdList = new uint256[](count); if (count == 0) return tokenIdList; uint256 cnt = 0; for (uint256 i = 1; i < (_tokenId + 1); i++) { if (_exists(i) && (ownerOf(i) == selectedAccount)) { tokenIdList[cnt++] = i; } if (cnt == count) break; } return tokenIdList; } /** * Get Setting * 0 : mintStep * 1 : mintPrice * 2 : mintPriceDiscount * 3 : totalLimit * 4 : LIMIT5 * 5 : LIMIT2 */ function getSetting() external view returns (uint256[] memory) { uint256[] memory setting = new uint256[](6); setting[0] = mintStep; setting[1] = mintPrice; setting[2] = mintPriceDiscount; setting[3] = totalLimit; setting[4] = LIMIT5; setting[5] = LIMIT2; return setting; } /** * Get Status by sender * 0 : freeMintCount * 1 : presaleCount * 2 : publicSaleCount */ function getAccountStatus(address account) external view returns (uint8[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint8[] memory status = new uint8[](3); if(balanceOf(selectedAccount) == 0) return status; status[0] = addressFreeMintCountMap[selectedAccount]; status[1] = addressPreSaleCountMap[selectedAccount]; status[2] = addressPublicSaleCountMap[selectedAccount]; return status; } }
/// @title A contract for ratDAO /// @author Phillip /// @notice NFT Minting
NatSpecSingleLine
getBalance
function getBalance() external view onlyOwner returns (uint256) { return address(this).balance; }
// Get Balance
LineComment
v0.8.10+commit.fc410830
{ "func_code_index": [ 10389, 10505 ] }
8,450
ratDAO
contracts/ratDAO.sol
0x43a10115280634d788815cd9316df1d07c92e1c5
Solidity
ratDAO
contract ratDAO is ERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint16; using SafeMath for uint8; uint16 private _tokenId; // Team wallet address [] teamWalletList = [ 0x0CC494215f952b7cD96378D803a0D3a6CAb282b0, // Wallet 1 address 0x214Fe0B10F0b2C4ea182F25DDdA95130C250C3e1, // Wallet 2 address 0xcC27e870C2ee553c60f51582433E80D1A4ed79da, // Wallet 3 address 0x1418a130132379b99f6E3871bef9507389b2972C, // Wallet 4 address 0x77fc746a68bFa56812b96f9686495efFF6F39364 // Wallet 5 address ]; mapping (address => uint8) teamWalletPercent; // Mint Counter for Each Wallet mapping (address => uint8) addressFreeMintCountMap; // Up to 2 mapping (address => uint8) addressPreSaleCountMap; // Up to 2 mapping (address => uint8) addressPublicSaleCountMap; // Up to 5 // Minting Limitation uint16 public secretFreeMintLimit = 600; uint16 public normalFreeMintLimit = 400; uint16 public preSaleDiscountLimit = 2000; uint16 public preSaleNormalLimit = 1000; uint16 public totalLimit = 8888; /** * Mint Step flag * 0: freeMint, * 1: preSale - discount, * 2: preSale - normal, * 3: publicSale, * 4: reveal, * 5: paused */ uint8 public mintStep = 0; // Merkle Tree Root bytes32 private merkleRoot; // Mint Price uint public mintPriceDiscount = 0.048 ether; uint public mintPrice = 0.06 ether; // BaseURI (real, placeholder) string private realBaseURI = "https://gateway.pinata.cloud/ipfs/QmWvVa8sUuRuTYLHNXPUVH7CmoDvXx7Ura8gVQBBn3zXcQ/"; string private placeholderBaseURI = "https://ratdao.mypinata.cloud/ipfs/QmabSngCR5cztRiSemNnjXcv9KPtWYuBZ1Rg4ciHKfV4GN/"; uint8 private LIMIT5 = 5; uint8 private LIMIT2 = 2; constructor() ERC721("ratDAO", "RDAO") { teamWalletPercent[teamWalletList[0]] = 29; // Wallet 1 percent teamWalletPercent[teamWalletList[1]] = 29; // Wallet 2 percent teamWalletPercent[teamWalletList[2]] = 20; // Wallet 3 percent teamWalletPercent[teamWalletList[3]] = 10; // Wallet 4 percent teamWalletPercent[teamWalletList[4]] = 12; // Wallet 5 percent } event Mint (address indexed _from, uint8 _mintStep, uint _tokenId, uint _mintPrice, uint8 _mintCount, uint8 _freeMintCount, uint8 _preSaleCount, uint8 _publicSaleCount); event Setting ( uint8 _mintStep, uint256 _mintPrice, uint256 _mintPriceDiscount, uint16 _totalLimit, uint8 _limit5, uint8 _limit2); /** * Override _baseURI * mintStep: 0~3 - Unreveal * 4 - Reveal */ function _baseURI() internal view override returns (string memory) { if (mintStep == 4) // Reveal return realBaseURI; return placeholderBaseURI; } /** * Override tokenURI */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist"); return string(abi.encodePacked(_baseURI(), Strings.toString(tokenId), ".json")); } /** * Address -> leaf for MerkleTree */ function _leaf(address account) private pure returns (bytes32) { return keccak256(abi.encodePacked(account)); } /** * Verify WhiteList using MerkleTree */ function verifyWhitelist(bytes32 leaf, bytes32[] memory proof) private view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == merkleRoot; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeSecret(uint8 _mintCount) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= secretFreeMintLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; secretFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeNormal(uint8 _mintCount, bytes32[] memory _proof) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= normalFreeMintLimit); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; normalFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Presale with WhiteList * mintStep: 1: discount * 2: normal * mintCount: Up to 2 */ function mintPresale(uint8 _mintCount, bytes32[] memory _proof) external payable nonReentrant returns (uint256) { require(_mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressPreSaleCountMap[msg.sender] + _mintCount <= LIMIT2); require(( // Presale 1 mintStep == 1 && (_mintCount <= preSaleDiscountLimit) && (msg.value == (mintPriceDiscount * _mintCount)) ) || ( // Presale 2 mintStep == 2 && (_mintCount <= preSaleNormalLimit) && (msg.value == (mintPrice * _mintCount)) )); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPreSaleCountMap[msg.sender] += _mintCount; if (mintStep == 1) { preSaleDiscountLimit -= _mintCount; } else { preSaleNormalLimit -= _mintCount; } totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Public Sale * mintStep: 3 * mintCount: Up to 5 */ function mintPublic(uint8 _mintCount) external payable nonReentrant returns (uint256) { require(mintStep == 3 && _mintCount > 0 && _mintCount <= LIMIT5); require(msg.sender != address(0)); require(msg.value == (mintPrice * _mintCount)); require(addressPublicSaleCountMap[msg.sender] + _mintCount <= LIMIT5); require(_mintCount <= totalLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPublicSaleCountMap[msg.sender] += _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Set status of mintStep * mintStep: 0 - freeMint, * 1 - preSale 1: discount, * 2 - preSale 2: normal, * 3 - publicSale, * 4 - reveal, * 5 - paused */ function setMintStep(uint8 _mintStep) external onlyOwner returns (uint8) { require(_mintStep >= 0 && _mintStep <= 5); mintStep = _mintStep; emit Setting(mintStep, mintPrice, mintPriceDiscount, totalLimit, LIMIT5, LIMIT2); return mintStep; } // Get Balance function getBalance() external view onlyOwner returns (uint256) { return address(this).balance; } // Withdraw function withdraw() external onlyOwner { require(address(this).balance != 0); uint256 balance = address(this).balance; for (uint8 i = 0; i < teamWalletList.length; i++) { payable(teamWalletList[i]).transfer(balance.div(100).mul(teamWalletPercent[teamWalletList[i]])); } } /// Set Methods function setRealBaseURI(string memory _realBaseURI) external onlyOwner returns (string memory) { realBaseURI = _realBaseURI; return realBaseURI; } function setPlaceholderBaseURI(string memory _placeholderBaseURI) external onlyOwner returns (string memory) { placeholderBaseURI = _placeholderBaseURI; return placeholderBaseURI; } function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner returns (bytes32) { merkleRoot = _merkleRoot; return merkleRoot; } /** * Get TokenList by sender */ function getTokenList(address account) external view returns (uint256[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint256 count = balanceOf(selectedAccount); uint256[] memory tokenIdList = new uint256[](count); if (count == 0) return tokenIdList; uint256 cnt = 0; for (uint256 i = 1; i < (_tokenId + 1); i++) { if (_exists(i) && (ownerOf(i) == selectedAccount)) { tokenIdList[cnt++] = i; } if (cnt == count) break; } return tokenIdList; } /** * Get Setting * 0 : mintStep * 1 : mintPrice * 2 : mintPriceDiscount * 3 : totalLimit * 4 : LIMIT5 * 5 : LIMIT2 */ function getSetting() external view returns (uint256[] memory) { uint256[] memory setting = new uint256[](6); setting[0] = mintStep; setting[1] = mintPrice; setting[2] = mintPriceDiscount; setting[3] = totalLimit; setting[4] = LIMIT5; setting[5] = LIMIT2; return setting; } /** * Get Status by sender * 0 : freeMintCount * 1 : presaleCount * 2 : publicSaleCount */ function getAccountStatus(address account) external view returns (uint8[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint8[] memory status = new uint8[](3); if(balanceOf(selectedAccount) == 0) return status; status[0] = addressFreeMintCountMap[selectedAccount]; status[1] = addressPreSaleCountMap[selectedAccount]; status[2] = addressPublicSaleCountMap[selectedAccount]; return status; } }
/// @title A contract for ratDAO /// @author Phillip /// @notice NFT Minting
NatSpecSingleLine
withdraw
function withdraw() external onlyOwner { require(address(this).balance != 0); uint256 balance = address(this).balance; for (uint8 i = 0; i < teamWalletList.length; i++) { payable(teamWalletList[i]).transfer(balance.div(100).mul(teamWalletPercent[teamWalletList[i]])); } }
// Withdraw
LineComment
v0.8.10+commit.fc410830
{ "func_code_index": [ 10529, 10871 ] }
8,451
ratDAO
contracts/ratDAO.sol
0x43a10115280634d788815cd9316df1d07c92e1c5
Solidity
ratDAO
contract ratDAO is ERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint16; using SafeMath for uint8; uint16 private _tokenId; // Team wallet address [] teamWalletList = [ 0x0CC494215f952b7cD96378D803a0D3a6CAb282b0, // Wallet 1 address 0x214Fe0B10F0b2C4ea182F25DDdA95130C250C3e1, // Wallet 2 address 0xcC27e870C2ee553c60f51582433E80D1A4ed79da, // Wallet 3 address 0x1418a130132379b99f6E3871bef9507389b2972C, // Wallet 4 address 0x77fc746a68bFa56812b96f9686495efFF6F39364 // Wallet 5 address ]; mapping (address => uint8) teamWalletPercent; // Mint Counter for Each Wallet mapping (address => uint8) addressFreeMintCountMap; // Up to 2 mapping (address => uint8) addressPreSaleCountMap; // Up to 2 mapping (address => uint8) addressPublicSaleCountMap; // Up to 5 // Minting Limitation uint16 public secretFreeMintLimit = 600; uint16 public normalFreeMintLimit = 400; uint16 public preSaleDiscountLimit = 2000; uint16 public preSaleNormalLimit = 1000; uint16 public totalLimit = 8888; /** * Mint Step flag * 0: freeMint, * 1: preSale - discount, * 2: preSale - normal, * 3: publicSale, * 4: reveal, * 5: paused */ uint8 public mintStep = 0; // Merkle Tree Root bytes32 private merkleRoot; // Mint Price uint public mintPriceDiscount = 0.048 ether; uint public mintPrice = 0.06 ether; // BaseURI (real, placeholder) string private realBaseURI = "https://gateway.pinata.cloud/ipfs/QmWvVa8sUuRuTYLHNXPUVH7CmoDvXx7Ura8gVQBBn3zXcQ/"; string private placeholderBaseURI = "https://ratdao.mypinata.cloud/ipfs/QmabSngCR5cztRiSemNnjXcv9KPtWYuBZ1Rg4ciHKfV4GN/"; uint8 private LIMIT5 = 5; uint8 private LIMIT2 = 2; constructor() ERC721("ratDAO", "RDAO") { teamWalletPercent[teamWalletList[0]] = 29; // Wallet 1 percent teamWalletPercent[teamWalletList[1]] = 29; // Wallet 2 percent teamWalletPercent[teamWalletList[2]] = 20; // Wallet 3 percent teamWalletPercent[teamWalletList[3]] = 10; // Wallet 4 percent teamWalletPercent[teamWalletList[4]] = 12; // Wallet 5 percent } event Mint (address indexed _from, uint8 _mintStep, uint _tokenId, uint _mintPrice, uint8 _mintCount, uint8 _freeMintCount, uint8 _preSaleCount, uint8 _publicSaleCount); event Setting ( uint8 _mintStep, uint256 _mintPrice, uint256 _mintPriceDiscount, uint16 _totalLimit, uint8 _limit5, uint8 _limit2); /** * Override _baseURI * mintStep: 0~3 - Unreveal * 4 - Reveal */ function _baseURI() internal view override returns (string memory) { if (mintStep == 4) // Reveal return realBaseURI; return placeholderBaseURI; } /** * Override tokenURI */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist"); return string(abi.encodePacked(_baseURI(), Strings.toString(tokenId), ".json")); } /** * Address -> leaf for MerkleTree */ function _leaf(address account) private pure returns (bytes32) { return keccak256(abi.encodePacked(account)); } /** * Verify WhiteList using MerkleTree */ function verifyWhitelist(bytes32 leaf, bytes32[] memory proof) private view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == merkleRoot; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeSecret(uint8 _mintCount) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= secretFreeMintLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; secretFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeNormal(uint8 _mintCount, bytes32[] memory _proof) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= normalFreeMintLimit); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; normalFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Presale with WhiteList * mintStep: 1: discount * 2: normal * mintCount: Up to 2 */ function mintPresale(uint8 _mintCount, bytes32[] memory _proof) external payable nonReentrant returns (uint256) { require(_mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressPreSaleCountMap[msg.sender] + _mintCount <= LIMIT2); require(( // Presale 1 mintStep == 1 && (_mintCount <= preSaleDiscountLimit) && (msg.value == (mintPriceDiscount * _mintCount)) ) || ( // Presale 2 mintStep == 2 && (_mintCount <= preSaleNormalLimit) && (msg.value == (mintPrice * _mintCount)) )); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPreSaleCountMap[msg.sender] += _mintCount; if (mintStep == 1) { preSaleDiscountLimit -= _mintCount; } else { preSaleNormalLimit -= _mintCount; } totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Public Sale * mintStep: 3 * mintCount: Up to 5 */ function mintPublic(uint8 _mintCount) external payable nonReentrant returns (uint256) { require(mintStep == 3 && _mintCount > 0 && _mintCount <= LIMIT5); require(msg.sender != address(0)); require(msg.value == (mintPrice * _mintCount)); require(addressPublicSaleCountMap[msg.sender] + _mintCount <= LIMIT5); require(_mintCount <= totalLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPublicSaleCountMap[msg.sender] += _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Set status of mintStep * mintStep: 0 - freeMint, * 1 - preSale 1: discount, * 2 - preSale 2: normal, * 3 - publicSale, * 4 - reveal, * 5 - paused */ function setMintStep(uint8 _mintStep) external onlyOwner returns (uint8) { require(_mintStep >= 0 && _mintStep <= 5); mintStep = _mintStep; emit Setting(mintStep, mintPrice, mintPriceDiscount, totalLimit, LIMIT5, LIMIT2); return mintStep; } // Get Balance function getBalance() external view onlyOwner returns (uint256) { return address(this).balance; } // Withdraw function withdraw() external onlyOwner { require(address(this).balance != 0); uint256 balance = address(this).balance; for (uint8 i = 0; i < teamWalletList.length; i++) { payable(teamWalletList[i]).transfer(balance.div(100).mul(teamWalletPercent[teamWalletList[i]])); } } /// Set Methods function setRealBaseURI(string memory _realBaseURI) external onlyOwner returns (string memory) { realBaseURI = _realBaseURI; return realBaseURI; } function setPlaceholderBaseURI(string memory _placeholderBaseURI) external onlyOwner returns (string memory) { placeholderBaseURI = _placeholderBaseURI; return placeholderBaseURI; } function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner returns (bytes32) { merkleRoot = _merkleRoot; return merkleRoot; } /** * Get TokenList by sender */ function getTokenList(address account) external view returns (uint256[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint256 count = balanceOf(selectedAccount); uint256[] memory tokenIdList = new uint256[](count); if (count == 0) return tokenIdList; uint256 cnt = 0; for (uint256 i = 1; i < (_tokenId + 1); i++) { if (_exists(i) && (ownerOf(i) == selectedAccount)) { tokenIdList[cnt++] = i; } if (cnt == count) break; } return tokenIdList; } /** * Get Setting * 0 : mintStep * 1 : mintPrice * 2 : mintPriceDiscount * 3 : totalLimit * 4 : LIMIT5 * 5 : LIMIT2 */ function getSetting() external view returns (uint256[] memory) { uint256[] memory setting = new uint256[](6); setting[0] = mintStep; setting[1] = mintPrice; setting[2] = mintPriceDiscount; setting[3] = totalLimit; setting[4] = LIMIT5; setting[5] = LIMIT2; return setting; } /** * Get Status by sender * 0 : freeMintCount * 1 : presaleCount * 2 : publicSaleCount */ function getAccountStatus(address account) external view returns (uint8[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint8[] memory status = new uint8[](3); if(balanceOf(selectedAccount) == 0) return status; status[0] = addressFreeMintCountMap[selectedAccount]; status[1] = addressPreSaleCountMap[selectedAccount]; status[2] = addressPublicSaleCountMap[selectedAccount]; return status; } }
/// @title A contract for ratDAO /// @author Phillip /// @notice NFT Minting
NatSpecSingleLine
setRealBaseURI
function setRealBaseURI(string memory _realBaseURI) external onlyOwner returns (string memory) { realBaseURI = _realBaseURI; return realBaseURI; }
/// Set Methods
NatSpecSingleLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 10895, 11069 ] }
8,452
ratDAO
contracts/ratDAO.sol
0x43a10115280634d788815cd9316df1d07c92e1c5
Solidity
ratDAO
contract ratDAO is ERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint16; using SafeMath for uint8; uint16 private _tokenId; // Team wallet address [] teamWalletList = [ 0x0CC494215f952b7cD96378D803a0D3a6CAb282b0, // Wallet 1 address 0x214Fe0B10F0b2C4ea182F25DDdA95130C250C3e1, // Wallet 2 address 0xcC27e870C2ee553c60f51582433E80D1A4ed79da, // Wallet 3 address 0x1418a130132379b99f6E3871bef9507389b2972C, // Wallet 4 address 0x77fc746a68bFa56812b96f9686495efFF6F39364 // Wallet 5 address ]; mapping (address => uint8) teamWalletPercent; // Mint Counter for Each Wallet mapping (address => uint8) addressFreeMintCountMap; // Up to 2 mapping (address => uint8) addressPreSaleCountMap; // Up to 2 mapping (address => uint8) addressPublicSaleCountMap; // Up to 5 // Minting Limitation uint16 public secretFreeMintLimit = 600; uint16 public normalFreeMintLimit = 400; uint16 public preSaleDiscountLimit = 2000; uint16 public preSaleNormalLimit = 1000; uint16 public totalLimit = 8888; /** * Mint Step flag * 0: freeMint, * 1: preSale - discount, * 2: preSale - normal, * 3: publicSale, * 4: reveal, * 5: paused */ uint8 public mintStep = 0; // Merkle Tree Root bytes32 private merkleRoot; // Mint Price uint public mintPriceDiscount = 0.048 ether; uint public mintPrice = 0.06 ether; // BaseURI (real, placeholder) string private realBaseURI = "https://gateway.pinata.cloud/ipfs/QmWvVa8sUuRuTYLHNXPUVH7CmoDvXx7Ura8gVQBBn3zXcQ/"; string private placeholderBaseURI = "https://ratdao.mypinata.cloud/ipfs/QmabSngCR5cztRiSemNnjXcv9KPtWYuBZ1Rg4ciHKfV4GN/"; uint8 private LIMIT5 = 5; uint8 private LIMIT2 = 2; constructor() ERC721("ratDAO", "RDAO") { teamWalletPercent[teamWalletList[0]] = 29; // Wallet 1 percent teamWalletPercent[teamWalletList[1]] = 29; // Wallet 2 percent teamWalletPercent[teamWalletList[2]] = 20; // Wallet 3 percent teamWalletPercent[teamWalletList[3]] = 10; // Wallet 4 percent teamWalletPercent[teamWalletList[4]] = 12; // Wallet 5 percent } event Mint (address indexed _from, uint8 _mintStep, uint _tokenId, uint _mintPrice, uint8 _mintCount, uint8 _freeMintCount, uint8 _preSaleCount, uint8 _publicSaleCount); event Setting ( uint8 _mintStep, uint256 _mintPrice, uint256 _mintPriceDiscount, uint16 _totalLimit, uint8 _limit5, uint8 _limit2); /** * Override _baseURI * mintStep: 0~3 - Unreveal * 4 - Reveal */ function _baseURI() internal view override returns (string memory) { if (mintStep == 4) // Reveal return realBaseURI; return placeholderBaseURI; } /** * Override tokenURI */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist"); return string(abi.encodePacked(_baseURI(), Strings.toString(tokenId), ".json")); } /** * Address -> leaf for MerkleTree */ function _leaf(address account) private pure returns (bytes32) { return keccak256(abi.encodePacked(account)); } /** * Verify WhiteList using MerkleTree */ function verifyWhitelist(bytes32 leaf, bytes32[] memory proof) private view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == merkleRoot; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeSecret(uint8 _mintCount) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= secretFreeMintLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; secretFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeNormal(uint8 _mintCount, bytes32[] memory _proof) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= normalFreeMintLimit); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; normalFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Presale with WhiteList * mintStep: 1: discount * 2: normal * mintCount: Up to 2 */ function mintPresale(uint8 _mintCount, bytes32[] memory _proof) external payable nonReentrant returns (uint256) { require(_mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressPreSaleCountMap[msg.sender] + _mintCount <= LIMIT2); require(( // Presale 1 mintStep == 1 && (_mintCount <= preSaleDiscountLimit) && (msg.value == (mintPriceDiscount * _mintCount)) ) || ( // Presale 2 mintStep == 2 && (_mintCount <= preSaleNormalLimit) && (msg.value == (mintPrice * _mintCount)) )); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPreSaleCountMap[msg.sender] += _mintCount; if (mintStep == 1) { preSaleDiscountLimit -= _mintCount; } else { preSaleNormalLimit -= _mintCount; } totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Public Sale * mintStep: 3 * mintCount: Up to 5 */ function mintPublic(uint8 _mintCount) external payable nonReentrant returns (uint256) { require(mintStep == 3 && _mintCount > 0 && _mintCount <= LIMIT5); require(msg.sender != address(0)); require(msg.value == (mintPrice * _mintCount)); require(addressPublicSaleCountMap[msg.sender] + _mintCount <= LIMIT5); require(_mintCount <= totalLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPublicSaleCountMap[msg.sender] += _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Set status of mintStep * mintStep: 0 - freeMint, * 1 - preSale 1: discount, * 2 - preSale 2: normal, * 3 - publicSale, * 4 - reveal, * 5 - paused */ function setMintStep(uint8 _mintStep) external onlyOwner returns (uint8) { require(_mintStep >= 0 && _mintStep <= 5); mintStep = _mintStep; emit Setting(mintStep, mintPrice, mintPriceDiscount, totalLimit, LIMIT5, LIMIT2); return mintStep; } // Get Balance function getBalance() external view onlyOwner returns (uint256) { return address(this).balance; } // Withdraw function withdraw() external onlyOwner { require(address(this).balance != 0); uint256 balance = address(this).balance; for (uint8 i = 0; i < teamWalletList.length; i++) { payable(teamWalletList[i]).transfer(balance.div(100).mul(teamWalletPercent[teamWalletList[i]])); } } /// Set Methods function setRealBaseURI(string memory _realBaseURI) external onlyOwner returns (string memory) { realBaseURI = _realBaseURI; return realBaseURI; } function setPlaceholderBaseURI(string memory _placeholderBaseURI) external onlyOwner returns (string memory) { placeholderBaseURI = _placeholderBaseURI; return placeholderBaseURI; } function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner returns (bytes32) { merkleRoot = _merkleRoot; return merkleRoot; } /** * Get TokenList by sender */ function getTokenList(address account) external view returns (uint256[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint256 count = balanceOf(selectedAccount); uint256[] memory tokenIdList = new uint256[](count); if (count == 0) return tokenIdList; uint256 cnt = 0; for (uint256 i = 1; i < (_tokenId + 1); i++) { if (_exists(i) && (ownerOf(i) == selectedAccount)) { tokenIdList[cnt++] = i; } if (cnt == count) break; } return tokenIdList; } /** * Get Setting * 0 : mintStep * 1 : mintPrice * 2 : mintPriceDiscount * 3 : totalLimit * 4 : LIMIT5 * 5 : LIMIT2 */ function getSetting() external view returns (uint256[] memory) { uint256[] memory setting = new uint256[](6); setting[0] = mintStep; setting[1] = mintPrice; setting[2] = mintPriceDiscount; setting[3] = totalLimit; setting[4] = LIMIT5; setting[5] = LIMIT2; return setting; } /** * Get Status by sender * 0 : freeMintCount * 1 : presaleCount * 2 : publicSaleCount */ function getAccountStatus(address account) external view returns (uint8[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint8[] memory status = new uint8[](3); if(balanceOf(selectedAccount) == 0) return status; status[0] = addressFreeMintCountMap[selectedAccount]; status[1] = addressPreSaleCountMap[selectedAccount]; status[2] = addressPublicSaleCountMap[selectedAccount]; return status; } }
/// @title A contract for ratDAO /// @author Phillip /// @notice NFT Minting
NatSpecSingleLine
getTokenList
function getTokenList(address account) external view returns (uint256[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint256 count = balanceOf(selectedAccount); uint256[] memory tokenIdList = new uint256[](count); if (count == 0) return tokenIdList; uint256 cnt = 0; for (uint256 i = 1; i < (_tokenId + 1); i++) { if (_exists(i) && (ownerOf(i) == selectedAccount)) { tokenIdList[cnt++] = i; } if (cnt == count) break; } return tokenIdList; }
/** * Get TokenList by sender */
NatSpecMultiLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 11494, 12281 ] }
8,453
ratDAO
contracts/ratDAO.sol
0x43a10115280634d788815cd9316df1d07c92e1c5
Solidity
ratDAO
contract ratDAO is ERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint16; using SafeMath for uint8; uint16 private _tokenId; // Team wallet address [] teamWalletList = [ 0x0CC494215f952b7cD96378D803a0D3a6CAb282b0, // Wallet 1 address 0x214Fe0B10F0b2C4ea182F25DDdA95130C250C3e1, // Wallet 2 address 0xcC27e870C2ee553c60f51582433E80D1A4ed79da, // Wallet 3 address 0x1418a130132379b99f6E3871bef9507389b2972C, // Wallet 4 address 0x77fc746a68bFa56812b96f9686495efFF6F39364 // Wallet 5 address ]; mapping (address => uint8) teamWalletPercent; // Mint Counter for Each Wallet mapping (address => uint8) addressFreeMintCountMap; // Up to 2 mapping (address => uint8) addressPreSaleCountMap; // Up to 2 mapping (address => uint8) addressPublicSaleCountMap; // Up to 5 // Minting Limitation uint16 public secretFreeMintLimit = 600; uint16 public normalFreeMintLimit = 400; uint16 public preSaleDiscountLimit = 2000; uint16 public preSaleNormalLimit = 1000; uint16 public totalLimit = 8888; /** * Mint Step flag * 0: freeMint, * 1: preSale - discount, * 2: preSale - normal, * 3: publicSale, * 4: reveal, * 5: paused */ uint8 public mintStep = 0; // Merkle Tree Root bytes32 private merkleRoot; // Mint Price uint public mintPriceDiscount = 0.048 ether; uint public mintPrice = 0.06 ether; // BaseURI (real, placeholder) string private realBaseURI = "https://gateway.pinata.cloud/ipfs/QmWvVa8sUuRuTYLHNXPUVH7CmoDvXx7Ura8gVQBBn3zXcQ/"; string private placeholderBaseURI = "https://ratdao.mypinata.cloud/ipfs/QmabSngCR5cztRiSemNnjXcv9KPtWYuBZ1Rg4ciHKfV4GN/"; uint8 private LIMIT5 = 5; uint8 private LIMIT2 = 2; constructor() ERC721("ratDAO", "RDAO") { teamWalletPercent[teamWalletList[0]] = 29; // Wallet 1 percent teamWalletPercent[teamWalletList[1]] = 29; // Wallet 2 percent teamWalletPercent[teamWalletList[2]] = 20; // Wallet 3 percent teamWalletPercent[teamWalletList[3]] = 10; // Wallet 4 percent teamWalletPercent[teamWalletList[4]] = 12; // Wallet 5 percent } event Mint (address indexed _from, uint8 _mintStep, uint _tokenId, uint _mintPrice, uint8 _mintCount, uint8 _freeMintCount, uint8 _preSaleCount, uint8 _publicSaleCount); event Setting ( uint8 _mintStep, uint256 _mintPrice, uint256 _mintPriceDiscount, uint16 _totalLimit, uint8 _limit5, uint8 _limit2); /** * Override _baseURI * mintStep: 0~3 - Unreveal * 4 - Reveal */ function _baseURI() internal view override returns (string memory) { if (mintStep == 4) // Reveal return realBaseURI; return placeholderBaseURI; } /** * Override tokenURI */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist"); return string(abi.encodePacked(_baseURI(), Strings.toString(tokenId), ".json")); } /** * Address -> leaf for MerkleTree */ function _leaf(address account) private pure returns (bytes32) { return keccak256(abi.encodePacked(account)); } /** * Verify WhiteList using MerkleTree */ function verifyWhitelist(bytes32 leaf, bytes32[] memory proof) private view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == merkleRoot; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeSecret(uint8 _mintCount) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= secretFreeMintLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; secretFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeNormal(uint8 _mintCount, bytes32[] memory _proof) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= normalFreeMintLimit); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; normalFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Presale with WhiteList * mintStep: 1: discount * 2: normal * mintCount: Up to 2 */ function mintPresale(uint8 _mintCount, bytes32[] memory _proof) external payable nonReentrant returns (uint256) { require(_mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressPreSaleCountMap[msg.sender] + _mintCount <= LIMIT2); require(( // Presale 1 mintStep == 1 && (_mintCount <= preSaleDiscountLimit) && (msg.value == (mintPriceDiscount * _mintCount)) ) || ( // Presale 2 mintStep == 2 && (_mintCount <= preSaleNormalLimit) && (msg.value == (mintPrice * _mintCount)) )); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPreSaleCountMap[msg.sender] += _mintCount; if (mintStep == 1) { preSaleDiscountLimit -= _mintCount; } else { preSaleNormalLimit -= _mintCount; } totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Public Sale * mintStep: 3 * mintCount: Up to 5 */ function mintPublic(uint8 _mintCount) external payable nonReentrant returns (uint256) { require(mintStep == 3 && _mintCount > 0 && _mintCount <= LIMIT5); require(msg.sender != address(0)); require(msg.value == (mintPrice * _mintCount)); require(addressPublicSaleCountMap[msg.sender] + _mintCount <= LIMIT5); require(_mintCount <= totalLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPublicSaleCountMap[msg.sender] += _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Set status of mintStep * mintStep: 0 - freeMint, * 1 - preSale 1: discount, * 2 - preSale 2: normal, * 3 - publicSale, * 4 - reveal, * 5 - paused */ function setMintStep(uint8 _mintStep) external onlyOwner returns (uint8) { require(_mintStep >= 0 && _mintStep <= 5); mintStep = _mintStep; emit Setting(mintStep, mintPrice, mintPriceDiscount, totalLimit, LIMIT5, LIMIT2); return mintStep; } // Get Balance function getBalance() external view onlyOwner returns (uint256) { return address(this).balance; } // Withdraw function withdraw() external onlyOwner { require(address(this).balance != 0); uint256 balance = address(this).balance; for (uint8 i = 0; i < teamWalletList.length; i++) { payable(teamWalletList[i]).transfer(balance.div(100).mul(teamWalletPercent[teamWalletList[i]])); } } /// Set Methods function setRealBaseURI(string memory _realBaseURI) external onlyOwner returns (string memory) { realBaseURI = _realBaseURI; return realBaseURI; } function setPlaceholderBaseURI(string memory _placeholderBaseURI) external onlyOwner returns (string memory) { placeholderBaseURI = _placeholderBaseURI; return placeholderBaseURI; } function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner returns (bytes32) { merkleRoot = _merkleRoot; return merkleRoot; } /** * Get TokenList by sender */ function getTokenList(address account) external view returns (uint256[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint256 count = balanceOf(selectedAccount); uint256[] memory tokenIdList = new uint256[](count); if (count == 0) return tokenIdList; uint256 cnt = 0; for (uint256 i = 1; i < (_tokenId + 1); i++) { if (_exists(i) && (ownerOf(i) == selectedAccount)) { tokenIdList[cnt++] = i; } if (cnt == count) break; } return tokenIdList; } /** * Get Setting * 0 : mintStep * 1 : mintPrice * 2 : mintPriceDiscount * 3 : totalLimit * 4 : LIMIT5 * 5 : LIMIT2 */ function getSetting() external view returns (uint256[] memory) { uint256[] memory setting = new uint256[](6); setting[0] = mintStep; setting[1] = mintPrice; setting[2] = mintPriceDiscount; setting[3] = totalLimit; setting[4] = LIMIT5; setting[5] = LIMIT2; return setting; } /** * Get Status by sender * 0 : freeMintCount * 1 : presaleCount * 2 : publicSaleCount */ function getAccountStatus(address account) external view returns (uint8[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint8[] memory status = new uint8[](3); if(balanceOf(selectedAccount) == 0) return status; status[0] = addressFreeMintCountMap[selectedAccount]; status[1] = addressPreSaleCountMap[selectedAccount]; status[2] = addressPublicSaleCountMap[selectedAccount]; return status; } }
/// @title A contract for ratDAO /// @author Phillip /// @notice NFT Minting
NatSpecSingleLine
getSetting
function getSetting() external view returns (uint256[] memory) { uint256[] memory setting = new uint256[](6); setting[0] = mintStep; setting[1] = mintPrice; setting[2] = mintPriceDiscount; setting[3] = totalLimit; setting[4] = LIMIT5; setting[5] = LIMIT2; return setting; }
/** * Get Setting * 0 : mintStep * 1 : mintPrice * 2 : mintPriceDiscount * 3 : totalLimit * 4 : LIMIT5 * 5 : LIMIT2 */
NatSpecMultiLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 12486, 12841 ] }
8,454
ratDAO
contracts/ratDAO.sol
0x43a10115280634d788815cd9316df1d07c92e1c5
Solidity
ratDAO
contract ratDAO is ERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint16; using SafeMath for uint8; uint16 private _tokenId; // Team wallet address [] teamWalletList = [ 0x0CC494215f952b7cD96378D803a0D3a6CAb282b0, // Wallet 1 address 0x214Fe0B10F0b2C4ea182F25DDdA95130C250C3e1, // Wallet 2 address 0xcC27e870C2ee553c60f51582433E80D1A4ed79da, // Wallet 3 address 0x1418a130132379b99f6E3871bef9507389b2972C, // Wallet 4 address 0x77fc746a68bFa56812b96f9686495efFF6F39364 // Wallet 5 address ]; mapping (address => uint8) teamWalletPercent; // Mint Counter for Each Wallet mapping (address => uint8) addressFreeMintCountMap; // Up to 2 mapping (address => uint8) addressPreSaleCountMap; // Up to 2 mapping (address => uint8) addressPublicSaleCountMap; // Up to 5 // Minting Limitation uint16 public secretFreeMintLimit = 600; uint16 public normalFreeMintLimit = 400; uint16 public preSaleDiscountLimit = 2000; uint16 public preSaleNormalLimit = 1000; uint16 public totalLimit = 8888; /** * Mint Step flag * 0: freeMint, * 1: preSale - discount, * 2: preSale - normal, * 3: publicSale, * 4: reveal, * 5: paused */ uint8 public mintStep = 0; // Merkle Tree Root bytes32 private merkleRoot; // Mint Price uint public mintPriceDiscount = 0.048 ether; uint public mintPrice = 0.06 ether; // BaseURI (real, placeholder) string private realBaseURI = "https://gateway.pinata.cloud/ipfs/QmWvVa8sUuRuTYLHNXPUVH7CmoDvXx7Ura8gVQBBn3zXcQ/"; string private placeholderBaseURI = "https://ratdao.mypinata.cloud/ipfs/QmabSngCR5cztRiSemNnjXcv9KPtWYuBZ1Rg4ciHKfV4GN/"; uint8 private LIMIT5 = 5; uint8 private LIMIT2 = 2; constructor() ERC721("ratDAO", "RDAO") { teamWalletPercent[teamWalletList[0]] = 29; // Wallet 1 percent teamWalletPercent[teamWalletList[1]] = 29; // Wallet 2 percent teamWalletPercent[teamWalletList[2]] = 20; // Wallet 3 percent teamWalletPercent[teamWalletList[3]] = 10; // Wallet 4 percent teamWalletPercent[teamWalletList[4]] = 12; // Wallet 5 percent } event Mint (address indexed _from, uint8 _mintStep, uint _tokenId, uint _mintPrice, uint8 _mintCount, uint8 _freeMintCount, uint8 _preSaleCount, uint8 _publicSaleCount); event Setting ( uint8 _mintStep, uint256 _mintPrice, uint256 _mintPriceDiscount, uint16 _totalLimit, uint8 _limit5, uint8 _limit2); /** * Override _baseURI * mintStep: 0~3 - Unreveal * 4 - Reveal */ function _baseURI() internal view override returns (string memory) { if (mintStep == 4) // Reveal return realBaseURI; return placeholderBaseURI; } /** * Override tokenURI */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist"); return string(abi.encodePacked(_baseURI(), Strings.toString(tokenId), ".json")); } /** * Address -> leaf for MerkleTree */ function _leaf(address account) private pure returns (bytes32) { return keccak256(abi.encodePacked(account)); } /** * Verify WhiteList using MerkleTree */ function verifyWhitelist(bytes32 leaf, bytes32[] memory proof) private view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == merkleRoot; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeSecret(uint8 _mintCount) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= secretFreeMintLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; secretFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Secret Free Mint * mintStep: 0 * mintCount: Up to 2 */ function mintFreeNormal(uint8 _mintCount, bytes32[] memory _proof) external nonReentrant returns (uint256) { require(mintStep == 0 && _mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressFreeMintCountMap[msg.sender] + _mintCount <= LIMIT2); require(_mintCount <= normalFreeMintLimit); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressFreeMintCountMap[msg.sender] += _mintCount; normalFreeMintLimit -= _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, 0, // _mintPrice _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Presale with WhiteList * mintStep: 1: discount * 2: normal * mintCount: Up to 2 */ function mintPresale(uint8 _mintCount, bytes32[] memory _proof) external payable nonReentrant returns (uint256) { require(_mintCount > 0 && _mintCount <= LIMIT2); require(msg.sender != address(0)); require(addressPreSaleCountMap[msg.sender] + _mintCount <= LIMIT2); require(( // Presale 1 mintStep == 1 && (_mintCount <= preSaleDiscountLimit) && (msg.value == (mintPriceDiscount * _mintCount)) ) || ( // Presale 2 mintStep == 2 && (_mintCount <= preSaleNormalLimit) && (msg.value == (mintPrice * _mintCount)) )); require(verifyWhitelist(_leaf(msg.sender), _proof) == true); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPreSaleCountMap[msg.sender] += _mintCount; if (mintStep == 1) { preSaleDiscountLimit -= _mintCount; } else { preSaleNormalLimit -= _mintCount; } totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Public Sale * mintStep: 3 * mintCount: Up to 5 */ function mintPublic(uint8 _mintCount) external payable nonReentrant returns (uint256) { require(mintStep == 3 && _mintCount > 0 && _mintCount <= LIMIT5); require(msg.sender != address(0)); require(msg.value == (mintPrice * _mintCount)); require(addressPublicSaleCountMap[msg.sender] + _mintCount <= LIMIT5); require(_mintCount <= totalLimit); for (uint8 i = 0; i < _mintCount; i++) { _tokenId++; _safeMint(msg.sender, _tokenId); } addressPublicSaleCountMap[msg.sender] += _mintCount; totalLimit -= _mintCount; emit Mint(msg.sender, mintStep, _tokenId, mintPrice, _mintCount, addressFreeMintCountMap[msg.sender], addressPreSaleCountMap[msg.sender], addressPublicSaleCountMap[msg.sender]); return _tokenId; } /** * Set status of mintStep * mintStep: 0 - freeMint, * 1 - preSale 1: discount, * 2 - preSale 2: normal, * 3 - publicSale, * 4 - reveal, * 5 - paused */ function setMintStep(uint8 _mintStep) external onlyOwner returns (uint8) { require(_mintStep >= 0 && _mintStep <= 5); mintStep = _mintStep; emit Setting(mintStep, mintPrice, mintPriceDiscount, totalLimit, LIMIT5, LIMIT2); return mintStep; } // Get Balance function getBalance() external view onlyOwner returns (uint256) { return address(this).balance; } // Withdraw function withdraw() external onlyOwner { require(address(this).balance != 0); uint256 balance = address(this).balance; for (uint8 i = 0; i < teamWalletList.length; i++) { payable(teamWalletList[i]).transfer(balance.div(100).mul(teamWalletPercent[teamWalletList[i]])); } } /// Set Methods function setRealBaseURI(string memory _realBaseURI) external onlyOwner returns (string memory) { realBaseURI = _realBaseURI; return realBaseURI; } function setPlaceholderBaseURI(string memory _placeholderBaseURI) external onlyOwner returns (string memory) { placeholderBaseURI = _placeholderBaseURI; return placeholderBaseURI; } function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner returns (bytes32) { merkleRoot = _merkleRoot; return merkleRoot; } /** * Get TokenList by sender */ function getTokenList(address account) external view returns (uint256[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint256 count = balanceOf(selectedAccount); uint256[] memory tokenIdList = new uint256[](count); if (count == 0) return tokenIdList; uint256 cnt = 0; for (uint256 i = 1; i < (_tokenId + 1); i++) { if (_exists(i) && (ownerOf(i) == selectedAccount)) { tokenIdList[cnt++] = i; } if (cnt == count) break; } return tokenIdList; } /** * Get Setting * 0 : mintStep * 1 : mintPrice * 2 : mintPriceDiscount * 3 : totalLimit * 4 : LIMIT5 * 5 : LIMIT2 */ function getSetting() external view returns (uint256[] memory) { uint256[] memory setting = new uint256[](6); setting[0] = mintStep; setting[1] = mintPrice; setting[2] = mintPriceDiscount; setting[3] = totalLimit; setting[4] = LIMIT5; setting[5] = LIMIT2; return setting; } /** * Get Status by sender * 0 : freeMintCount * 1 : presaleCount * 2 : publicSaleCount */ function getAccountStatus(address account) external view returns (uint8[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint8[] memory status = new uint8[](3); if(balanceOf(selectedAccount) == 0) return status; status[0] = addressFreeMintCountMap[selectedAccount]; status[1] = addressPreSaleCountMap[selectedAccount]; status[2] = addressPublicSaleCountMap[selectedAccount]; return status; } }
/// @title A contract for ratDAO /// @author Phillip /// @notice NFT Minting
NatSpecSingleLine
getAccountStatus
function getAccountStatus(address account) external view returns (uint8[] memory) { require(msg.sender != address(0)); require(account != address(0)); address selectedAccount = msg.sender; if (owner() == msg.sender) selectedAccount = account; uint8[] memory status = new uint8[](3); if(balanceOf(selectedAccount) == 0) return status; status[0] = addressFreeMintCountMap[selectedAccount]; status[1] = addressPreSaleCountMap[selectedAccount]; status[2] = addressPublicSaleCountMap[selectedAccount]; return status; }
/** * Get Status by sender * 0 : freeMintCount * 1 : presaleCount * 2 : publicSaleCount */
NatSpecMultiLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 12985, 13642 ] }
8,455
AccessToken
AccessToken.sol
0x11229b2fa7ba8f1cee0bd9d11913f7f01201cbe2
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
totalSupply
function totalSupply() constant returns (uint256 supply) {}
/// @return total amount of tokens
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://d93aac7fb23f70405f229d31f202122b15740391c9681d5310df791da57cc4ff
{ "func_code_index": [ 60, 124 ] }
8,456
AccessToken
AccessToken.sol
0x11229b2fa7ba8f1cee0bd9d11913f7f01201cbe2
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
balanceOf
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @param _owner The address from which the balance will be retrieved /// @return The balance
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://d93aac7fb23f70405f229d31f202122b15740391c9681d5310df791da57cc4ff
{ "func_code_index": [ 232, 309 ] }
8,457
AccessToken
AccessToken.sol
0x11229b2fa7ba8f1cee0bd9d11913f7f01201cbe2
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
transfer
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://d93aac7fb23f70405f229d31f202122b15740391c9681d5310df791da57cc4ff
{ "func_code_index": [ 546, 623 ] }
8,458
AccessToken
AccessToken.sol
0x11229b2fa7ba8f1cee0bd9d11913f7f01201cbe2
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://d93aac7fb23f70405f229d31f202122b15740391c9681d5310df791da57cc4ff
{ "func_code_index": [ 946, 1042 ] }
8,459
AccessToken
AccessToken.sol
0x11229b2fa7ba8f1cee0bd9d11913f7f01201cbe2
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
approve
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://d93aac7fb23f70405f229d31f202122b15740391c9681d5310df791da57cc4ff
{ "func_code_index": [ 1326, 1407 ] }
8,460
AccessToken
AccessToken.sol
0x11229b2fa7ba8f1cee0bd9d11913f7f01201cbe2
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
allowance
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
/// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://d93aac7fb23f70405f229d31f202122b15740391c9681d5310df791da57cc4ff
{ "func_code_index": [ 1615, 1712 ] }
8,461
AccessToken
AccessToken.sol
0x11229b2fa7ba8f1cee0bd9d11913f7f01201cbe2
Solidity
AccessToken
contract AccessToken is StandardToken { /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // which means the following function name has to match the contract name declared above function AccessToken() { balances[msg.sender] = 10000000000000000000000000000; totalSupply = 10000000000000000000000000000; name = "AccessToken"; decimals = 18; symbol = "ACT"; unitsOneEthCanBuy = 100000000; fundsWallet = msg.sender; } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; require(balances[fundsWallet] >= amount); balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
AccessToken
function AccessToken() { balances[msg.sender] = 10000000000000000000000000000; totalSupply = 10000000000000000000000000000; name = "AccessToken"; decimals = 18; symbol = "ACT"; unitsOneEthCanBuy = 100000000; fundsWallet = msg.sender; }
// Where should the raised ETH go? // which means the following function name has to match the contract name declared above
LineComment
v0.4.24+commit.e67f0147
bzzr://d93aac7fb23f70405f229d31f202122b15740391c9681d5310df791da57cc4ff
{ "func_code_index": [ 1120, 1428 ] }
8,462
AccessToken
AccessToken.sol
0x11229b2fa7ba8f1cee0bd9d11913f7f01201cbe2
Solidity
AccessToken
contract AccessToken is StandardToken { /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // which means the following function name has to match the contract name declared above function AccessToken() { balances[msg.sender] = 10000000000000000000000000000; totalSupply = 10000000000000000000000000000; name = "AccessToken"; decimals = 18; symbol = "ACT"; unitsOneEthCanBuy = 100000000; fundsWallet = msg.sender; } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; require(balances[fundsWallet] >= amount); balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
approveAndCall
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; }
/* Approves and then calls the receiving contract */
Comment
v0.4.24+commit.e67f0147
bzzr://d93aac7fb23f70405f229d31f202122b15740391c9681d5310df791da57cc4ff
{ "func_code_index": [ 2024, 2829 ] }
8,463
MoonieNFT
contracts/common/lib/MerklePatriciaProof.sol
0x744418761efbd3e7239d76e429d6df7f18fca590
Solidity
MerklePatriciaProof
library MerklePatriciaProof { /* * @dev Verifies a merkle patricia proof. * @param value The terminating value in the trie. * @param encodedPath The path in the trie leading to value. * @param rlpParentNodes The rlp encoded stack of nodes. * @param root The root hash of the trie. * @return The boolean validity of the proof. */ function verify( bytes memory value, bytes memory encodedPath, bytes memory rlpParentNodes, bytes32 root ) internal pure returns (bool) { RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes); RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item); bytes memory currentNode; RLPReader.RLPItem[] memory currentNodeList; bytes32 nodeKey = root; uint256 pathPtr = 0; bytes memory path = _getNibbleArray(encodedPath); if (path.length == 0) { return false; } for (uint256 i = 0; i < parentNodes.length; i++) { if (pathPtr > path.length) { return false; } currentNode = RLPReader.toRlpBytes(parentNodes[i]); if (nodeKey != keccak256(currentNode)) { return false; } currentNodeList = RLPReader.toList(parentNodes[i]); if (currentNodeList.length == 17) { if (pathPtr == path.length) { if ( keccak256(RLPReader.toBytes(currentNodeList[16])) == keccak256(value) ) { return true; } else { return false; } } uint8 nextPathNibble = uint8(path[pathPtr]); if (nextPathNibble > 16) { return false; } nodeKey = bytes32( RLPReader.toUintStrict(currentNodeList[nextPathNibble]) ); pathPtr += 1; } else if (currentNodeList.length == 2) { uint256 traversed = _nibblesToTraverse( RLPReader.toBytes(currentNodeList[0]), path, pathPtr ); if (pathPtr + traversed == path.length) { //leaf node if ( keccak256(RLPReader.toBytes(currentNodeList[1])) == keccak256(value) ) { return true; } else { return false; } } //extension node if (traversed == 0) { return false; } pathPtr += traversed; nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[1])); } else { return false; } } } function _nibblesToTraverse( bytes memory encodedPartialPath, bytes memory path, uint256 pathPtr ) private pure returns (uint256) { uint256 len = 0; // encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath // and slicedPath have elements that are each one hex character (1 nibble) bytes memory partialPath = _getNibbleArray(encodedPartialPath); bytes memory slicedPath = new bytes(partialPath.length); // pathPtr counts nibbles in path // partialPath.length is a number of nibbles for (uint256 i = pathPtr; i < pathPtr + partialPath.length; i++) { bytes1 pathNibble = path[i]; slicedPath[i - pathPtr] = pathNibble; } if (keccak256(partialPath) == keccak256(slicedPath)) { len = partialPath.length; } else { len = 0; } return len; } // bytes b must be hp encoded function _getNibbleArray(bytes memory b) internal pure returns (bytes memory) { bytes memory nibbles = ""; if (b.length > 0) { uint8 offset; uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b)); if (hpNibble == 1 || hpNibble == 3) { nibbles = new bytes(b.length * 2 - 1); bytes1 oddNibble = _getNthNibbleOfBytes(1, b); nibbles[0] = oddNibble; offset = 1; } else { nibbles = new bytes(b.length * 2 - 2); offset = 0; } for (uint256 i = offset; i < nibbles.length; i++) { nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b); } } return nibbles; } function _getNthNibbleOfBytes(uint256 n, bytes memory str) private pure returns (bytes1) { return bytes1( n % 2 == 0 ? uint8(str[n / 2]) / 0x10 : uint8(str[n / 2]) % 0x10 ); } }
verify
function verify( bytes memory value, bytes memory encodedPath, bytes memory rlpParentNodes, bytes32 root ) internal pure returns (bool) { RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes); RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item); bytes memory currentNode; RLPReader.RLPItem[] memory currentNodeList; bytes32 nodeKey = root; uint256 pathPtr = 0; bytes memory path = _getNibbleArray(encodedPath); if (path.length == 0) { return false; } for (uint256 i = 0; i < parentNodes.length; i++) { if (pathPtr > path.length) { return false; } currentNode = RLPReader.toRlpBytes(parentNodes[i]); if (nodeKey != keccak256(currentNode)) { return false; } currentNodeList = RLPReader.toList(parentNodes[i]); if (currentNodeList.length == 17) { if (pathPtr == path.length) { if ( keccak256(RLPReader.toBytes(currentNodeList[16])) == keccak256(value) ) { return true; } else { return false; } } uint8 nextPathNibble = uint8(path[pathPtr]); if (nextPathNibble > 16) { return false; } nodeKey = bytes32( RLPReader.toUintStrict(currentNodeList[nextPathNibble]) ); pathPtr += 1; } else if (currentNodeList.length == 2) { uint256 traversed = _nibblesToTraverse( RLPReader.toBytes(currentNodeList[0]), path, pathPtr ); if (pathPtr + traversed == path.length) { //leaf node if ( keccak256(RLPReader.toBytes(currentNodeList[1])) == keccak256(value) ) { return true; } else { return false; } } //extension node if (traversed == 0) { return false; } pathPtr += traversed; nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[1])); } else { return false; } } }
/* * @dev Verifies a merkle patricia proof. * @param value The terminating value in the trie. * @param encodedPath The path in the trie leading to value. * @param rlpParentNodes The rlp encoded stack of nodes. * @param root The root hash of the trie. * @return The boolean validity of the proof. */
Comment
v0.8.4+commit.c7e474f2
MIT
ipfs://e272d0561e5d257fa285f8fe8be939eea21aea62940820517462c2d69edbff82
{ "func_code_index": [ 377, 3120 ] }
8,464
MoonieNFT
contracts/common/lib/MerklePatriciaProof.sol
0x744418761efbd3e7239d76e429d6df7f18fca590
Solidity
MerklePatriciaProof
library MerklePatriciaProof { /* * @dev Verifies a merkle patricia proof. * @param value The terminating value in the trie. * @param encodedPath The path in the trie leading to value. * @param rlpParentNodes The rlp encoded stack of nodes. * @param root The root hash of the trie. * @return The boolean validity of the proof. */ function verify( bytes memory value, bytes memory encodedPath, bytes memory rlpParentNodes, bytes32 root ) internal pure returns (bool) { RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes); RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item); bytes memory currentNode; RLPReader.RLPItem[] memory currentNodeList; bytes32 nodeKey = root; uint256 pathPtr = 0; bytes memory path = _getNibbleArray(encodedPath); if (path.length == 0) { return false; } for (uint256 i = 0; i < parentNodes.length; i++) { if (pathPtr > path.length) { return false; } currentNode = RLPReader.toRlpBytes(parentNodes[i]); if (nodeKey != keccak256(currentNode)) { return false; } currentNodeList = RLPReader.toList(parentNodes[i]); if (currentNodeList.length == 17) { if (pathPtr == path.length) { if ( keccak256(RLPReader.toBytes(currentNodeList[16])) == keccak256(value) ) { return true; } else { return false; } } uint8 nextPathNibble = uint8(path[pathPtr]); if (nextPathNibble > 16) { return false; } nodeKey = bytes32( RLPReader.toUintStrict(currentNodeList[nextPathNibble]) ); pathPtr += 1; } else if (currentNodeList.length == 2) { uint256 traversed = _nibblesToTraverse( RLPReader.toBytes(currentNodeList[0]), path, pathPtr ); if (pathPtr + traversed == path.length) { //leaf node if ( keccak256(RLPReader.toBytes(currentNodeList[1])) == keccak256(value) ) { return true; } else { return false; } } //extension node if (traversed == 0) { return false; } pathPtr += traversed; nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[1])); } else { return false; } } } function _nibblesToTraverse( bytes memory encodedPartialPath, bytes memory path, uint256 pathPtr ) private pure returns (uint256) { uint256 len = 0; // encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath // and slicedPath have elements that are each one hex character (1 nibble) bytes memory partialPath = _getNibbleArray(encodedPartialPath); bytes memory slicedPath = new bytes(partialPath.length); // pathPtr counts nibbles in path // partialPath.length is a number of nibbles for (uint256 i = pathPtr; i < pathPtr + partialPath.length; i++) { bytes1 pathNibble = path[i]; slicedPath[i - pathPtr] = pathNibble; } if (keccak256(partialPath) == keccak256(slicedPath)) { len = partialPath.length; } else { len = 0; } return len; } // bytes b must be hp encoded function _getNibbleArray(bytes memory b) internal pure returns (bytes memory) { bytes memory nibbles = ""; if (b.length > 0) { uint8 offset; uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b)); if (hpNibble == 1 || hpNibble == 3) { nibbles = new bytes(b.length * 2 - 1); bytes1 oddNibble = _getNthNibbleOfBytes(1, b); nibbles[0] = oddNibble; offset = 1; } else { nibbles = new bytes(b.length * 2 - 2); offset = 0; } for (uint256 i = offset; i < nibbles.length; i++) { nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b); } } return nibbles; } function _getNthNibbleOfBytes(uint256 n, bytes memory str) private pure returns (bytes1) { return bytes1( n % 2 == 0 ? uint8(str[n / 2]) / 0x10 : uint8(str[n / 2]) % 0x10 ); } }
_getNibbleArray
function _getNibbleArray(bytes memory b) internal pure returns (bytes memory) { bytes memory nibbles = ""; if (b.length > 0) { uint8 offset; uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b)); if (hpNibble == 1 || hpNibble == 3) { nibbles = new bytes(b.length * 2 - 1); bytes1 oddNibble = _getNthNibbleOfBytes(1, b); nibbles[0] = oddNibble; offset = 1; } else { nibbles = new bytes(b.length * 2 - 2); offset = 0; } for (uint256 i = offset; i < nibbles.length; i++) { nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b); } } return nibbles; }
// bytes b must be hp encoded
LineComment
v0.8.4+commit.c7e474f2
MIT
ipfs://e272d0561e5d257fa285f8fe8be939eea21aea62940820517462c2d69edbff82
{ "func_code_index": [ 4144, 4976 ] }
8,465
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
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) { require(b <= a, "SafeMath: subtraction overflow"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); 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.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 251, 437 ] }
8,466
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
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) { require(b <= a, "SafeMath: subtraction overflow"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } }
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; 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. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 707, 896 ] }
8,467
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
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) { require(b <= a, "SafeMath: subtraction overflow"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); 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-solidity/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.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 1142, 1617 ] }
8,468
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
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) { require(b <= a, "SafeMath: subtraction overflow"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } }
div
function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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 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.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 2080, 2418 ] }
8,469
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
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) { require(b <= a, "SafeMath: subtraction overflow"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } }
mod
function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; }
/** * @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.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 2870, 3027 ] }
8,470
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
Solidity
IERC20
interface IERC20 { /** * @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. * * > 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 AddPreSaleList(address indexed from, address indexed to, uint256 value); }
totalSupply
function totalSupply() external view returns (uint256);
/** * @dev Returns the amount of tokens in existence. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 94, 154 ] }
8,471
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
Solidity
IERC20
interface IERC20 { /** * @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. * * > 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 AddPreSaleList(address indexed from, address indexed to, uint256 value); }
balanceOf
function balanceOf(address account) external view returns (uint256);
/** * @dev Returns the amount of tokens owned by `account`. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 237, 310 ] }
8,472
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
Solidity
IERC20
interface IERC20 { /** * @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. * * > 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 AddPreSaleList(address indexed from, address indexed to, uint256 value); }
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.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 534, 616 ] }
8,473
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
Solidity
IERC20
interface IERC20 { /** * @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. * * > 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 AddPreSaleList(address indexed from, address indexed to, uint256 value); }
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.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 895, 983 ] }
8,474
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
Solidity
IERC20
interface IERC20 { /** * @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. * * > 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 AddPreSaleList(address indexed from, address indexed to, uint256 value); }
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. * * > 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.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 1638, 1717 ] }
8,475
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
Solidity
IERC20
interface IERC20 { /** * @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. * * > 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 AddPreSaleList(address indexed from, address indexed to, uint256 value); }
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.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 2030, 2132 ] }
8,476
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
Solidity
YFRocket
contract YFRocket is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _pre_sale_list; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release; address payable private _owner; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor () public { _name = "YFRocket"; _symbol = "YFR"; _decimals = 18; _totalSupply = 666666000000000000000000 ; amount_release = 666666000000000000000000 ; _owner = msg.sender; _issueTokens(_owner, amount_release); } /** * @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. * * > Note that 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 returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); 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 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 `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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); 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 () external payable { require(msg.value > 0); _pre_sale_list[msg.sender] = _pre_sale_list[msg.sender].add(msg.value); _owner.transfer(msg.value); emit AddPreSaleList( msg.sender, address(this), msg.value); } /** * Transfer token **/ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
name
function name() public view returns (string memory) { return _name; }
/** * @dev Returns the name of the token. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 1030, 1118 ] }
8,477
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
Solidity
YFRocket
contract YFRocket is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _pre_sale_list; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release; address payable private _owner; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor () public { _name = "YFRocket"; _symbol = "YFR"; _decimals = 18; _totalSupply = 666666000000000000000000 ; amount_release = 666666000000000000000000 ; _owner = msg.sender; _issueTokens(_owner, amount_release); } /** * @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. * * > Note that 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 returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); 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 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 `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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); 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 () external payable { require(msg.value > 0); _pre_sale_list[msg.sender] = _pre_sale_list[msg.sender].add(msg.value); _owner.transfer(msg.value); emit AddPreSaleList( msg.sender, address(this), msg.value); } /** * Transfer token **/ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
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.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 1232, 1324 ] }
8,478
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
Solidity
YFRocket
contract YFRocket is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _pre_sale_list; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release; address payable private _owner; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor () public { _name = "YFRocket"; _symbol = "YFR"; _decimals = 18; _totalSupply = 666666000000000000000000 ; amount_release = 666666000000000000000000 ; _owner = msg.sender; _issueTokens(_owner, amount_release); } /** * @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. * * > Note that 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 returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); 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 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 `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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); 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 () external payable { require(msg.value > 0); _pre_sale_list[msg.sender] = _pre_sale_list[msg.sender].add(msg.value); _owner.transfer(msg.value); emit AddPreSaleList( msg.sender, address(this), msg.value); } /** * Transfer token **/ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
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. * * > Note that 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.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 1888, 1976 ] }
8,479
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
Solidity
YFRocket
contract YFRocket is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _pre_sale_list; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release; address payable private _owner; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor () public { _name = "YFRocket"; _symbol = "YFR"; _decimals = 18; _totalSupply = 666666000000000000000000 ; amount_release = 666666000000000000000000 ; _owner = msg.sender; _issueTokens(_owner, amount_release); } /** * @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. * * > Note that 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 returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); 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 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 `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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); 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 () external payable { require(msg.value > 0); _pre_sale_list[msg.sender] = _pre_sale_list[msg.sender].add(msg.value); _owner.transfer(msg.value); emit AddPreSaleList( msg.sender, address(this), msg.value); } /** * Transfer token **/ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
totalSupply
function totalSupply() public view returns (uint256) { return _totalSupply; }
/** * @dev See `IERC20.totalSupply`. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 2034, 2130 ] }
8,480
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
Solidity
YFRocket
contract YFRocket is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _pre_sale_list; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release; address payable private _owner; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor () public { _name = "YFRocket"; _symbol = "YFR"; _decimals = 18; _totalSupply = 666666000000000000000000 ; amount_release = 666666000000000000000000 ; _owner = msg.sender; _issueTokens(_owner, amount_release); } /** * @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. * * > Note that 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 returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); 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 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 `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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); 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 () external payable { require(msg.value > 0); _pre_sale_list[msg.sender] = _pre_sale_list[msg.sender].add(msg.value); _owner.transfer(msg.value); emit AddPreSaleList( msg.sender, address(this), msg.value); } /** * Transfer token **/ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
balanceOf
function balanceOf(address account) public view returns (uint256) { return _balances[account]; }
/** * @dev See `IERC20.balanceOf`. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 2188, 2303 ] }
8,481
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
Solidity
YFRocket
contract YFRocket is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _pre_sale_list; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release; address payable private _owner; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor () public { _name = "YFRocket"; _symbol = "YFR"; _decimals = 18; _totalSupply = 666666000000000000000000 ; amount_release = 666666000000000000000000 ; _owner = msg.sender; _issueTokens(_owner, amount_release); } /** * @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. * * > Note that 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 returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); 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 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 `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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); 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 () external payable { require(msg.value > 0); _pre_sale_list[msg.sender] = _pre_sale_list[msg.sender].add(msg.value); _owner.transfer(msg.value); emit AddPreSaleList( msg.sender, address(this), msg.value); } /** * Transfer token **/ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
transfer
function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, 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.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 2511, 2672 ] }
8,482
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
Solidity
YFRocket
contract YFRocket is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _pre_sale_list; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release; address payable private _owner; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor () public { _name = "YFRocket"; _symbol = "YFR"; _decimals = 18; _totalSupply = 666666000000000000000000 ; amount_release = 666666000000000000000000 ; _owner = msg.sender; _issueTokens(_owner, amount_release); } /** * @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. * * > Note that 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 returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); 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 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 `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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); 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 () external payable { require(msg.value > 0); _pre_sale_list[msg.sender] = _pre_sale_list[msg.sender].add(msg.value); _owner.transfer(msg.value); emit AddPreSaleList( msg.sender, address(this), msg.value); } /** * Transfer token **/ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
allowance
function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; }
/** * @dev See `IERC20.allowance`. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 2730, 2869 ] }
8,483
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
Solidity
YFRocket
contract YFRocket is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _pre_sale_list; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release; address payable private _owner; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor () public { _name = "YFRocket"; _symbol = "YFR"; _decimals = 18; _totalSupply = 666666000000000000000000 ; amount_release = 666666000000000000000000 ; _owner = msg.sender; _issueTokens(_owner, amount_release); } /** * @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. * * > Note that 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 returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); 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 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 `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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); 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 () external payable { require(msg.value > 0); _pre_sale_list[msg.sender] = _pre_sale_list[msg.sender].add(msg.value); _owner.transfer(msg.value); emit AddPreSaleList( msg.sender, address(this), msg.value); } /** * Transfer token **/ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
approve
function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; }
/** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 3011, 3164 ] }
8,484
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
Solidity
YFRocket
contract YFRocket is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _pre_sale_list; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release; address payable private _owner; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor () public { _name = "YFRocket"; _symbol = "YFR"; _decimals = 18; _totalSupply = 666666000000000000000000 ; amount_release = 666666000000000000000000 ; _owner = msg.sender; _issueTokens(_owner, amount_release); } /** * @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. * * > Note that 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 returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); 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 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 `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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); 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 () external payable { require(msg.value > 0); _pre_sale_list[msg.sender] = _pre_sale_list[msg.sender].add(msg.value); _owner.transfer(msg.value); emit AddPreSaleList( msg.sender, address(this), msg.value); } /** * Transfer token **/ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
transferFrom
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 3630, 3891 ] }
8,485
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
Solidity
YFRocket
contract YFRocket is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _pre_sale_list; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release; address payable private _owner; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor () public { _name = "YFRocket"; _symbol = "YFR"; _decimals = 18; _totalSupply = 666666000000000000000000 ; amount_release = 666666000000000000000000 ; _owner = msg.sender; _issueTokens(_owner, amount_release); } /** * @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. * * > Note that 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 returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); 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 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 `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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); 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 () external payable { require(msg.value > 0); _pre_sale_list[msg.sender] = _pre_sale_list[msg.sender].add(msg.value); _owner.transfer(msg.value); emit AddPreSaleList( msg.sender, address(this), msg.value); } /** * Transfer token **/ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
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 `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 4295, 4506 ] }
8,486
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
Solidity
YFRocket
contract YFRocket is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _pre_sale_list; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release; address payable private _owner; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor () public { _name = "YFRocket"; _symbol = "YFR"; _decimals = 18; _totalSupply = 666666000000000000000000 ; amount_release = 666666000000000000000000 ; _owner = msg.sender; _issueTokens(_owner, amount_release); } /** * @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. * * > Note that 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 returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); 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 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 `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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); 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 () external payable { require(msg.value > 0); _pre_sale_list[msg.sender] = _pre_sale_list[msg.sender].add(msg.value); _owner.transfer(msg.value); emit AddPreSaleList( msg.sender, address(this), msg.value); } /** * Transfer token **/ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
decreaseAllowance
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); 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.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 5004, 5225 ] }
8,487
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
Solidity
YFRocket
contract YFRocket is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _pre_sale_list; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release; address payable private _owner; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor () public { _name = "YFRocket"; _symbol = "YFR"; _decimals = 18; _totalSupply = 666666000000000000000000 ; amount_release = 666666000000000000000000 ; _owner = msg.sender; _issueTokens(_owner, amount_release); } /** * @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. * * > Note that 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 returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); 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 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 `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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); 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 () external payable { require(msg.value > 0); _pre_sale_list[msg.sender] = _pre_sale_list[msg.sender].add(msg.value); _owner.transfer(msg.value); emit AddPreSaleList( msg.sender, address(this), msg.value); } /** * Transfer token **/ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
function () external payable { require(msg.value > 0); _pre_sale_list[msg.sender] = _pre_sale_list[msg.sender].add(msg.value); _owner.transfer(msg.value); emit AddPreSaleList( msg.sender, address(this), msg.value);
/** * @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.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 5710, 5973 ] }
8,488
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
Solidity
YFRocket
contract YFRocket is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _pre_sale_list; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release; address payable private _owner; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor () public { _name = "YFRocket"; _symbol = "YFR"; _decimals = 18; _totalSupply = 666666000000000000000000 ; amount_release = 666666000000000000000000 ; _owner = msg.sender; _issueTokens(_owner, amount_release); } /** * @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. * * > Note that 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 returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); 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 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 `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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); 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 () external payable { require(msg.value > 0); _pre_sale_list[msg.sender] = _pre_sale_list[msg.sender].add(msg.value); _owner.transfer(msg.value); emit AddPreSaleList( msg.sender, address(this), msg.value); } /** * Transfer token **/ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
_transfer
function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); }
/** * Transfer token **/
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 6014, 6448 ] }
8,489
YFRocket
YFRocket.sol
0xc4776a7a2d88d5dcb36d58a4de738f5fac410f6f
Solidity
YFRocket
contract YFRocket is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _pre_sale_list; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release; address payable private _owner; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor () public { _name = "YFRocket"; _symbol = "YFR"; _decimals = 18; _totalSupply = 666666000000000000000000 ; amount_release = 666666000000000000000000 ; _owner = msg.sender; _issueTokens(_owner, amount_release); } /** * @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. * * > Note that 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 returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); 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 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 `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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); 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 () external payable { require(msg.value > 0); _pre_sale_list[msg.sender] = _pre_sale_list[msg.sender].add(msg.value); _owner.transfer(msg.value); emit AddPreSaleList( msg.sender, address(this), msg.value); } /** * Transfer token **/ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
_approve
function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); }
/** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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.5.17+commit.d19bba13
None
bzzr://7cd836ec52f82b65db85c45a4f0e6cc0a2a9cf9ed4914343288a6a090bf4ac75
{ "func_code_index": [ 6881, 7221 ] }
8,490
ICPRToken
@openzeppelin/contracts/drafts/ERC20Permit.sol
0x2eb007970aaf70d4a9ea485e1795fa9355a8c0f2
Solidity
ERC20Permit
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256( abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _nonces[owner].current(), deadline) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _nonces[owner].increment(); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } }
/** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */
NatSpecMultiLine
permit
function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256( abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _nonces[owner].current(), deadline) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _nonces[owner].increment(); _approve(owner, spender, value); }
/** * @dev See {IERC20Permit-permit}. */
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
ipfs://14f2e5781094bf60c378c0d3950de0d2ef7ee3fa8e839eafd3083c01ef564497
{ "func_code_index": [ 728, 1502 ] }
8,491
ICPRToken
@openzeppelin/contracts/drafts/ERC20Permit.sol
0x2eb007970aaf70d4a9ea485e1795fa9355a8c0f2
Solidity
ERC20Permit
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256( abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _nonces[owner].current(), deadline) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _nonces[owner].increment(); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } }
/** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */
NatSpecMultiLine
nonces
function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); }
/** * @dev See {IERC20Permit-nonces}. */
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
ipfs://14f2e5781094bf60c378c0d3950de0d2ef7ee3fa8e839eafd3083c01ef564497
{ "func_code_index": [ 1563, 1688 ] }
8,492
ICPRToken
@openzeppelin/contracts/drafts/ERC20Permit.sol
0x2eb007970aaf70d4a9ea485e1795fa9355a8c0f2
Solidity
ERC20Permit
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256( abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _nonces[owner].current(), deadline) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _nonces[owner].increment(); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } }
/** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */
NatSpecMultiLine
DOMAIN_SEPARATOR
function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); }
// solhint-disable-next-line func-name-mixedcase
LineComment
v0.7.6+commit.7338295f
MIT
ipfs://14f2e5781094bf60c378c0d3950de0d2ef7ee3fa8e839eafd3083c01ef564497
{ "func_code_index": [ 1813, 1933 ] }
8,493
CoreVault
contracts/CoreVault.sol
0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c
Solidity
CoreVault
contract CoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of COREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accCorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. COREs to distribute per block. uint256 accCorePerShare; // Accumulated COREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The CORE TOKEN! INBUNIERC20 public core; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; //// pending rewards awaiting anyone to massUpdate uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) { averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock)); } // Returns averge fees in this epoch function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) { averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function startNewEpoch() public { require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value); function initialize( INBUNIERC20 _core, address _devaddr, address superAdmin ) public initializer { OwnableUpgradeSafe.__Ownable_init(); DEV_FEE = 3000; core = _core; devaddr = _devaddr; contractStartBlock = block.number; _superAdmin = superAdmin; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accCorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's COREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing CORE governance consensus function setPoolWithdrawable( uint256 _pid, bool _withdrawable ) public onlyOwner { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 20.00% // Note contract owner is meant to be a governance contract allowing CORE governance consensus uint16 DEV_FEE; function setDevFee(uint16 _DEV_FEE) public onlyOwner { require(_DEV_FEE <= 6000, 'Dev fee clamped at 20%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending COREs on frontend. function pendingCore(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCorePerShare = pool.accCorePerShare; return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { console.log("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.add(updatePool(pid)); } pendingRewards = pendingRewards.sub(allRewards); } // ---- // Function that adds pending rewards, called by the CORE token. // ---- uint256 private coreBalance; function addPendingRewards(uint256 _) public { uint256 newRewards = core.balanceOf(address(this)).sub(coreBalance); if(newRewards > 0) { coreBalance = core.balanceOf(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.add(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) { PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get .div(totalAllocPoint); // we can do this because pools are only mass updated uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000); uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee); pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee); pool.accCorePerShare = pool.accCorePerShare.add( coreRewardToDistribute.mul(1e12).div(tokenSupply) ); } // Deposit tokens to CoreVault for CORE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function depositFor(address depositFor, uint256 _pid, uint256 _amount) public { // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // This is depositedFor address } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address emit Deposit(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{ PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount); _withdraw(_pid, _amount, owner, msg.sender); } // Withdraw tokens from CoreVault. function withdraw(uint256 _pid, uint256 _amount) public { _withdraw(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); massUpdatePools(); updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(address(to), _amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Withdraw(to, _pid, _amount); } function updateAndPayOutPending(uint256 _pid, address from) internal { uint256 pending = pendingCore(_pid, from); if(pending > 0) { safeCoreTransfer(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin { require(isContract(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).approve(contractAddress, _amount); } function isContract(address addr) public returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe core transfer function, just in case if rounding error causes pool to not have enough COREs. function safeCoreTransfer(address _to, uint256 _amount) internal { uint256 coreBal = core.balanceOf(address(this)); if (_amount > coreBal) { core.transfer(_to, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(_to, _amount); coreBalance = core.balanceOf(address(this)); } //Avoids possible recursion loop // proxy? transferDevFee(); } function transferDevFee() public { if(pending_DEV_rewards == 0) return; uint256 coreBal = core.balanceOf(address(this)); if (pending_DEV_rewards > coreBal) { core.transfer(devaddr, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(devaddr, pending_DEV_rewards); coreBalance = core.balanceOf(address(this)); } pending_DEV_rewards = 0; } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing CORE governance token holders to do this functions. function setDevFeeReciever(address _devaddr) public onlyOwner { devaddr = _devaddr; } address private _superAdmin; event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current super admin */ function superAdmin() public view returns (address) { return _superAdmin; } /** * @dev Throws if called by any account other than the superAdmin */ modifier onlySuperAdmin() { require(_superAdmin == _msgSender(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function burnSuperAdmin() public virtual onlySuperAdmin { emit SuperAdminTransfered(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function newSuperAdmin(address newOwner) public virtual onlySuperAdmin { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SuperAdminTransfered(_superAdmin, newOwner); _superAdmin = newOwner; } }
// Core Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
averageFeesPerBlockSinceStart
function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) { averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock)); }
// Returns fees generated since start of this contract
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25
{ "func_code_index": [ 2147, 2376 ] }
8,494
CoreVault
contracts/CoreVault.sol
0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c
Solidity
CoreVault
contract CoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of COREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accCorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. COREs to distribute per block. uint256 accCorePerShare; // Accumulated COREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The CORE TOKEN! INBUNIERC20 public core; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; //// pending rewards awaiting anyone to massUpdate uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) { averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock)); } // Returns averge fees in this epoch function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) { averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function startNewEpoch() public { require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value); function initialize( INBUNIERC20 _core, address _devaddr, address superAdmin ) public initializer { OwnableUpgradeSafe.__Ownable_init(); DEV_FEE = 3000; core = _core; devaddr = _devaddr; contractStartBlock = block.number; _superAdmin = superAdmin; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accCorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's COREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing CORE governance consensus function setPoolWithdrawable( uint256 _pid, bool _withdrawable ) public onlyOwner { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 20.00% // Note contract owner is meant to be a governance contract allowing CORE governance consensus uint16 DEV_FEE; function setDevFee(uint16 _DEV_FEE) public onlyOwner { require(_DEV_FEE <= 6000, 'Dev fee clamped at 20%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending COREs on frontend. function pendingCore(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCorePerShare = pool.accCorePerShare; return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { console.log("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.add(updatePool(pid)); } pendingRewards = pendingRewards.sub(allRewards); } // ---- // Function that adds pending rewards, called by the CORE token. // ---- uint256 private coreBalance; function addPendingRewards(uint256 _) public { uint256 newRewards = core.balanceOf(address(this)).sub(coreBalance); if(newRewards > 0) { coreBalance = core.balanceOf(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.add(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) { PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get .div(totalAllocPoint); // we can do this because pools are only mass updated uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000); uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee); pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee); pool.accCorePerShare = pool.accCorePerShare.add( coreRewardToDistribute.mul(1e12).div(tokenSupply) ); } // Deposit tokens to CoreVault for CORE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function depositFor(address depositFor, uint256 _pid, uint256 _amount) public { // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // This is depositedFor address } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address emit Deposit(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{ PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount); _withdraw(_pid, _amount, owner, msg.sender); } // Withdraw tokens from CoreVault. function withdraw(uint256 _pid, uint256 _amount) public { _withdraw(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); massUpdatePools(); updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(address(to), _amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Withdraw(to, _pid, _amount); } function updateAndPayOutPending(uint256 _pid, address from) internal { uint256 pending = pendingCore(_pid, from); if(pending > 0) { safeCoreTransfer(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin { require(isContract(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).approve(contractAddress, _amount); } function isContract(address addr) public returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe core transfer function, just in case if rounding error causes pool to not have enough COREs. function safeCoreTransfer(address _to, uint256 _amount) internal { uint256 coreBal = core.balanceOf(address(this)); if (_amount > coreBal) { core.transfer(_to, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(_to, _amount); coreBalance = core.balanceOf(address(this)); } //Avoids possible recursion loop // proxy? transferDevFee(); } function transferDevFee() public { if(pending_DEV_rewards == 0) return; uint256 coreBal = core.balanceOf(address(this)); if (pending_DEV_rewards > coreBal) { core.transfer(devaddr, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(devaddr, pending_DEV_rewards); coreBalance = core.balanceOf(address(this)); } pending_DEV_rewards = 0; } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing CORE governance token holders to do this functions. function setDevFeeReciever(address _devaddr) public onlyOwner { devaddr = _devaddr; } address private _superAdmin; event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current super admin */ function superAdmin() public view returns (address) { return _superAdmin; } /** * @dev Throws if called by any account other than the superAdmin */ modifier onlySuperAdmin() { require(_superAdmin == _msgSender(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function burnSuperAdmin() public virtual onlySuperAdmin { emit SuperAdminTransfered(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function newSuperAdmin(address newOwner) public virtual onlySuperAdmin { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SuperAdminTransfered(_superAdmin, newOwner); _superAdmin = newOwner; } }
// Core Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
averageFeesPerBlockEpoch
function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) { averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock)); }
// Returns averge fees in this epoch
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25
{ "func_code_index": [ 2421, 2615 ] }
8,495
CoreVault
contracts/CoreVault.sol
0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c
Solidity
CoreVault
contract CoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of COREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accCorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. COREs to distribute per block. uint256 accCorePerShare; // Accumulated COREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The CORE TOKEN! INBUNIERC20 public core; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; //// pending rewards awaiting anyone to massUpdate uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) { averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock)); } // Returns averge fees in this epoch function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) { averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function startNewEpoch() public { require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value); function initialize( INBUNIERC20 _core, address _devaddr, address superAdmin ) public initializer { OwnableUpgradeSafe.__Ownable_init(); DEV_FEE = 3000; core = _core; devaddr = _devaddr; contractStartBlock = block.number; _superAdmin = superAdmin; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accCorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's COREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing CORE governance consensus function setPoolWithdrawable( uint256 _pid, bool _withdrawable ) public onlyOwner { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 20.00% // Note contract owner is meant to be a governance contract allowing CORE governance consensus uint16 DEV_FEE; function setDevFee(uint16 _DEV_FEE) public onlyOwner { require(_DEV_FEE <= 6000, 'Dev fee clamped at 20%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending COREs on frontend. function pendingCore(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCorePerShare = pool.accCorePerShare; return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { console.log("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.add(updatePool(pid)); } pendingRewards = pendingRewards.sub(allRewards); } // ---- // Function that adds pending rewards, called by the CORE token. // ---- uint256 private coreBalance; function addPendingRewards(uint256 _) public { uint256 newRewards = core.balanceOf(address(this)).sub(coreBalance); if(newRewards > 0) { coreBalance = core.balanceOf(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.add(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) { PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get .div(totalAllocPoint); // we can do this because pools are only mass updated uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000); uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee); pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee); pool.accCorePerShare = pool.accCorePerShare.add( coreRewardToDistribute.mul(1e12).div(tokenSupply) ); } // Deposit tokens to CoreVault for CORE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function depositFor(address depositFor, uint256 _pid, uint256 _amount) public { // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // This is depositedFor address } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address emit Deposit(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{ PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount); _withdraw(_pid, _amount, owner, msg.sender); } // Withdraw tokens from CoreVault. function withdraw(uint256 _pid, uint256 _amount) public { _withdraw(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); massUpdatePools(); updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(address(to), _amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Withdraw(to, _pid, _amount); } function updateAndPayOutPending(uint256 _pid, address from) internal { uint256 pending = pendingCore(_pid, from); if(pending > 0) { safeCoreTransfer(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin { require(isContract(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).approve(contractAddress, _amount); } function isContract(address addr) public returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe core transfer function, just in case if rounding error causes pool to not have enough COREs. function safeCoreTransfer(address _to, uint256 _amount) internal { uint256 coreBal = core.balanceOf(address(this)); if (_amount > coreBal) { core.transfer(_to, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(_to, _amount); coreBalance = core.balanceOf(address(this)); } //Avoids possible recursion loop // proxy? transferDevFee(); } function transferDevFee() public { if(pending_DEV_rewards == 0) return; uint256 coreBal = core.balanceOf(address(this)); if (pending_DEV_rewards > coreBal) { core.transfer(devaddr, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(devaddr, pending_DEV_rewards); coreBalance = core.balanceOf(address(this)); } pending_DEV_rewards = 0; } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing CORE governance token holders to do this functions. function setDevFeeReciever(address _devaddr) public onlyOwner { devaddr = _devaddr; } address private _superAdmin; event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current super admin */ function superAdmin() public view returns (address) { return _superAdmin; } /** * @dev Throws if called by any account other than the superAdmin */ modifier onlySuperAdmin() { require(_superAdmin == _msgSender(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function burnSuperAdmin() public virtual onlySuperAdmin { emit SuperAdminTransfered(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function newSuperAdmin(address newOwner) public virtual onlySuperAdmin { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SuperAdminTransfered(_superAdmin, newOwner); _superAdmin = newOwner; } }
// Core Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
startNewEpoch
function startNewEpoch() public { require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; }
//Starts a new calculation epoch // Because averge since start will not be accurate
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25
{ "func_code_index": [ 2816, 3219 ] }
8,496
CoreVault
contracts/CoreVault.sol
0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c
Solidity
CoreVault
contract CoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of COREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accCorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. COREs to distribute per block. uint256 accCorePerShare; // Accumulated COREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The CORE TOKEN! INBUNIERC20 public core; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; //// pending rewards awaiting anyone to massUpdate uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) { averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock)); } // Returns averge fees in this epoch function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) { averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function startNewEpoch() public { require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value); function initialize( INBUNIERC20 _core, address _devaddr, address superAdmin ) public initializer { OwnableUpgradeSafe.__Ownable_init(); DEV_FEE = 3000; core = _core; devaddr = _devaddr; contractStartBlock = block.number; _superAdmin = superAdmin; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accCorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's COREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing CORE governance consensus function setPoolWithdrawable( uint256 _pid, bool _withdrawable ) public onlyOwner { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 20.00% // Note contract owner is meant to be a governance contract allowing CORE governance consensus uint16 DEV_FEE; function setDevFee(uint16 _DEV_FEE) public onlyOwner { require(_DEV_FEE <= 6000, 'Dev fee clamped at 20%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending COREs on frontend. function pendingCore(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCorePerShare = pool.accCorePerShare; return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { console.log("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.add(updatePool(pid)); } pendingRewards = pendingRewards.sub(allRewards); } // ---- // Function that adds pending rewards, called by the CORE token. // ---- uint256 private coreBalance; function addPendingRewards(uint256 _) public { uint256 newRewards = core.balanceOf(address(this)).sub(coreBalance); if(newRewards > 0) { coreBalance = core.balanceOf(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.add(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) { PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get .div(totalAllocPoint); // we can do this because pools are only mass updated uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000); uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee); pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee); pool.accCorePerShare = pool.accCorePerShare.add( coreRewardToDistribute.mul(1e12).div(tokenSupply) ); } // Deposit tokens to CoreVault for CORE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function depositFor(address depositFor, uint256 _pid, uint256 _amount) public { // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // This is depositedFor address } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address emit Deposit(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{ PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount); _withdraw(_pid, _amount, owner, msg.sender); } // Withdraw tokens from CoreVault. function withdraw(uint256 _pid, uint256 _amount) public { _withdraw(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); massUpdatePools(); updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(address(to), _amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Withdraw(to, _pid, _amount); } function updateAndPayOutPending(uint256 _pid, address from) internal { uint256 pending = pendingCore(_pid, from); if(pending > 0) { safeCoreTransfer(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin { require(isContract(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).approve(contractAddress, _amount); } function isContract(address addr) public returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe core transfer function, just in case if rounding error causes pool to not have enough COREs. function safeCoreTransfer(address _to, uint256 _amount) internal { uint256 coreBal = core.balanceOf(address(this)); if (_amount > coreBal) { core.transfer(_to, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(_to, _amount); coreBalance = core.balanceOf(address(this)); } //Avoids possible recursion loop // proxy? transferDevFee(); } function transferDevFee() public { if(pending_DEV_rewards == 0) return; uint256 coreBal = core.balanceOf(address(this)); if (pending_DEV_rewards > coreBal) { core.transfer(devaddr, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(devaddr, pending_DEV_rewards); coreBalance = core.balanceOf(address(this)); } pending_DEV_rewards = 0; } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing CORE governance token holders to do this functions. function setDevFeeReciever(address _devaddr) public onlyOwner { devaddr = _devaddr; } address private _superAdmin; event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current super admin */ function superAdmin() public view returns (address) { return _superAdmin; } /** * @dev Throws if called by any account other than the superAdmin */ modifier onlySuperAdmin() { require(_superAdmin == _msgSender(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function burnSuperAdmin() public virtual onlySuperAdmin { emit SuperAdminTransfered(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function newSuperAdmin(address newOwner) public virtual onlySuperAdmin { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SuperAdminTransfered(_superAdmin, newOwner); _superAdmin = newOwner; } }
// Core Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
add
function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accCorePerShare: 0, withdrawable : _withdrawable }) ); }
// Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25
{ "func_code_index": [ 4226, 4947 ] }
8,497
CoreVault
contracts/CoreVault.sol
0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c
Solidity
CoreVault
contract CoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of COREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accCorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. COREs to distribute per block. uint256 accCorePerShare; // Accumulated COREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The CORE TOKEN! INBUNIERC20 public core; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; //// pending rewards awaiting anyone to massUpdate uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) { averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock)); } // Returns averge fees in this epoch function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) { averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function startNewEpoch() public { require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value); function initialize( INBUNIERC20 _core, address _devaddr, address superAdmin ) public initializer { OwnableUpgradeSafe.__Ownable_init(); DEV_FEE = 3000; core = _core; devaddr = _devaddr; contractStartBlock = block.number; _superAdmin = superAdmin; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accCorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's COREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing CORE governance consensus function setPoolWithdrawable( uint256 _pid, bool _withdrawable ) public onlyOwner { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 20.00% // Note contract owner is meant to be a governance contract allowing CORE governance consensus uint16 DEV_FEE; function setDevFee(uint16 _DEV_FEE) public onlyOwner { require(_DEV_FEE <= 6000, 'Dev fee clamped at 20%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending COREs on frontend. function pendingCore(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCorePerShare = pool.accCorePerShare; return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { console.log("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.add(updatePool(pid)); } pendingRewards = pendingRewards.sub(allRewards); } // ---- // Function that adds pending rewards, called by the CORE token. // ---- uint256 private coreBalance; function addPendingRewards(uint256 _) public { uint256 newRewards = core.balanceOf(address(this)).sub(coreBalance); if(newRewards > 0) { coreBalance = core.balanceOf(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.add(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) { PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get .div(totalAllocPoint); // we can do this because pools are only mass updated uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000); uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee); pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee); pool.accCorePerShare = pool.accCorePerShare.add( coreRewardToDistribute.mul(1e12).div(tokenSupply) ); } // Deposit tokens to CoreVault for CORE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function depositFor(address depositFor, uint256 _pid, uint256 _amount) public { // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // This is depositedFor address } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address emit Deposit(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{ PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount); _withdraw(_pid, _amount, owner, msg.sender); } // Withdraw tokens from CoreVault. function withdraw(uint256 _pid, uint256 _amount) public { _withdraw(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); massUpdatePools(); updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(address(to), _amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Withdraw(to, _pid, _amount); } function updateAndPayOutPending(uint256 _pid, address from) internal { uint256 pending = pendingCore(_pid, from); if(pending > 0) { safeCoreTransfer(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin { require(isContract(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).approve(contractAddress, _amount); } function isContract(address addr) public returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe core transfer function, just in case if rounding error causes pool to not have enough COREs. function safeCoreTransfer(address _to, uint256 _amount) internal { uint256 coreBal = core.balanceOf(address(this)); if (_amount > coreBal) { core.transfer(_to, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(_to, _amount); coreBalance = core.balanceOf(address(this)); } //Avoids possible recursion loop // proxy? transferDevFee(); } function transferDevFee() public { if(pending_DEV_rewards == 0) return; uint256 coreBal = core.balanceOf(address(this)); if (pending_DEV_rewards > coreBal) { core.transfer(devaddr, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(devaddr, pending_DEV_rewards); coreBalance = core.balanceOf(address(this)); } pending_DEV_rewards = 0; } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing CORE governance token holders to do this functions. function setDevFeeReciever(address _devaddr) public onlyOwner { devaddr = _devaddr; } address private _superAdmin; event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current super admin */ function superAdmin() public view returns (address) { return _superAdmin; } /** * @dev Throws if called by any account other than the superAdmin */ modifier onlySuperAdmin() { require(_superAdmin == _msgSender(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function burnSuperAdmin() public virtual onlySuperAdmin { emit SuperAdminTransfered(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function newSuperAdmin(address newOwner) public virtual onlySuperAdmin { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SuperAdminTransfered(_superAdmin, newOwner); _superAdmin = newOwner; } }
// Core Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
set
function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; }
// Update the given pool's COREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25
{ "func_code_index": [ 5145, 5522 ] }
8,498
CoreVault
contracts/CoreVault.sol
0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c
Solidity
CoreVault
contract CoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of COREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accCorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. COREs to distribute per block. uint256 accCorePerShare; // Accumulated COREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The CORE TOKEN! INBUNIERC20 public core; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; //// pending rewards awaiting anyone to massUpdate uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) { averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock)); } // Returns averge fees in this epoch function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) { averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function startNewEpoch() public { require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value); function initialize( INBUNIERC20 _core, address _devaddr, address superAdmin ) public initializer { OwnableUpgradeSafe.__Ownable_init(); DEV_FEE = 3000; core = _core; devaddr = _devaddr; contractStartBlock = block.number; _superAdmin = superAdmin; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accCorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's COREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing CORE governance consensus function setPoolWithdrawable( uint256 _pid, bool _withdrawable ) public onlyOwner { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 20.00% // Note contract owner is meant to be a governance contract allowing CORE governance consensus uint16 DEV_FEE; function setDevFee(uint16 _DEV_FEE) public onlyOwner { require(_DEV_FEE <= 6000, 'Dev fee clamped at 20%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending COREs on frontend. function pendingCore(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCorePerShare = pool.accCorePerShare; return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { console.log("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.add(updatePool(pid)); } pendingRewards = pendingRewards.sub(allRewards); } // ---- // Function that adds pending rewards, called by the CORE token. // ---- uint256 private coreBalance; function addPendingRewards(uint256 _) public { uint256 newRewards = core.balanceOf(address(this)).sub(coreBalance); if(newRewards > 0) { coreBalance = core.balanceOf(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.add(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) { PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get .div(totalAllocPoint); // we can do this because pools are only mass updated uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000); uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee); pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee); pool.accCorePerShare = pool.accCorePerShare.add( coreRewardToDistribute.mul(1e12).div(tokenSupply) ); } // Deposit tokens to CoreVault for CORE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function depositFor(address depositFor, uint256 _pid, uint256 _amount) public { // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // This is depositedFor address } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address emit Deposit(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{ PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount); _withdraw(_pid, _amount, owner, msg.sender); } // Withdraw tokens from CoreVault. function withdraw(uint256 _pid, uint256 _amount) public { _withdraw(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); massUpdatePools(); updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(address(to), _amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Withdraw(to, _pid, _amount); } function updateAndPayOutPending(uint256 _pid, address from) internal { uint256 pending = pendingCore(_pid, from); if(pending > 0) { safeCoreTransfer(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin { require(isContract(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).approve(contractAddress, _amount); } function isContract(address addr) public returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe core transfer function, just in case if rounding error causes pool to not have enough COREs. function safeCoreTransfer(address _to, uint256 _amount) internal { uint256 coreBal = core.balanceOf(address(this)); if (_amount > coreBal) { core.transfer(_to, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(_to, _amount); coreBalance = core.balanceOf(address(this)); } //Avoids possible recursion loop // proxy? transferDevFee(); } function transferDevFee() public { if(pending_DEV_rewards == 0) return; uint256 coreBal = core.balanceOf(address(this)); if (pending_DEV_rewards > coreBal) { core.transfer(devaddr, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(devaddr, pending_DEV_rewards); coreBalance = core.balanceOf(address(this)); } pending_DEV_rewards = 0; } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing CORE governance token holders to do this functions. function setDevFeeReciever(address _devaddr) public onlyOwner { devaddr = _devaddr; } address private _superAdmin; event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current super admin */ function superAdmin() public view returns (address) { return _superAdmin; } /** * @dev Throws if called by any account other than the superAdmin */ modifier onlySuperAdmin() { require(_superAdmin == _msgSender(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function burnSuperAdmin() public virtual onlySuperAdmin { emit SuperAdminTransfered(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function newSuperAdmin(address newOwner) public virtual onlySuperAdmin { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SuperAdminTransfered(_superAdmin, newOwner); _superAdmin = newOwner; } }
// Core Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
setPoolWithdrawable
function setPoolWithdrawable( uint256 _pid, bool _withdrawable ) public onlyOwner { poolInfo[_pid].withdrawable = _withdrawable; }
// Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing CORE governance consensus
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25
{ "func_code_index": [ 5684, 5856 ] }
8,499
CoreVault
contracts/CoreVault.sol
0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c
Solidity
CoreVault
contract CoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of COREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accCorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. COREs to distribute per block. uint256 accCorePerShare; // Accumulated COREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The CORE TOKEN! INBUNIERC20 public core; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; //// pending rewards awaiting anyone to massUpdate uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) { averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock)); } // Returns averge fees in this epoch function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) { averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function startNewEpoch() public { require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value); function initialize( INBUNIERC20 _core, address _devaddr, address superAdmin ) public initializer { OwnableUpgradeSafe.__Ownable_init(); DEV_FEE = 3000; core = _core; devaddr = _devaddr; contractStartBlock = block.number; _superAdmin = superAdmin; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accCorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's COREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing CORE governance consensus function setPoolWithdrawable( uint256 _pid, bool _withdrawable ) public onlyOwner { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 20.00% // Note contract owner is meant to be a governance contract allowing CORE governance consensus uint16 DEV_FEE; function setDevFee(uint16 _DEV_FEE) public onlyOwner { require(_DEV_FEE <= 6000, 'Dev fee clamped at 20%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending COREs on frontend. function pendingCore(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCorePerShare = pool.accCorePerShare; return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { console.log("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.add(updatePool(pid)); } pendingRewards = pendingRewards.sub(allRewards); } // ---- // Function that adds pending rewards, called by the CORE token. // ---- uint256 private coreBalance; function addPendingRewards(uint256 _) public { uint256 newRewards = core.balanceOf(address(this)).sub(coreBalance); if(newRewards > 0) { coreBalance = core.balanceOf(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.add(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) { PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get .div(totalAllocPoint); // we can do this because pools are only mass updated uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000); uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee); pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee); pool.accCorePerShare = pool.accCorePerShare.add( coreRewardToDistribute.mul(1e12).div(tokenSupply) ); } // Deposit tokens to CoreVault for CORE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function depositFor(address depositFor, uint256 _pid, uint256 _amount) public { // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // This is depositedFor address } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address emit Deposit(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{ PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount); _withdraw(_pid, _amount, owner, msg.sender); } // Withdraw tokens from CoreVault. function withdraw(uint256 _pid, uint256 _amount) public { _withdraw(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); massUpdatePools(); updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(address(to), _amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Withdraw(to, _pid, _amount); } function updateAndPayOutPending(uint256 _pid, address from) internal { uint256 pending = pendingCore(_pid, from); if(pending > 0) { safeCoreTransfer(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin { require(isContract(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).approve(contractAddress, _amount); } function isContract(address addr) public returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe core transfer function, just in case if rounding error causes pool to not have enough COREs. function safeCoreTransfer(address _to, uint256 _amount) internal { uint256 coreBal = core.balanceOf(address(this)); if (_amount > coreBal) { core.transfer(_to, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(_to, _amount); coreBalance = core.balanceOf(address(this)); } //Avoids possible recursion loop // proxy? transferDevFee(); } function transferDevFee() public { if(pending_DEV_rewards == 0) return; uint256 coreBal = core.balanceOf(address(this)); if (pending_DEV_rewards > coreBal) { core.transfer(devaddr, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(devaddr, pending_DEV_rewards); coreBalance = core.balanceOf(address(this)); } pending_DEV_rewards = 0; } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing CORE governance token holders to do this functions. function setDevFeeReciever(address _devaddr) public onlyOwner { devaddr = _devaddr; } address private _superAdmin; event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current super admin */ function superAdmin() public view returns (address) { return _superAdmin; } /** * @dev Throws if called by any account other than the superAdmin */ modifier onlySuperAdmin() { require(_superAdmin == _msgSender(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function burnSuperAdmin() public virtual onlySuperAdmin { emit SuperAdminTransfered(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function newSuperAdmin(address newOwner) public virtual onlySuperAdmin { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SuperAdminTransfered(_superAdmin, newOwner); _superAdmin = newOwner; } }
// Core Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
pendingCore
function pendingCore(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCorePerShare = pool.accCorePerShare; return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt); }
// View function to see pending COREs on frontend.
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25
{ "func_code_index": [ 6306, 6676 ] }
8,500
CoreVault
contracts/CoreVault.sol
0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c
Solidity
CoreVault
contract CoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of COREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accCorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. COREs to distribute per block. uint256 accCorePerShare; // Accumulated COREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The CORE TOKEN! INBUNIERC20 public core; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; //// pending rewards awaiting anyone to massUpdate uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) { averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock)); } // Returns averge fees in this epoch function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) { averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function startNewEpoch() public { require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value); function initialize( INBUNIERC20 _core, address _devaddr, address superAdmin ) public initializer { OwnableUpgradeSafe.__Ownable_init(); DEV_FEE = 3000; core = _core; devaddr = _devaddr; contractStartBlock = block.number; _superAdmin = superAdmin; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accCorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's COREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing CORE governance consensus function setPoolWithdrawable( uint256 _pid, bool _withdrawable ) public onlyOwner { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 20.00% // Note contract owner is meant to be a governance contract allowing CORE governance consensus uint16 DEV_FEE; function setDevFee(uint16 _DEV_FEE) public onlyOwner { require(_DEV_FEE <= 6000, 'Dev fee clamped at 20%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending COREs on frontend. function pendingCore(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCorePerShare = pool.accCorePerShare; return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { console.log("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.add(updatePool(pid)); } pendingRewards = pendingRewards.sub(allRewards); } // ---- // Function that adds pending rewards, called by the CORE token. // ---- uint256 private coreBalance; function addPendingRewards(uint256 _) public { uint256 newRewards = core.balanceOf(address(this)).sub(coreBalance); if(newRewards > 0) { coreBalance = core.balanceOf(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.add(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) { PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get .div(totalAllocPoint); // we can do this because pools are only mass updated uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000); uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee); pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee); pool.accCorePerShare = pool.accCorePerShare.add( coreRewardToDistribute.mul(1e12).div(tokenSupply) ); } // Deposit tokens to CoreVault for CORE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function depositFor(address depositFor, uint256 _pid, uint256 _amount) public { // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // This is depositedFor address } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address emit Deposit(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{ PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount); _withdraw(_pid, _amount, owner, msg.sender); } // Withdraw tokens from CoreVault. function withdraw(uint256 _pid, uint256 _amount) public { _withdraw(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); massUpdatePools(); updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(address(to), _amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Withdraw(to, _pid, _amount); } function updateAndPayOutPending(uint256 _pid, address from) internal { uint256 pending = pendingCore(_pid, from); if(pending > 0) { safeCoreTransfer(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin { require(isContract(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).approve(contractAddress, _amount); } function isContract(address addr) public returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe core transfer function, just in case if rounding error causes pool to not have enough COREs. function safeCoreTransfer(address _to, uint256 _amount) internal { uint256 coreBal = core.balanceOf(address(this)); if (_amount > coreBal) { core.transfer(_to, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(_to, _amount); coreBalance = core.balanceOf(address(this)); } //Avoids possible recursion loop // proxy? transferDevFee(); } function transferDevFee() public { if(pending_DEV_rewards == 0) return; uint256 coreBal = core.balanceOf(address(this)); if (pending_DEV_rewards > coreBal) { core.transfer(devaddr, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(devaddr, pending_DEV_rewards); coreBalance = core.balanceOf(address(this)); } pending_DEV_rewards = 0; } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing CORE governance token holders to do this functions. function setDevFeeReciever(address _devaddr) public onlyOwner { devaddr = _devaddr; } address private _superAdmin; event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current super admin */ function superAdmin() public view returns (address) { return _superAdmin; } /** * @dev Throws if called by any account other than the superAdmin */ modifier onlySuperAdmin() { require(_superAdmin == _msgSender(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function burnSuperAdmin() public virtual onlySuperAdmin { emit SuperAdminTransfered(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function newSuperAdmin(address newOwner) public virtual onlySuperAdmin { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SuperAdminTransfered(_superAdmin, newOwner); _superAdmin = newOwner; } }
// Core Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
massUpdatePools
function massUpdatePools() public { console.log("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.add(updatePool(pid)); } pendingRewards = pendingRewards.sub(allRewards); }
// Update reward vairables for all pools. Be careful of gas spending!
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25
{ "func_code_index": [ 6754, 7099 ] }
8,501
CoreVault
contracts/CoreVault.sol
0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c
Solidity
CoreVault
contract CoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of COREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accCorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. COREs to distribute per block. uint256 accCorePerShare; // Accumulated COREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The CORE TOKEN! INBUNIERC20 public core; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; //// pending rewards awaiting anyone to massUpdate uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) { averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock)); } // Returns averge fees in this epoch function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) { averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function startNewEpoch() public { require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value); function initialize( INBUNIERC20 _core, address _devaddr, address superAdmin ) public initializer { OwnableUpgradeSafe.__Ownable_init(); DEV_FEE = 3000; core = _core; devaddr = _devaddr; contractStartBlock = block.number; _superAdmin = superAdmin; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accCorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's COREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing CORE governance consensus function setPoolWithdrawable( uint256 _pid, bool _withdrawable ) public onlyOwner { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 20.00% // Note contract owner is meant to be a governance contract allowing CORE governance consensus uint16 DEV_FEE; function setDevFee(uint16 _DEV_FEE) public onlyOwner { require(_DEV_FEE <= 6000, 'Dev fee clamped at 20%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending COREs on frontend. function pendingCore(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCorePerShare = pool.accCorePerShare; return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { console.log("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.add(updatePool(pid)); } pendingRewards = pendingRewards.sub(allRewards); } // ---- // Function that adds pending rewards, called by the CORE token. // ---- uint256 private coreBalance; function addPendingRewards(uint256 _) public { uint256 newRewards = core.balanceOf(address(this)).sub(coreBalance); if(newRewards > 0) { coreBalance = core.balanceOf(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.add(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) { PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get .div(totalAllocPoint); // we can do this because pools are only mass updated uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000); uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee); pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee); pool.accCorePerShare = pool.accCorePerShare.add( coreRewardToDistribute.mul(1e12).div(tokenSupply) ); } // Deposit tokens to CoreVault for CORE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function depositFor(address depositFor, uint256 _pid, uint256 _amount) public { // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // This is depositedFor address } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address emit Deposit(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{ PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount); _withdraw(_pid, _amount, owner, msg.sender); } // Withdraw tokens from CoreVault. function withdraw(uint256 _pid, uint256 _amount) public { _withdraw(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); massUpdatePools(); updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(address(to), _amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Withdraw(to, _pid, _amount); } function updateAndPayOutPending(uint256 _pid, address from) internal { uint256 pending = pendingCore(_pid, from); if(pending > 0) { safeCoreTransfer(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin { require(isContract(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).approve(contractAddress, _amount); } function isContract(address addr) public returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe core transfer function, just in case if rounding error causes pool to not have enough COREs. function safeCoreTransfer(address _to, uint256 _amount) internal { uint256 coreBal = core.balanceOf(address(this)); if (_amount > coreBal) { core.transfer(_to, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(_to, _amount); coreBalance = core.balanceOf(address(this)); } //Avoids possible recursion loop // proxy? transferDevFee(); } function transferDevFee() public { if(pending_DEV_rewards == 0) return; uint256 coreBal = core.balanceOf(address(this)); if (pending_DEV_rewards > coreBal) { core.transfer(devaddr, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(devaddr, pending_DEV_rewards); coreBalance = core.balanceOf(address(this)); } pending_DEV_rewards = 0; } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing CORE governance token holders to do this functions. function setDevFeeReciever(address _devaddr) public onlyOwner { devaddr = _devaddr; } address private _superAdmin; event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current super admin */ function superAdmin() public view returns (address) { return _superAdmin; } /** * @dev Throws if called by any account other than the superAdmin */ modifier onlySuperAdmin() { require(_superAdmin == _msgSender(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function burnSuperAdmin() public virtual onlySuperAdmin { emit SuperAdminTransfered(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function newSuperAdmin(address newOwner) public virtual onlySuperAdmin { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SuperAdminTransfered(_superAdmin, newOwner); _superAdmin = newOwner; } }
// Core Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
updatePool
function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) { PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get .div(totalAllocPoint); // we can do this because pools are only mass updated uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000); uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee); pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee); pool.accCorePerShare = pool.accCorePerShare.add( coreRewardToDistribute.mul(1e12).div(tokenSupply) ); }
// Update reward variables of the given pool to be up-to-date.
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25
{ "func_code_index": [ 7731, 8738 ] }
8,502
CoreVault
contracts/CoreVault.sol
0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c
Solidity
CoreVault
contract CoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of COREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accCorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. COREs to distribute per block. uint256 accCorePerShare; // Accumulated COREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The CORE TOKEN! INBUNIERC20 public core; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; //// pending rewards awaiting anyone to massUpdate uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) { averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock)); } // Returns averge fees in this epoch function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) { averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function startNewEpoch() public { require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value); function initialize( INBUNIERC20 _core, address _devaddr, address superAdmin ) public initializer { OwnableUpgradeSafe.__Ownable_init(); DEV_FEE = 3000; core = _core; devaddr = _devaddr; contractStartBlock = block.number; _superAdmin = superAdmin; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accCorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's COREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing CORE governance consensus function setPoolWithdrawable( uint256 _pid, bool _withdrawable ) public onlyOwner { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 20.00% // Note contract owner is meant to be a governance contract allowing CORE governance consensus uint16 DEV_FEE; function setDevFee(uint16 _DEV_FEE) public onlyOwner { require(_DEV_FEE <= 6000, 'Dev fee clamped at 20%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending COREs on frontend. function pendingCore(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCorePerShare = pool.accCorePerShare; return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { console.log("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.add(updatePool(pid)); } pendingRewards = pendingRewards.sub(allRewards); } // ---- // Function that adds pending rewards, called by the CORE token. // ---- uint256 private coreBalance; function addPendingRewards(uint256 _) public { uint256 newRewards = core.balanceOf(address(this)).sub(coreBalance); if(newRewards > 0) { coreBalance = core.balanceOf(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.add(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) { PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get .div(totalAllocPoint); // we can do this because pools are only mass updated uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000); uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee); pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee); pool.accCorePerShare = pool.accCorePerShare.add( coreRewardToDistribute.mul(1e12).div(tokenSupply) ); } // Deposit tokens to CoreVault for CORE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function depositFor(address depositFor, uint256 _pid, uint256 _amount) public { // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // This is depositedFor address } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address emit Deposit(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{ PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount); _withdraw(_pid, _amount, owner, msg.sender); } // Withdraw tokens from CoreVault. function withdraw(uint256 _pid, uint256 _amount) public { _withdraw(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); massUpdatePools(); updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(address(to), _amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Withdraw(to, _pid, _amount); } function updateAndPayOutPending(uint256 _pid, address from) internal { uint256 pending = pendingCore(_pid, from); if(pending > 0) { safeCoreTransfer(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin { require(isContract(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).approve(contractAddress, _amount); } function isContract(address addr) public returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe core transfer function, just in case if rounding error causes pool to not have enough COREs. function safeCoreTransfer(address _to, uint256 _amount) internal { uint256 coreBal = core.balanceOf(address(this)); if (_amount > coreBal) { core.transfer(_to, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(_to, _amount); coreBalance = core.balanceOf(address(this)); } //Avoids possible recursion loop // proxy? transferDevFee(); } function transferDevFee() public { if(pending_DEV_rewards == 0) return; uint256 coreBal = core.balanceOf(address(this)); if (pending_DEV_rewards > coreBal) { core.transfer(devaddr, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(devaddr, pending_DEV_rewards); coreBalance = core.balanceOf(address(this)); } pending_DEV_rewards = 0; } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing CORE governance token holders to do this functions. function setDevFeeReciever(address _devaddr) public onlyOwner { devaddr = _devaddr; } address private _superAdmin; event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current super admin */ function superAdmin() public view returns (address) { return _superAdmin; } /** * @dev Throws if called by any account other than the superAdmin */ modifier onlySuperAdmin() { require(_superAdmin == _msgSender(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function burnSuperAdmin() public virtual onlySuperAdmin { emit SuperAdminTransfered(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function newSuperAdmin(address newOwner) public virtual onlySuperAdmin { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SuperAdminTransfered(_superAdmin, newOwner); _superAdmin = newOwner; } }
// Core Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
deposit
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
// Deposit tokens to CoreVault for CORE allocation.
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25
{ "func_code_index": [ 8799, 9506 ] }
8,503
CoreVault
contracts/CoreVault.sol
0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c
Solidity
CoreVault
contract CoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of COREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accCorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. COREs to distribute per block. uint256 accCorePerShare; // Accumulated COREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The CORE TOKEN! INBUNIERC20 public core; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; //// pending rewards awaiting anyone to massUpdate uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) { averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock)); } // Returns averge fees in this epoch function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) { averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function startNewEpoch() public { require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value); function initialize( INBUNIERC20 _core, address _devaddr, address superAdmin ) public initializer { OwnableUpgradeSafe.__Ownable_init(); DEV_FEE = 3000; core = _core; devaddr = _devaddr; contractStartBlock = block.number; _superAdmin = superAdmin; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accCorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's COREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing CORE governance consensus function setPoolWithdrawable( uint256 _pid, bool _withdrawable ) public onlyOwner { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 20.00% // Note contract owner is meant to be a governance contract allowing CORE governance consensus uint16 DEV_FEE; function setDevFee(uint16 _DEV_FEE) public onlyOwner { require(_DEV_FEE <= 6000, 'Dev fee clamped at 20%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending COREs on frontend. function pendingCore(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCorePerShare = pool.accCorePerShare; return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { console.log("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.add(updatePool(pid)); } pendingRewards = pendingRewards.sub(allRewards); } // ---- // Function that adds pending rewards, called by the CORE token. // ---- uint256 private coreBalance; function addPendingRewards(uint256 _) public { uint256 newRewards = core.balanceOf(address(this)).sub(coreBalance); if(newRewards > 0) { coreBalance = core.balanceOf(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.add(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) { PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get .div(totalAllocPoint); // we can do this because pools are only mass updated uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000); uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee); pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee); pool.accCorePerShare = pool.accCorePerShare.add( coreRewardToDistribute.mul(1e12).div(tokenSupply) ); } // Deposit tokens to CoreVault for CORE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function depositFor(address depositFor, uint256 _pid, uint256 _amount) public { // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // This is depositedFor address } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address emit Deposit(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{ PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount); _withdraw(_pid, _amount, owner, msg.sender); } // Withdraw tokens from CoreVault. function withdraw(uint256 _pid, uint256 _amount) public { _withdraw(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); massUpdatePools(); updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(address(to), _amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Withdraw(to, _pid, _amount); } function updateAndPayOutPending(uint256 _pid, address from) internal { uint256 pending = pendingCore(_pid, from); if(pending > 0) { safeCoreTransfer(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin { require(isContract(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).approve(contractAddress, _amount); } function isContract(address addr) public returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe core transfer function, just in case if rounding error causes pool to not have enough COREs. function safeCoreTransfer(address _to, uint256 _amount) internal { uint256 coreBal = core.balanceOf(address(this)); if (_amount > coreBal) { core.transfer(_to, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(_to, _amount); coreBalance = core.balanceOf(address(this)); } //Avoids possible recursion loop // proxy? transferDevFee(); } function transferDevFee() public { if(pending_DEV_rewards == 0) return; uint256 coreBal = core.balanceOf(address(this)); if (pending_DEV_rewards > coreBal) { core.transfer(devaddr, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(devaddr, pending_DEV_rewards); coreBalance = core.balanceOf(address(this)); } pending_DEV_rewards = 0; } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing CORE governance token holders to do this functions. function setDevFeeReciever(address _devaddr) public onlyOwner { devaddr = _devaddr; } address private _superAdmin; event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current super admin */ function superAdmin() public view returns (address) { return _superAdmin; } /** * @dev Throws if called by any account other than the superAdmin */ modifier onlySuperAdmin() { require(_superAdmin == _msgSender(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function burnSuperAdmin() public virtual onlySuperAdmin { emit SuperAdminTransfered(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function newSuperAdmin(address newOwner) public virtual onlySuperAdmin { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SuperAdminTransfered(_superAdmin, newOwner); _superAdmin = newOwner; } }
// Core Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
depositFor
function depositFor(address depositFor, uint256 _pid, uint256 _amount) public { // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // This is depositedFor address } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address emit Deposit(depositFor, _pid, _amount); }
// Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25
{ "func_code_index": [ 9700, 10527 ] }
8,504
CoreVault
contracts/CoreVault.sol
0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c
Solidity
CoreVault
contract CoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of COREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accCorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. COREs to distribute per block. uint256 accCorePerShare; // Accumulated COREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The CORE TOKEN! INBUNIERC20 public core; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; //// pending rewards awaiting anyone to massUpdate uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) { averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock)); } // Returns averge fees in this epoch function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) { averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function startNewEpoch() public { require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value); function initialize( INBUNIERC20 _core, address _devaddr, address superAdmin ) public initializer { OwnableUpgradeSafe.__Ownable_init(); DEV_FEE = 3000; core = _core; devaddr = _devaddr; contractStartBlock = block.number; _superAdmin = superAdmin; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accCorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's COREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing CORE governance consensus function setPoolWithdrawable( uint256 _pid, bool _withdrawable ) public onlyOwner { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 20.00% // Note contract owner is meant to be a governance contract allowing CORE governance consensus uint16 DEV_FEE; function setDevFee(uint16 _DEV_FEE) public onlyOwner { require(_DEV_FEE <= 6000, 'Dev fee clamped at 20%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending COREs on frontend. function pendingCore(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCorePerShare = pool.accCorePerShare; return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { console.log("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.add(updatePool(pid)); } pendingRewards = pendingRewards.sub(allRewards); } // ---- // Function that adds pending rewards, called by the CORE token. // ---- uint256 private coreBalance; function addPendingRewards(uint256 _) public { uint256 newRewards = core.balanceOf(address(this)).sub(coreBalance); if(newRewards > 0) { coreBalance = core.balanceOf(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.add(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) { PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get .div(totalAllocPoint); // we can do this because pools are only mass updated uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000); uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee); pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee); pool.accCorePerShare = pool.accCorePerShare.add( coreRewardToDistribute.mul(1e12).div(tokenSupply) ); } // Deposit tokens to CoreVault for CORE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function depositFor(address depositFor, uint256 _pid, uint256 _amount) public { // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // This is depositedFor address } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address emit Deposit(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{ PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount); _withdraw(_pid, _amount, owner, msg.sender); } // Withdraw tokens from CoreVault. function withdraw(uint256 _pid, uint256 _amount) public { _withdraw(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); massUpdatePools(); updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(address(to), _amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Withdraw(to, _pid, _amount); } function updateAndPayOutPending(uint256 _pid, address from) internal { uint256 pending = pendingCore(_pid, from); if(pending > 0) { safeCoreTransfer(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin { require(isContract(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).approve(contractAddress, _amount); } function isContract(address addr) public returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe core transfer function, just in case if rounding error causes pool to not have enough COREs. function safeCoreTransfer(address _to, uint256 _amount) internal { uint256 coreBal = core.balanceOf(address(this)); if (_amount > coreBal) { core.transfer(_to, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(_to, _amount); coreBalance = core.balanceOf(address(this)); } //Avoids possible recursion loop // proxy? transferDevFee(); } function transferDevFee() public { if(pending_DEV_rewards == 0) return; uint256 coreBal = core.balanceOf(address(this)); if (pending_DEV_rewards > coreBal) { core.transfer(devaddr, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(devaddr, pending_DEV_rewards); coreBalance = core.balanceOf(address(this)); } pending_DEV_rewards = 0; } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing CORE governance token holders to do this functions. function setDevFeeReciever(address _devaddr) public onlyOwner { devaddr = _devaddr; } address private _superAdmin; event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current super admin */ function superAdmin() public view returns (address) { return _superAdmin; } /** * @dev Throws if called by any account other than the superAdmin */ modifier onlySuperAdmin() { require(_superAdmin == _msgSender(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function burnSuperAdmin() public virtual onlySuperAdmin { emit SuperAdminTransfered(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function newSuperAdmin(address newOwner) public virtual onlySuperAdmin { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SuperAdminTransfered(_superAdmin, newOwner); _superAdmin = newOwner; } }
// Core Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
setAllowanceForPoolToken
function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, _pid, value); }
// Test coverage // [x] Does allowance update correctly?
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25
{ "func_code_index": [ 10597, 10858 ] }
8,505
CoreVault
contracts/CoreVault.sol
0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c
Solidity
CoreVault
contract CoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of COREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accCorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. COREs to distribute per block. uint256 accCorePerShare; // Accumulated COREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The CORE TOKEN! INBUNIERC20 public core; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; //// pending rewards awaiting anyone to massUpdate uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) { averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock)); } // Returns averge fees in this epoch function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) { averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function startNewEpoch() public { require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value); function initialize( INBUNIERC20 _core, address _devaddr, address superAdmin ) public initializer { OwnableUpgradeSafe.__Ownable_init(); DEV_FEE = 3000; core = _core; devaddr = _devaddr; contractStartBlock = block.number; _superAdmin = superAdmin; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accCorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's COREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing CORE governance consensus function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing CORE governance consensus function setPoolWithdrawable( uint256 _pid, bool _withdrawable ) public onlyOwner { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 20.00% // Note contract owner is meant to be a governance contract allowing CORE governance consensus uint16 DEV_FEE; function setDevFee(uint16 _DEV_FEE) public onlyOwner { require(_DEV_FEE <= 6000, 'Dev fee clamped at 20%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending COREs on frontend. function pendingCore(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCorePerShare = pool.accCorePerShare; return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { console.log("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.add(updatePool(pid)); } pendingRewards = pendingRewards.sub(allRewards); } // ---- // Function that adds pending rewards, called by the CORE token. // ---- uint256 private coreBalance; function addPendingRewards(uint256 _) public { uint256 newRewards = core.balanceOf(address(this)).sub(coreBalance); if(newRewards > 0) { coreBalance = core.balanceOf(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.add(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) { PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get .div(totalAllocPoint); // we can do this because pools are only mass updated uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000); uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee); pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee); pool.accCorePerShare = pool.accCorePerShare.add( coreRewardToDistribute.mul(1e12).div(tokenSupply) ); } // Deposit tokens to CoreVault for CORE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function depositFor(address depositFor, uint256 _pid, uint256 _amount) public { // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // This is depositedFor address } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address emit Deposit(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{ PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount); _withdraw(_pid, _amount, owner, msg.sender); } // Withdraw tokens from CoreVault. function withdraw(uint256 _pid, uint256 _amount) public { _withdraw(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); massUpdatePools(); updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(address(to), _amount); } user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); emit Withdraw(to, _pid, _amount); } function updateAndPayOutPending(uint256 _pid, address from) internal { uint256 pending = pendingCore(_pid, from); if(pending > 0) { safeCoreTransfer(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin { require(isContract(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).approve(contractAddress, _amount); } function isContract(address addr) public returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe core transfer function, just in case if rounding error causes pool to not have enough COREs. function safeCoreTransfer(address _to, uint256 _amount) internal { uint256 coreBal = core.balanceOf(address(this)); if (_amount > coreBal) { core.transfer(_to, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(_to, _amount); coreBalance = core.balanceOf(address(this)); } //Avoids possible recursion loop // proxy? transferDevFee(); } function transferDevFee() public { if(pending_DEV_rewards == 0) return; uint256 coreBal = core.balanceOf(address(this)); if (pending_DEV_rewards > coreBal) { core.transfer(devaddr, coreBal); coreBalance = core.balanceOf(address(this)); } else { core.transfer(devaddr, pending_DEV_rewards); coreBalance = core.balanceOf(address(this)); } pending_DEV_rewards = 0; } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing CORE governance token holders to do this functions. function setDevFeeReciever(address _devaddr) public onlyOwner { devaddr = _devaddr; } address private _superAdmin; event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current super admin */ function superAdmin() public view returns (address) { return _superAdmin; } /** * @dev Throws if called by any account other than the superAdmin */ modifier onlySuperAdmin() { require(_superAdmin == _msgSender(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function burnSuperAdmin() public virtual onlySuperAdmin { emit SuperAdminTransfered(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function newSuperAdmin(address newOwner) public virtual onlySuperAdmin { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SuperAdminTransfered(_superAdmin, newOwner); _superAdmin = newOwner; } }
// Core Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
withdrawFrom
function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{ PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount); _withdraw(_pid, _amount, owner, msg.sender); }
// Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25
{ "func_code_index": [ 10995, 11390 ] }
8,506