file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
./full_match/7700/0xDd89eF185faE0ed0e5E1c7784431A4fDb73fcaA0/sources/contracts/transferHelpers/BaseTransferHelper.sol
@notice Ensures a user has approved the module they're calling @param _user The address of the user
modifier onlyApprovedModule(address _user) { require(isModuleApproved(_user), "module has not been approved by user"); _; }
4,646,947
[ 1, 19869, 279, 729, 711, 20412, 326, 1605, 2898, 4565, 4440, 225, 389, 1355, 1021, 1758, 434, 326, 729, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 31639, 3120, 12, 2867, 389, 1355, 13, 288, 203, 3639, 2583, 12, 291, 3120, 31639, 24899, 1355, 3631, 315, 2978, 711, 486, 2118, 20412, 635, 729, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "../ERC721B.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721BStaticTokenURI is ERC721B, IERC721Metadata { // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual returns(string memory) { return staticTokenURI(tokenId); } /** * @dev See {IERC721Metadata-tokenURI}. */ function staticTokenURI(uint256 tokenId) public view virtual returns(string memory) { if(!_exists(tokenId)) revert NonExistentToken(); return _tokenURIs[tokenId]; } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { if(!_exists(tokenId)) revert NonExistentToken(); _tokenURIs[tokenId] = _tokenURI; } }
* @dev See {IERC721Metadata-tokenURI}./
function tokenURI(uint256 tokenId) public view virtual returns(string memory) { return staticTokenURI(tokenId); }
1,033,649
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 2277, 17, 2316, 3098, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 5024, 1135, 12, 1080, 3778, 13, 288, 203, 565, 327, 760, 1345, 3098, 12, 2316, 548, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x6ea5992aB4A78D5720bD12A089D13c073d04B55d/sources/CellarPoolShare.sol
"Address: call to non-contract"
require(isContract(target), "R5");
3,722,941
[ 1, 6, 1887, 30, 745, 358, 1661, 17, 16351, 6, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 291, 8924, 12, 3299, 3631, 315, 54, 25, 8863, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "./interfaces/IOniiChainDescriptor.sol"; import "./interfaces/IOniiChain.sol"; import "./libraries/NFTDescriptor.sol"; import "./libraries/DetailHelper.sol"; import "base64-sol/base64.sol"; /// @title Describes Onii /// @notice Produces a string containing the data URI for a JSON metadata string contract OniiChainDescriptor is IOniiChainDescriptor { /// @dev Max value for defining probabilities uint256 internal constant MAX = 100000; uint256[] internal BACKGROUND_ITEMS = [4000, 3400, 3080, 2750, 2400, 1900, 1200, 0]; uint256[] internal SKIN_ITEMS = [2000, 1000, 0]; uint256[] internal NOSE_ITEMS = [10, 0]; uint256[] internal MARK_ITEMS = [50000, 40000, 31550, 24550, 18550, 13550, 9050, 5550, 2550, 550, 50, 10, 0]; uint256[] internal EYEBROW_ITEMS = [65000, 40000, 20000, 10000, 4000, 0]; uint256[] internal MASK_ITEMS = [20000, 14000, 10000, 6000, 2000, 1000, 100, 0]; uint256[] internal EARRINGS_ITEMS = [50000, 38000, 28000, 20000, 13000, 8000, 5000, 2900, 1000, 100, 30, 0]; uint256[] internal ACCESSORY_ITEMS = [ 50000, 43000, 36200, 29700, 23400, 17400, 11900, 7900, 4400, 1400, 400, 200, 11, 1, 0 ]; uint256[] internal MOUTH_ITEMS = [ 80000, 63000, 48000, 36000, 27000, 19000, 12000, 7000, 4000, 2000, 1000, 500, 50, 0 ]; uint256[] internal HAIR_ITEMS = [ 97000, 94000, 91000, 88000, 85000, 82000, 79000, 76000, 73000, 70000, 67000, 64000, 61000, 58000, 55000, 52000, 49000, 46000, 43000, 40000, 37000, 34000, 31000, 28000, 25000, 22000, 19000, 16000, 13000, 10000, 3000, 1000, 0 ]; uint256[] internal EYE_ITEMS = [ 98000, 96000, 94000, 92000, 90000, 88000, 86000, 84000, 82000, 80000, 78000, 76000, 74000, 72000, 70000, 68000, 60800, 53700, 46700, 39900, 33400, 27200, 21200, 15300, 10600, 6600, 3600, 2600, 1700, 1000, 500, 100, 10, 0 ]; /// @inheritdoc IOniiChainDescriptor function tokenURI(IOniiChain oniiChain, uint256 tokenId) external view override returns (string memory) { NFTDescriptor.SVGParams memory params = getSVGParams(oniiChain, tokenId); params.background = getBackgroundId(params); string memory image = Base64.encode(bytes(NFTDescriptor.generateSVGImage(params))); string memory name = NFTDescriptor.generateName(params, tokenId); string memory description = NFTDescriptor.generateDescription(params); string memory attributes = NFTDescriptor.generateAttributes(params); return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( bytes( abi.encodePacked( '{"name":"', name, '", "description":"', description, '", "attributes":', attributes, ', "image": "', "data:image/svg+xml;base64,", image, '"}' ) ) ) ) ); } /// @inheritdoc IOniiChainDescriptor function generateHairId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, HAIR_ITEMS, this.generateHairId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateEyeId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, EYE_ITEMS, this.generateEyeId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateEyebrowId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, EYEBROW_ITEMS, this.generateEyebrowId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateNoseId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, NOSE_ITEMS, this.generateNoseId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateMouthId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, MOUTH_ITEMS, this.generateMouthId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateMarkId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, MARK_ITEMS, this.generateMarkId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateEarringsId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, EARRINGS_ITEMS, this.generateEarringsId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateAccessoryId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, ACCESSORY_ITEMS, this.generateAccessoryId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateMaskId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, MASK_ITEMS, this.generateMaskId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateSkinId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, SKIN_ITEMS, this.generateSkinId.selector, tokenId); } /// @dev Get SVGParams from OniiChain.Detail function getSVGParams(IOniiChain oniiChain, uint256 tokenId) private view returns (NFTDescriptor.SVGParams memory) { IOniiChain.Detail memory detail = oniiChain.details(tokenId); return NFTDescriptor.SVGParams({ hair: detail.hair, eye: detail.eye, eyebrow: detail.eyebrow, nose: detail.nose, mouth: detail.mouth, mark: detail.mark, earring: detail.earrings, accessory: detail.accessory, mask: detail.mask, skin: detail.skin, original: detail.original, background: 0, timestamp: detail.timestamp, creator: detail.creator }); } function getBackgroundId(NFTDescriptor.SVGParams memory params) private view returns (uint8) { uint256 score = itemScorePosition(params.hair, HAIR_ITEMS) + itemScoreProba(params.accessory, ACCESSORY_ITEMS) + itemScoreProba(params.earring, EARRINGS_ITEMS) + itemScoreProba(params.mask, MASK_ITEMS) + itemScorePosition(params.mouth, MOUTH_ITEMS) + (itemScoreProba(params.skin, SKIN_ITEMS) / 2) + itemScoreProba(params.skin, SKIN_ITEMS) + itemScoreProba(params.nose, NOSE_ITEMS) + itemScoreProba(params.mark, MARK_ITEMS) + itemScorePosition(params.eye, EYE_ITEMS) + itemScoreProba(params.eyebrow, EYEBROW_ITEMS); return DetailHelper.pickItems(score, BACKGROUND_ITEMS); } /// @dev Get item score based on his probability function itemScoreProba(uint8 item, uint256[] memory ITEMS) private pure returns (uint256) { uint256 raw = ((item == 1 ? MAX : ITEMS[item - 2]) - ITEMS[item - 1]); return ((raw >= 1000) ? raw * 6 : raw) / 1000; } /// @dev Get item score based on his index function itemScorePosition(uint8 item, uint256[] memory ITEMS) private pure returns (uint256) { uint256 raw = ITEMS[item - 1]; return ((raw >= 1000) ? raw * 6 : raw) / 1000; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "./IOniiChain.sol"; /// @title Describes Onii via URI interface IOniiChainDescriptor { /// @notice Produces the URI describing a particular Onii (token id) /// @dev Note this URI may be a data: URI with the JSON contents directly inlined /// @param oniiChain The OniiChain contract /// @param tokenId The ID of the token for which to produce a description /// @return The URI of the ERC721-compliant metadata function tokenURI(IOniiChain oniiChain, uint256 tokenId) external view returns (string memory); /// @notice Generate randomly an ID for the hair item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the hair item id function generateHairId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the eye item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the eye item id function generateEyeId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the eyebrow item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the eyebrow item id function generateEyebrowId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the nose item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the nose item id function generateNoseId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the mouth item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the mouth item id function generateMouthId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the mark item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the mark item id function generateMarkId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the earrings item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the earrings item id function generateEarringsId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the accessory item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the accessory item id function generateAccessoryId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the mask item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the mask item id function generateMaskId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly the skin colors /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the skin item id function generateSkinId(uint256 tokenId, uint256 seed) external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; /// @title OniiChain NFTs Interface interface IOniiChain { /// @notice Details about the Onii struct Detail { uint8 hair; uint8 eye; uint8 eyebrow; uint8 nose; uint8 mouth; uint8 mark; uint8 earrings; uint8 accessory; uint8 mask; uint8 skin; bool original; uint256 timestamp; address creator; } /// @notice Returns the details associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the Onii /// @return detail memory function details(uint256 tokenId) external view returns (Detail memory detail); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "./details/BackgroundDetail.sol"; import "./details/BodyDetail.sol"; import "./details/HairDetail.sol"; import "./details/MouthDetail.sol"; import "./details/NoseDetail.sol"; import "./details/EyesDetail.sol"; import "./details/EyebrowDetail.sol"; import "./details/MarkDetail.sol"; import "./details/AccessoryDetail.sol"; import "./details/EarringsDetail.sol"; import "./details/MaskDetail.sol"; import "./DetailHelper.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /// @notice Helper to generate SVGs library NFTDescriptor { struct SVGParams { uint8 hair; uint8 eye; uint8 eyebrow; uint8 nose; uint8 mouth; uint8 mark; uint8 earring; uint8 accessory; uint8 mask; uint8 background; uint8 skin; bool original; uint256 timestamp; address creator; } /// @dev Combine all the SVGs to generate the final image function generateSVGImage(SVGParams memory params) internal view returns (string memory) { return string( abi.encodePacked( generateSVGHead(), DetailHelper.getDetailSVG(address(BackgroundDetail), params.background), generateSVGFace(params), DetailHelper.getDetailSVG(address(EarringsDetail), params.earring), DetailHelper.getDetailSVG(address(HairDetail), params.hair), DetailHelper.getDetailSVG(address(MaskDetail), params.mask), DetailHelper.getDetailSVG(address(AccessoryDetail), params.accessory), generateCopy(params.original), "</svg>" ) ); } /// @dev Combine face items function generateSVGFace(SVGParams memory params) private view returns (string memory) { return string( abi.encodePacked( DetailHelper.getDetailSVG(address(BodyDetail), params.skin), DetailHelper.getDetailSVG(address(MarkDetail), params.mark), DetailHelper.getDetailSVG(address(MouthDetail), params.mouth), DetailHelper.getDetailSVG(address(NoseDetail), params.nose), DetailHelper.getDetailSVG(address(EyesDetail), params.eye), DetailHelper.getDetailSVG(address(EyebrowDetail), params.eyebrow) ) ); } /// @dev generate Json Metadata name function generateName(SVGParams memory params, uint256 tokenId) internal pure returns (string memory) { return string( abi.encodePacked( BackgroundDetail.getItemNameById(params.background), " Onii ", Strings.toString(tokenId) ) ); } /// @dev generate Json Metadata description function generateDescription(SVGParams memory params) internal pure returns (string memory) { return string( abi.encodePacked( "Generated by ", Strings.toHexString(uint256(uint160(params.creator))), " at ", Strings.toString(params.timestamp) ) ); } /// @dev generate SVG header function generateSVGHead() private pure returns (string memory) { return string( abi.encodePacked( '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px"', ' viewBox="0 0 420 420" style="enable-background:new 0 0 420 420;" xml:space="preserve">' ) ); } /// @dev generate the "Copy" SVG if the onii is not the original function generateCopy(bool original) private pure returns (string memory) { return !original ? string( abi.encodePacked( '<g id="Copy">', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M239.5,300.6c-4.9,1.8-5.9,8.1,1.3,4.1"/>', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M242.9,299.5c-2.6,0.8-1.8,4.3,0.8,4.2 C246.3,303.1,245.6,298.7,242.9,299.5"/>', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M247.5,302.9c0.2-1.6-1.4-4-0.8-5.4 c0.4-1.2,2.5-1.4,3.2-0.3c0.1,1.5-0.9,2.7-2.3,2.5"/>', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M250.6,295.4c1.1-0.1,2.2,0,3.3,0.1 c0.5-0.8,0.7-1.7,0.5-2.7"/>', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M252.5,299.1c0.5-1.2,1.2-2.3,1.4-3.5"/>', "</g>" ) ) : ""; } /// @dev generate Json Metadata attributes function generateAttributes(SVGParams memory params) internal pure returns (string memory) { return string( abi.encodePacked( "[", getJsonAttribute("Body", BodyDetail.getItemNameById(params.skin), false), getJsonAttribute("Hair", HairDetail.getItemNameById(params.hair), false), getJsonAttribute("Mouth", MouthDetail.getItemNameById(params.mouth), false), getJsonAttribute("Nose", NoseDetail.getItemNameById(params.nose), false), getJsonAttribute("Eyes", EyesDetail.getItemNameById(params.eye), false), getJsonAttribute("Eyebrow", EyebrowDetail.getItemNameById(params.eyebrow), false), abi.encodePacked( getJsonAttribute("Mark", MarkDetail.getItemNameById(params.mark), false), getJsonAttribute("Accessory", AccessoryDetail.getItemNameById(params.accessory), false), getJsonAttribute("Earrings", EarringsDetail.getItemNameById(params.earring), false), getJsonAttribute("Mask", MaskDetail.getItemNameById(params.mask), false), getJsonAttribute("Background", BackgroundDetail.getItemNameById(params.background), false), getJsonAttribute("Original", params.original ? "true" : "false", true), "]" ) ) ); } /// @dev Get the json attribute as /// { /// "trait_type": "Skin", /// "value": "Human" /// } function getJsonAttribute( string memory trait, string memory value, bool end ) private pure returns (string memory json) { return string(abi.encodePacked('{ "trait_type" : "', trait, '", "value" : "', value, '" }', end ? "" : ",")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; /// @title Helper for details generation library DetailHelper { /// @notice Call the library item function /// @param lib The library address /// @param id The item ID function getDetailSVG(address lib, uint8 id) internal view returns (string memory) { (bool success, bytes memory data) = lib.staticcall( abi.encodeWithSignature(string(abi.encodePacked("item_", Strings.toString(id), "()"))) ); require(success); return abi.decode(data, (string)); } /// @notice Generate a random number and return the index from the /// corresponding interval. /// @param max The maximum value to generate /// @param seed Used for the initialization of the number generator /// @param intervals the intervals /// @param selector Caller selector /// @param tokenId the current tokenId function generate( uint256 max, uint256 seed, uint256[] memory intervals, bytes4 selector, uint256 tokenId ) internal view returns (uint8) { uint256 generated = generateRandom(max, seed, tokenId, selector); return pickItems(generated, intervals); } /// @notice Generate random number between 1 and max /// @param max Maximum value of the random number /// @param seed Used for the initialization of the number generator /// @param tokenId Current tokenId used as seed /// @param selector Caller selector used as seed function generateRandom( uint256 max, uint256 seed, uint256 tokenId, bytes4 selector ) private view returns (uint256) { return (uint256( keccak256( abi.encodePacked(block.difficulty, block.number, tx.origin, tx.gasprice, selector, seed, tokenId) ) ) % (max + 1)) + 1; } /// @notice Pick an item for the given random value /// @param val The random value /// @param intervals The intervals for the corresponding items /// @return the item ID where : intervals[] index + 1 = item ID function pickItems(uint256 val, uint256[] memory intervals) internal pure returns (uint8) { for (uint256 i; i < intervals.length; i++) { if (val > intervals[i]) { return SafeCast.toUint8(i + 1); } } revert("DetailHelper::pickItems: No item"); } } // SPDX-License-Identifier: MIT /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides a function for encoding some bytes in base64 library Base64 { string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F))))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Background SVG generator library BackgroundDetail { /// @dev background N°1 => Ordinary function item_1() public pure returns (string memory) { return base("636363", "CFCFCF", "ABABAB"); } /// @dev background N°2 => Unusual function item_2() public pure returns (string memory) { return base("004A06", "61E89B", "12B55F"); } /// @dev background N°3 => Surprising function item_3() public pure returns (string memory) { return base("1A4685", "6BF0E3", "00ADC7"); } /// @dev background N°4 => Impressive function item_4() public pure returns (string memory) { return base("380113", "D87AE6", "8A07BA"); } /// @dev background N°5 => Extraordinary function item_5() public pure returns (string memory) { return base("A33900", "FAF299", "FF9121"); } /// @dev background N°6 => Phenomenal function item_6() public pure returns (string memory) { return base("000000", "C000E8", "DED52C"); } /// @dev background N°7 => Artistic function item_7() public pure returns (string memory) { return base("FF00E3", "E8E18B", "00C4AD"); } /// @dev background N°8 => Unreal function item_8() public pure returns (string memory) { return base("CCCC75", "54054D", "001E2E"); } /// @notice Return the background name of the given id /// @param id The background Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Ordinary"; } else if (id == 2) { name = "Unusual"; } else if (id == 3) { name = "Surprising"; } else if (id == 4) { name = "Impressive"; } else if (id == 5) { name = "Extraordinary"; } else if (id == 6) { name = "Phenomenal"; } else if (id == 7) { name = "Artistic"; } else if (id == 8) { name = "Unreal"; } } /// @dev The base SVG for the backgrounds function base( string memory stop1, string memory stop2, string memory stop3 ) private pure returns (string memory) { return string( abi.encodePacked( '<g id="Background">', '<radialGradient id="gradient" cx="210" cy="-134.05" r="210.025" gradientTransform="matrix(1 0 0 -1 0 76)" gradientUnits="userSpaceOnUse">', "<style>", ".color-anim {animation: col 6s infinite;animation-timing-function: ease-in-out;}", "@keyframes col {0%,51% {stop-color:none} 52% {stop-color:#FFBAF7} 53%,100% {stop-color:none}}", "</style>", "<stop offset='0' class='color-anim' style='stop-color:#", stop1, "'/>", "<stop offset='0.66' style='stop-color:#", stop2, "'><animate attributeName='offset' dur='18s' values='0.54;0.8;0.54' repeatCount='indefinite' keyTimes='0;.4;1'/></stop>", "<stop offset='1' style='stop-color:#", stop3, "'><animate attributeName='offset' dur='18s' values='0.86;1;0.86' repeatCount='indefinite'/></stop>", abi.encodePacked( "</radialGradient>", '<path fill="url(#gradient)" d="M390,420H30c-16.6,0-30-13.4-30-30V30C0,13.4,13.4,0,30,0h360c16.6,0,30,13.4,30,30v360C420,406.6,406.6,420,390,420z"/>', '<path id="Border" opacity="0.4" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-miterlimit="10" d="M383.4,410H36.6C21.9,410,10,398.1,10,383.4V36.6C10,21.9,21.9,10,36.6,10h346.8c14.7,0,26.6,11.9,26.6,26.6v346.8 C410,398.1,398.1,410,383.4,410z"/>', '<path id="Mask" opacity="0.1" fill="#48005E" d="M381.4,410H38.6C22.8,410,10,397.2,10,381.4V38.6 C10,22.8,22.8,10,38.6,10h342.9c15.8,0,28.6,12.8,28.6,28.6v342.9C410,397.2,397.2,410,381.4,410z"/>', "</g>" ) ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Body SVG generator library BodyDetail { /// @dev Body N°1 => Human function item_1() public pure returns (string memory) { return base("FFEBB4", "FFBE94"); } /// @dev Body N°2 => Shadow function item_2() public pure returns (string memory) { return base("2d2d2d", "000000"); } /// @dev Body N°3 => Light function item_3() public pure returns (string memory) { return base("ffffff", "696969"); } /// @notice Return the skin name of the given id /// @param id The skin Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Human"; } else if (id == 2) { name = "Shadow"; } else if (id == 3) { name = "Light"; } } /// @dev The base SVG for the body function base(string memory skin, string memory shadow) private pure returns (string memory) { string memory pathBase = "<path fill-rule='evenodd' clip-rule='evenodd' fill='#"; string memory strokeBase = "' stroke='#000000' stroke-linecap='round' stroke-miterlimit='10'"; return string( abi.encodePacked( '<g id="Body">', pathBase, skin, strokeBase, " d='M177.1,287.1c0.8,9.6,0.3,19.3-1.5,29.2c-0.5,2.5-2.1,4.7-4.5,6c-15.7,8.5-41.1,16.4-68.8,24.2c-7.8,2.2-9.1,11.9-2,15.7c69,37,140.4,40.9,215.4,6.7c6.9-3.2,7-12.2,0.1-15.4c-21.4-9.9-42.1-19.7-53.1-26.2c-2.5-1.5-4-3.9-4.3-6.5c-0.7-7.4-0.9-16.1-0.3-25.5c0.7-10.8,2.5-20.3,4.4-28.2'/>", abi.encodePacked( pathBase, shadow, "' d='M177.1,289c0,0,23.2,33.7,39.3,29.5s40.9-20.5,40.9-20.5c1.2-8.7,2.4-17.5,3.5-26.2c-4.6,4.7-10.9,10.2-19,15.3c-10.8,6.8-21,10.4-28.5,12.4L177.1,289z'/>", pathBase, skin, strokeBase, " d='M301.3,193.6c2.5-4.6,10.7-68.1-19.8-99.1c-29.5-29.9-96-34-128.1-0.3s-23.7,105.6-23.7,105.6s12.4,59.8,24.2,72c0,0,32.3,24.8,40.7,29.5c8.4,4.8,16.4,2.2,16.4,2.2c15.4-5.7,25.1-10.9,33.3-17.4'/>", pathBase ), skin, strokeBase, " d='M141.8,247.2c0.1,1.1-11.6,7.4-12.9-7.1c-1.3-14.5-3.9-18.2-9.3-34.5s9.1-8.4,9.1-8.4'/>", abi.encodePacked( pathBase, skin, strokeBase, " d='M254.8,278.1c7-8.6,13.9-17.2,20.9-25.8c1.2-1.4,2.9-2.1,4.6-1.7c3.9,0.8,11.2,1.2,12.8-6.7c2.3-11,6.5-23.5,12.3-33.6c3.2-5.7,0.7-11.4-2.2-15.3c-2.1-2.8-6.1-2.7-7.9,0.2c-2.6,4-5,7.9-7.6,11.9'/>", "<polygon fill-rule='evenodd' clip-rule='evenodd' fill='#", skin, "' points='272,237.4 251.4,270.4 260.9,268.6 276.9,232.4'/>", "<path d='M193.3,196.4c0.8,5.1,1,10.2,1,15.4c0,2.6-0.1,5.2-0.4,7.7c-0.3,2.6-0.7,5.1-1.3,7.6h-0.1c0.1-2.6,0.3-5.1,0.4-7.7c0.2-2.5,0.4-5.1,0.6-7.6c0.1-2.6,0.2-5.1,0.1-7.7C193.5,201.5,193.4,198.9,193.3,196.4L193.3,196.4z'/>", "<path fill='#", shadow ), "' d='M197.8,242.8l-7.9-3.5c-0.4-0.2-0.5-0.7-0.2-1.1l3.2-3.3c0.4-0.4,1-0.5,1.5-0.3l12.7,4.6c0.6,0.2,0.6,1.1-0.1,1.3l-8.7,2.4C198.1,242.9,197.9,242.9,197.8,242.8z'/>", "</g>" ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; import "./constants/Colors.sol"; /// @title Hair SVG generator library HairDetail { /// @dev Hair N°1 => Classic Brown function item_1() public pure returns (string memory) { return base(classicHairs(Colors.BROWN)); } /// @dev Hair N°2 => Classic Black function item_2() public pure returns (string memory) { return base(classicHairs(Colors.BLACK)); } /// @dev Hair N°3 => Classic Gray function item_3() public pure returns (string memory) { return base(classicHairs(Colors.GRAY)); } /// @dev Hair N°4 => Classic White function item_4() public pure returns (string memory) { return base(classicHairs(Colors.WHITE)); } /// @dev Hair N°5 => Classic Blue function item_5() public pure returns (string memory) { return base(classicHairs(Colors.BLUE)); } /// @dev Hair N°6 => Classic Yellow function item_6() public pure returns (string memory) { return base(classicHairs(Colors.YELLOW)); } /// @dev Hair N°7 => Classic Pink function item_7() public pure returns (string memory) { return base(classicHairs(Colors.PINK)); } /// @dev Hair N°8 => Classic Red function item_8() public pure returns (string memory) { return base(classicHairs(Colors.RED)); } /// @dev Hair N°9 => Classic Purple function item_9() public pure returns (string memory) { return base(classicHairs(Colors.PURPLE)); } /// @dev Hair N°10 => Classic Green function item_10() public pure returns (string memory) { return base(classicHairs(Colors.GREEN)); } /// @dev Hair N°11 => Classic Saiki function item_11() public pure returns (string memory) { return base(classicHairs(Colors.SAIKI)); } /// @dev Hair N°12 => Classic 2 Brown function item_12() public pure returns (string memory) { return base(classicTwoHairs(Colors.BROWN)); } /// @dev Hair N°13 => Classic 2 Black function item_13() public pure returns (string memory) { return base(classicTwoHairs(Colors.BLACK)); } /// @dev Hair N°14 => Classic 2 Gray function item_14() public pure returns (string memory) { return base(classicTwoHairs(Colors.GRAY)); } /// @dev Hair N°15 => Classic 2 White function item_15() public pure returns (string memory) { return base(classicTwoHairs(Colors.WHITE)); } /// @dev Hair N°16 => Classic 2 Blue function item_16() public pure returns (string memory) { return base(classicTwoHairs(Colors.BLUE)); } /// @dev Hair N°17 => Classic 2 Yellow function item_17() public pure returns (string memory) { return base(classicTwoHairs(Colors.YELLOW)); } /// @dev Hair N°18 => Classic 2 Pink function item_18() public pure returns (string memory) { return base(classicTwoHairs(Colors.PINK)); } /// @dev Hair N°19 => Classic 2 Red function item_19() public pure returns (string memory) { return base(classicTwoHairs(Colors.RED)); } /// @dev Hair N°20 => Classic 2 Purple function item_20() public pure returns (string memory) { return base(classicTwoHairs(Colors.PURPLE)); } /// @dev Hair N°21 => Classic 2 Green function item_21() public pure returns (string memory) { return base(classicTwoHairs(Colors.GREEN)); } /// @dev Hair N°22 => Classic 2 Saiki function item_22() public pure returns (string memory) { return base(classicTwoHairs(Colors.SAIKI)); } /// @dev Hair N°23 => Short Black function item_23() public pure returns (string memory) { return base(shortHairs(Colors.BLACK)); } /// @dev Hair N°24 => Short Blue function item_24() public pure returns (string memory) { return base(shortHairs(Colors.BLUE)); } /// @dev Hair N°25 => Short Pink function item_25() public pure returns (string memory) { return base(shortHairs(Colors.PINK)); } /// @dev Hair N°26 => Short White function item_26() public pure returns (string memory) { return base(shortHairs(Colors.WHITE)); } /// @dev Hair N°27 => Spike Black function item_27() public pure returns (string memory) { return base(spike(Colors.BLACK)); } /// @dev Hair N°28 => Spike Blue function item_28() public pure returns (string memory) { return base(spike(Colors.BLUE)); } /// @dev Hair N°29 => Spike Pink function item_29() public pure returns (string memory) { return base(spike(Colors.PINK)); } /// @dev Hair N°30 => Spike White function item_30() public pure returns (string memory) { return base(spike(Colors.WHITE)); } /// @dev Hair N°31 => Monk function item_31() public pure returns (string memory) { return base(monk()); } /// @dev Hair N°32 => Nihon function item_32() public pure returns (string memory) { return base( string( abi.encodePacked( monk(), '<path opacity="0.36" fill="#6E5454" stroke="#8A8A8A" stroke-width="0.5" stroke-miterlimit="10" d=" M287.5,206.8c0,0,0.1-17.4-2.9-20.3c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6 c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3 S111,72.1,216.8,70.4c108.4-1.7,87.1,121.7,85.1,122.4C295.4,190.1,293.9,197.7,287.5,206.8z"/>', '<g opacity="0.33">', '<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.367 227.089)" fill="#FFFFFF" cx="274.3" cy="113.1" rx="1.4" ry="5.3"/>', '<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.4151 255.0608)" fill="#FFFFFF" cx="254.1" cy="97.3" rx="4.2" ry="16.3"/>', "</g>", '<path fill="#FFFFFF" stroke="#2B232B" stroke-miterlimit="10" d="M136.2,125.1c0,0,72,9.9,162.2,0c0,0,4.4,14.9,4.8,26.6 c0,0-125.4,20.9-172.6-0.3C129.5,151.3,132.9,130.3,136.2,125.1z"/>', '<polygon fill="#FFFFFF" stroke="#2B232B" stroke-miterlimit="10" points="306.2,138 324.2,168.1 330,160"/>', '<path fill="#FFFFFF" stroke="#2B232B" stroke-miterlimit="10" d="M298.4,125.1l34.2,54.6l-18,15.5l-10.7-43.5 C302.3,142.2,299.9,128.8,298.4,125.1z"/>', '<ellipse opacity="0.87" fill="#FF0039" cx="198.2" cy="144.1" rx="9.9" ry="10.8"/>' ) ) ); } /// @dev Hair N°33 => Bald function item_33() public pure returns (string memory) { return base( string( abi.encodePacked( '<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.1733 226.5807)" fill="#FFFFFF" cx="273.6" cy="113.1" rx="1.4" ry="5.3"/>', '<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.1174 254.4671)" fill="#FFFFFF" cx="253.4" cy="97.3" rx="4.2" ry="16.3"/>' ) ) ); } /// @dev Generate classic hairs with the given color function classicHairs(string memory hairsColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", hairsColor, "' stroke='#000000' stroke-width='0.5' stroke-miterlimit='10' d='M252.4,71.8c0,0-15.1-13.6-42.6-12.3l15.6,8.8c0,0-12.9-0.9-28.4-1.3c-6.1-0.2-21.8,3.3-38.3-1.4c0,0,7.3,7.2,9.4,7.7c0,0-30.6,13.8-47.3,34.2c0,0,10.7-8.9,16.7-10.9c0,0-26,25.2-31.5,70c0,0,9.2-28.6,15.5-34.2c0,0-10.7,27.4-5.3,48.2c0,0,2.4-14.5,4.9-19.2c-1,14.1,2.4,33.9,13.8,47.8c0,0-3.3-15.8-2.2-21.9l8.8-17.9c0.1,4.1,1.3,8.1,3.1,12.3c0,0,13-36.1,19.7-43.9c0,0-2.9,15.4-1.1,29.6c0,0,6.8-23.5,16.9-36.8c0,0-4.6,15.6-2.7,31.9c0,0,9.4-26.2,10.4-28.2l-2.7,9.2c0,0,4.1,21.6,3.8,25.3c0,0,8.4-10.3,21.2-52l-2.9,12c0,0,9.8,20.3,10.3,22.2s-1.3-13.9-1.3-13.9s12.4,21.7,13.5,26c0,0,5.5-20.8,3.4-35.7l1.1,9.6c0,0,15,20.3,16.4,30.1s-0.1-23.4-0.1-23.4s13.8,30.6,17,39.4c0,0,1.9-17,1.4-19.4s8.5,34.6,4.4,46c0,0,11.7-16.4,11.5-21.4c1.4,0.8-1.3,22.6-4,26.3c0,0,3.2-0.3,8.4-9.3c0,0,11.1-13.4,11.8-11.7c0.7,1.7,1.8-2.9,5.5,10.2l2.6-7.6c0,0-0.4,15.4-3.3,21.4c0,0,14.3-32.5,10.4-58.7c0,0,3.7,9.3,4.4,16.9s3.1-32.8-7.7-51.4c0,0,6.9,3.9,10.8,4.8c0,0-12.6-12.5-13.6-15.9c0,0-14.1-25.7-39.1-34.6c0,0,9.3-3.2,15.6,0.2C286.5,78.8,271.5,66.7,252.4,71.8z'/>", '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M286,210c0,0,8.5-10.8,8.6-18.7"/>', '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M132.5,190.4c0,0-1.3-11.3,0.3-16.9"/>', '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M141.5,170c0,0-1-6.5,1.6-20.4"/>', '<path opacity="0.2" d="M267.7,151.7l-0.3,30.9c0,0,1.9-18.8,1.8-19.3s8.6,43.5,3.9,47.2c0,0,11.9-18.8,12.1-21.5s0,22-3.9,25c0,0,6-4.4,8.6-10.1c0,0,6.1-7,9.9-10.7c0,0,3.9-1,6.8,8.2l2.8-6.9c0,0,0.1,13.4-1.3,16.1c0,0,10.5-28.2,7.9-52.9c0,0,4.7,8.3,4.9,17.1c0.1,8.8,1.7-8.6,0.2-17.8c0,0-6.5-13.9-8.2-15.4c0,0,2.2,14.9,1.3,18.4c0,0-8.2-15.1-11.4-17.3c0,0,1.2,41-1.6,46.1c0,0-6.8-22.7-11.4-26.5c0,0,0.7,17.4-3.6,23.2C284.5,183.3,280.8,169.9,267.7,151.7z"/>', '<path opacity="0.2" d="M234.3,137.1c0,0,17.1,23.2,16.7,30.2s-0.2-13.3-0.2-13.3s-11.7-22-17.6-26.2L234.3,137.1z"/>', '<polygon opacity="0.2" points="250.7,143.3 267.5,162.9 267.3,181.9"/>', '<path opacity="0.2" d="M207.4,129.2l9.7,20.7l-1-13.7c0,0,11.6,21,13.5,25.4l1.4-5l-17.6-27.4l1,7.5l-6-12.6L207.4,129.2z"/>', '<path opacity="0.2" d="M209.2,118c0,0-13.7,36.6-18.5,40.9c-1.7-7.2-1.9-7.9-4.2-20.3c0,0-0.1,2.7-1.4,5.3c0.7,8.2,4.1,24.4,4,24.5S206.4,136.6,209.2,118z"/>', '<path opacity="0.2" d="M187.6,134.7c0,0-9.6,25.5-10,26.9l-0.4-3.6C177.1,158.1,186.8,135.8,187.6,134.7z"/>', '<path opacity="0.2" fill-rule="evenodd" clip-rule="evenodd" d="M180.7,129.6c0,0-16.7,22.3-17.7,24.2s0,12.4,0.3,12.8S165.9,153,180.7,129.6z"/>', '<path opacity="0.2" fill-rule="evenodd" clip-rule="evenodd" d="M180.4,130.6c0,0-0.2,20.5-0.6,21.5c-0.4,0.9-2.6,5.8-2.6,5.8S176.1,147.1,180.4,130.6z"/>', abi.encodePacked( '<path opacity="0.2" d="M163.9,138c0,0-16.3,25.3-17.9,26.3c0,0-3.8-12.8-3-14.7s-9.6,10.3-9.9,17c0,0-8.4-0.6-11-7.4c-1-2.5,1.4-9.1,2.1-12.2c0,0-6.5,7.9-9.4,22.5c0,0,0.6,8.8,1.1,10c0,0,3.5-14.8,4.9-17.7c0,0-0.3,33.3,13.6,46.7c0,0-3.7-18.6-2.6-21l9.4-18.6c0,0,2.1,10.5,3.1,12.3l13.9-33.1L163.9,138z"/>', '<path fill="#FFFFFF" d="M204,82.3c0,0-10.3,24.4-11.5,30.4c0,0,11.1-20.6,12.6-20.8c0,0,11.4,20.4,12,22.2C217.2,114.1,208.2,88.2,204,82.3z"/>', '<path fill="#FFFFFF" d="M185.6,83.5c0,0-1,29.2,0,39.2c0,0-4-21.4-3.6-25.5c0.4-4-13.5,19.6-16,23.9c0,0,7.5-20.6,10.5-25.8c0,0-14.4,9.4-22,21.3C154.6,116.7,170.1,93.4,185.6,83.5z"/>', '<path fill="#FFFFFF" d="M158.6,96.2c0,0-12,15.3-14.7,23.2"/>', '<path fill="#FFFFFF" d="M125.8,125.9c0,0,9.5-20.6,23.5-27.7"/>', '<path fill="#FFFFFF" d="M296.5,121.6c0,0-9.5-20.6-23.5-27.7"/>', '<path fill="#FFFFFF" d="M216.1,88.5c0,0,10.9,19.9,11.6,23.6s3.7-5.5-10.6-23.6"/>', '<path fill="#FFFFFF" d="M227,92c0,0,21.1,25.4,22,27.4s-4.9-23.8-12.9-29.5c0,0,9.5,20.7,9.9,21.9C246.3,113,233.1,94.1,227,92z"/>', '<path fill="#FFFFFF" d="M263.1,119.5c0,0-9.5-26.8-10.6-28.3s15.5,14.1,16.2,22.5c0,0-11.1-16.1-11.8-16.9C256.1,96,264.3,114.1,263.1,119.5z"/>' ) ) ); } /// @dev Generate classic 2 hairs with the given color function classicTwoHairs(string memory hairsColor) private pure returns (string memory) { return string( abi.encodePacked( "<polygon fill='#", hairsColor, "' points='188.2,124.6 198.3,128.1 211.2,124.3 197.8,113.2'/>", '<polygon opacity="0.5" points="188.4,124.7 198.3,128.1 211.7,124.2 197.7,113.6"/>', "<path fill='#", hairsColor, "' stroke='#000000' stroke-width='0.5' stroke-miterlimit='10' d='M274,209.6c1,0.9,10.1-12.8,10.5-18.3 c1.1,3.2-0.2,16.8-2.9,20.5c0,0,3.7-0.7,8.3-6.5c0,0,11.1-13.4,11.8-11.7c0.7,1.7,1.8-2.9,5.5,10.2l2.6-7.6 c0,0-0.4,15.4-3.3,21.4c0,0,14.3-32.5,10.4-58.7c0,0,3.7,9.3,4.4,16.9s3.1-32.8-7.7-51.4c0,0,6.9,3.9,10.8,4.8 c0,0-12.6-12.5-13.6-15.9c0,0-14.1-25.7-39.1-34.6c0,0,9.3-3.2,15.6,0.2c-0.1-0.1-15.1-12.2-34.2-7.1c0,0-15.1-13.6-42.6-12.3 l15.6,8.8c0,0-12.9-0.9-28.4-1.3c-6.1-0.2-21.8,3.3-38.3-1.4c0,0,7.3,7.2,9.4,7.7c0,0-30.6,13.8-47.3,34.2 c0,0,10.7-8.9,16.7-10.9c0,0-26,25.2-31.5,70c0,0,9.2-28.6,15.5-34.2c0,0-10.7,27.4-5.3,48.2c0,0,2.4-14.5,4.9-19.2 c-1,14.1,2.4,33.9,13.8,47.8c0,0-3.3-15.8-2.2-21.9l8.8-17.9c0.1,4.1,1.3,8.1,3.1,12.3c0,0,13-36.1,19.7-43.9 c0,0-2.9,15.4-1.1,29.6c0,0,7.2-26.8,17.3-40.1c0,0,0.8,0.1,17.6-7.6c6.3,3.1,8,1.4,17.9,7.7c4.1,5.3,13.8,31.9,15.6,41.5 c3.4-7.3,5.6-19,5.2-29.5c2.7,3.7,8.9,19.9,9.6,34.3c0,0,7.9-15.9,5.9-29c0-0.2,0.2,14.5,0.3,14.3c0,0,12.1,19.9,14.9,19.7 c0-0.8-1.7-12.9-1.7-12.8c1.3,5.8,2.8,23.3,3.1,27.1l5-9.5C276.2,184,276.8,204.9,274,209.6z'/>", '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M286.7,210c0,0,8.5-10.8,8.6-18.7"/>', '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M133.2,190.4 c0,0-1.3-11.3,0.3-16.9"/>', abi.encodePacked( '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M142.2,170 c0,0-1-6.5,1.6-20.4"/>', '<path opacity="0.2" fill-rule="evenodd" clip-rule="evenodd" d="M180.6,128.2 c0,0-15.9,23.7-16.9,25.6s0,12.4,0.3,12.8S165.8,151.6,180.6,128.2z"/>', '<path opacity="0.2" d="M164.6,138c0,0-16.3,25.3-17.9,26.3c0,0-3.8-12.8-3-14.7s-9.6,10.3-9.9,17 c0,0-8.4-0.6-11-7.4c-1-2.5,1.4-9.1,2.1-12.2c0,0-6.5,7.9-9.4,22.5c0,0,0.6,8.8,1.1,10c0,0,3.5-14.8,4.9-17.7 c0,0-0.3,33.3,13.6,46.7c0,0-3.7-18.6-2.6-21l9.4-18.6c0,0,2.1,10.5,3.1,12.3l13.9-33.1L164.6,138z"/>', '<path opacity="0.16" d="M253.3,155.9c0.8,4.4,8.1,12.1,13.1,11.7l1.6,11c0,0-5.2-3.9-14.7-19.9 V155.9z"/>', '<path opacity="0.16" d="M237.6,139.4c0,0,4.4,3,13.9,21.7c0,0-4.3,12-4.6,12.4 C246.6,173.9,248.5,162.8,237.6,139.4z"/>', '<path opacity="0.17" d="M221,136.7c0,0,5.2,4,14.4,23c0,0-1.2,4.6-3.1,8.9 C227.7,152.4,227.1,149.9,221,136.7z"/>', '<path opacity="0.2" d="M272.1,152.6c-2.4,8.1-3.6,13.8-4.9,17.9c0,0,1.3,12.8,2.1,22.2 c4.7-8.4,5.4-8.8,5.4-9c-0.1-0.5,3.6,11.2-0.7,25.9c1.6,1,13.3-16.9,11.9-20.6c-1-2.5-0.4,19.8-4.3,22.8c0,0,6.4-2.2,9-7.9 c0,0,6.1-7,9.9-10.7c0,0,3.9-1,6.8,8.2l2.8-6.9c0,0,0.1,13.4-1.3,16.1c0,0,10.5-28.2,7.9-52.9c0,0,4.7,8.3,4.9,17.1 c0.1,8.8,1.7-8.6,0.2-17.8c0,0-6.5-13.9-8.2-15.4c0,0,2.2,14.9,1.3,18.4c0,0-8.2-15.1-11.4-17.3c0,0,1.2,41-1.6,46.1 c0,0-6.8-22.7-11.4-26.5c0,0-1.8,15.7-5,22.9C283.7,183,280.5,166.7,272.1,152.6z"/>' ), abi.encodePacked( '<path opacity="0.14" d="M198.2,115.2c-0.9-3.9,3.2-35.1,34.7-36C227.6,78.5,198.9,99.8,198.2,115.2z"/>', '<g opacity="0.76">', '<path fill="#FFFFFF" d="M153,105.9c0,0-12,15.3-14.7,23.2"/>', '<path fill="#FFFFFF" d="M126.5,125.9c0,0,9.5-20.6,23.5-27.7"/>', '<path fill="#FFFFFF" d="M297.2,121.6c0,0-9.5-20.6-23.5-27.7"/>', '<path fill="#FFFFFF" d="M241.9,109.4c0,0,10.9,19.9,11.6,23.6s3.7-5.5-10.6-23.6"/>', '<path fill="#FFFFFF" d="M155.1,117.3c0,0-10.9,19.9-11.6,23.6s-3.7-5.5,10.6-23.6"/>', '<path fill="#FFFFFF" d="M256.1,101.5c0,0,21.1,25.4,22,27.4c0.9,2-4.9-23.8-12.9-29.5c0,0,9.5,20.7,9.9,21.9 C275.4,122.5,262.2,103.6,256.1,101.5z"/>', '<path fill="#FFFFFF" d="M230,138.5c0,0-12.9-24.9-14.1-26.4c-1.2-1.4,18.2,11.9,19.3,20.2c0,0-11.9-13-12.7-13.7 C221.8,117.9,230.9,133,230,138.5z"/>', '<path fill="#FFFFFF" d="M167,136.6c0,0,15.5-24.5,17-25.8c1.5-1.2-19.1,10.6-21.6,18.8c0,0,15-13.5,15.8-14.2 C179.2,114.8,166.8,130.9,167,136.6z"/>', "</g>" ) ) ); } /// @dev Generate mohawk with the given color function spike(string memory hairsColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", hairsColor, "' d='M287.3,207.1c0,0-0.4-17.7-3.4-20.6c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3c0.9-0.2-19.1-126.3,86.7-126.8c108.4-0.3,87.1,121.7,85.1,122.4C294.5,191.6,293.7,198,287.3,207.1z'/>", '<path fill-rule="evenodd" clip-rule="evenodd" fill="#212121" stroke="#000000" stroke-miterlimit="10" d="M196,124.6c0,0-30.3-37.5-20.6-77.7c0,0,0.7,18,12,25.1c0,0-8.6-13.4-0.3-33.4c0,0,2.7,15.8,10.7,23.4c0,0-2.7-18.4,2.2-29.6c0,0,9.7,23.2,13.9,26.3c0,0-6.5-17.2,5.4-27.7c0,0-0.8,18.6,9.8,25.4c0,0-2.7-11,4-18.9c0,0,1.2,25.1,6.6,29.4c0,0-2.7-12,2.1-20c0,0,6,24,8.6,28.5c-9.1-2.6-17.9-3.2-26.6-3C223.7,72.3,198,80.8,196,124.6z"/>', crop() ) ); } function shortHairs(string memory hairsColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", hairsColor, "' d='M287.3,207.1c0,0-0.4-17.7-3.4-20.6c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3c0.9-0.2-19.1-126.3,86.7-126.8c108.4-0.3,87.1,121.7,85.1,122.4C294.5,191.6,293.7,198,287.3,207.1z'/>", '<path fill="#212121" stroke="#000000" stroke-miterlimit="10" d="M134.9,129.3c1-8.7,2.8-19.9,2.6-24.1 c1.1,2,4.4,6.1,4.7,6.9c2-15.1,3.9-18.6,6.6-28.2c0.1,5.2,0.4,6.1,4.6,11.9c0.1-7,4.5-17.6,8.8-24.3c0.6,3,4,8.2,5.8,10.7 c2.4-7,8.6-13.4,14.5-17.9c-0.3,3.4-0.1,6.8,0.7,10.1c4.9-5.1,7.1-8.7,15.6-15.4c-0.2,4.5,1.8,9,5.1,12c4.1-3.7,7.7-8,10.6-12.7 c0.6,3.7,1.4,7.3,2.5,10.8c2.6-4.6,7.9-8.4,12.4-11.3c1.5,3.5,1.3,11,5.9,11.7c7.1,1.1,10-3.3,11.4-10.1 c2.2,6.6,4.8,12.5,9.4,17.7c4.2,0.5,5.7-5.6,4.2-9c4.2,5.8,8.4,11.6,12.5,17.4c0.7-2.9,0.9-5.9,0.6-8.8 c3.4,7.6,9.1,16.7,13.6,23.6c0-1.9,1.8-8.5,1.8-10.4c2.6,7.3,7.7,17.9,10.3,36.6c0.2,1.1-23.8,7.5-28.8,10.1 c-1.2-2.3-2.2-4.3-6.2-8c-12.1-5.7-35.6-7.9-54.5-2.2c-16.3,4.8-21.5-2.3-31.3-3.1c-11.8-1.8-31.1-1.7-36.2,10.7 C139.6,133.6,137.9,132.2,134.9,129.3z"/>', '<polygon fill="#212121" points="270.7,138.4 300.2,129 300.7,131.1 271.3,139.9"/>', '<polygon fill="#212121" points="141.1,137 134,131.7 133.8,132.9 140.8,137.7 "/>', crop() ) ); } /// @dev Generate crop SVG function crop() private pure returns (string memory) { return string( abi.encodePacked( '<g id="Light" opacity="0.14">', '<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.1603 226.5965)" fill="#FFFFFF" cx="273.6" cy="113.1" rx="1.4" ry="5.3"/>', '<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.0969 254.4865)" fill="#FFFFFF" cx="253.4" cy="97.3" rx="4.2" ry="16.3"/>', "</g>", '<path opacity="0.05" fill-rule="evenodd" clip-rule="evenodd" d="M276.4,163.7c0,0,0.2-1.9,0.2,14.1c0,0,6.5,7.5,8.5,11s2.6,17.8,2.6,17.8l7-11.2c0,0,1.8-3.2,6.6-2.6c0,0,5.6-13.1,2.2-42.2C303.5,150.6,294.2,162.1,276.4,163.7z"/>', '<path opacity="0.1" fill-rule="evenodd" clip-rule="evenodd" d="M129.2,194.4c0,0-0.7-8.9,6.8-20.3c0,0-0.2-21.2,1.3-22.9c-3.7,0-6.7-0.5-7.7-2.4C129.6,148.8,125.8,181.5,129.2,194.4z"/>' ) ); } /// @dev Generate monk SVG function monk() private pure returns (string memory) { return string( abi.encodePacked( '<path opacity="0.36" fill="#6E5454" stroke="#8A8A8A" stroke-width="0.5" stroke-miterlimit="10" d="M286.8,206.8c0,0,0.1-17.4-2.9-20.3c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3S110.3,72.1,216.1,70.4c108.4-1.7,87.1,121.7,85.1,122.4C294.7,190.1,293.2,197.7,286.8,206.8z"/>', '<g id="Bald" opacity="0.33">', '<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.1603 226.5965)" fill="#FFFFFF" cx="273.6" cy="113.1" rx="1.4" ry="5.3"/>', '<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.0969 254.4865)" fill="#FFFFFF" cx="253.4" cy="97.3" rx="4.2" ry="16.3"/>', "</g>" ) ); } /// @notice Return the hair cut name of the given id /// @param id The hair Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic Brown"; } else if (id == 2) { name = "Classic Black"; } else if (id == 3) { name = "Classic Gray"; } else if (id == 4) { name = "Classic White"; } else if (id == 5) { name = "Classic Blue"; } else if (id == 6) { name = "Classic Yellow"; } else if (id == 7) { name = "Classic Pink"; } else if (id == 8) { name = "Classic Red"; } else if (id == 9) { name = "Classic Purple"; } else if (id == 10) { name = "Classic Green"; } else if (id == 11) { name = "Classic Saiki"; } else if (id == 12) { name = "Classic Brown"; } else if (id == 13) { name = "Classic 2 Black"; } else if (id == 14) { name = "Classic 2 Gray"; } else if (id == 15) { name = "Classic 2 White"; } else if (id == 16) { name = "Classic 2 Blue"; } else if (id == 17) { name = "Classic 2 Yellow"; } else if (id == 18) { name = "Classic 2 Pink"; } else if (id == 19) { name = "Classic 2 Red"; } else if (id == 20) { name = "Classic 2 Purple"; } else if (id == 21) { name = "Classic 2 Green"; } else if (id == 22) { name = "Classic 2 Saiki"; } else if (id == 23) { name = "Short Black"; } else if (id == 24) { name = "Short Blue"; } else if (id == 25) { name = "Short Pink"; } else if (id == 26) { name = "Short White"; } else if (id == 27) { name = "Spike Black"; } else if (id == 28) { name = "Spike Blue"; } else if (id == 29) { name = "Spike Pink"; } else if (id == 30) { name = "Spike White"; } else if (id == 31) { name = "Monk"; } else if (id == 32) { name = "Nihon"; } else if (id == 33) { name = "Bald"; } } /// @dev The base SVG for the hair function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Hair">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Mouth SVG generator library MouthDetail { /// @dev Mouth N°1 => Neutral function item_1() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M178.3,262.7c3.3-0.2,6.6-0.1,9.9,0c3.3,0.1,6.6,0.3,9.8,0.8c-3.3,0.3-6.6,0.3-9.9,0.2C184.8,263.6,181.5,263.3,178.3,262.7z"/>', '<path d="M201.9,263.4c1.2-0.1,2.3-0.1,3.5-0.2l3.5-0.2l6.9-0.3c2.3-0.1,4.6-0.2,6.9-0.4c1.2-0.1,2.3-0.2,3.5-0.3l1.7-0.2c0.6-0.1,1.1-0.2,1.7-0.2c-2.2,0.8-4.5,1.1-6.8,1.4s-4.6,0.5-7,0.6c-2.3,0.1-4.6,0.2-7,0.1C206.6,263.7,204.3,263.6,201.9,263.4z"/>', '<path d="M195.8,271.8c0.8,0.5,1.8,0.8,2.7,1s1.8,0.4,2.7,0.5s1.8,0,2.8-0.1c0.9-0.1,1.8-0.5,2.8-0.8c-0.7,0.7-1.6,1.3-2.6,1.6c-1,0.3-2,0.5-3,0.4s-2-0.3-2.9-0.8C197.3,273.2,196.4,272.7,195.8,271.8z"/>' ) ) ); } /// @dev Mouth N°2 => Smile function item_2() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M178.2,259.6c1.6,0.5,3.3,0.9,4.9,1.3c1.6,0.4,3.3,0.8,4.9,1.1c1.6,0.4,3.3,0.6,4.9,0.9c1.7,0.3,3.3,0.4,5,0.6c-1.7,0.2-3.4,0.3-5.1,0.2c-1.7-0.1-3.4-0.3-5.1-0.7C184.5,262.3,181.2,261.2,178.2,259.6z"/>', '<path d="M201.9,263.4l7-0.6c2.3-0.2,4.7-0.4,7-0.7c2.3-0.2,4.6-0.6,6.9-1c0.6-0.1,1.2-0.2,1.7-0.3l1.7-0.4l1.7-0.5l1.6-0.7c-0.5,0.3-1,0.7-1.5,0.9l-1.6,0.8c-1.1,0.4-2.2,0.8-3.4,1.1c-2.3,0.6-4.6,1-7,1.3s-4.7,0.4-7.1,0.5C206.7,263.6,204.3,263.6,201.9,263.4z"/>', '<path d="M195.8,271.8c0.8,0.5,1.8,0.8,2.7,1s1.8,0.4,2.7,0.5s1.8,0,2.8-0.1c0.9-0.1,1.8-0.5,2.8-0.8c-0.7,0.7-1.6,1.3-2.6,1.6c-1,0.3-2,0.5-3,0.4s-2-0.3-2.9-0.8C197.3,273.2,196.4,272.7,195.8,271.8z"/>' ) ) ); } /// @dev Mouth N°3 => Sulk function item_3() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M179.2,263.2c0,0,24.5,3.1,43.3-0.6"/>', '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M176.7,256.8c0,0,6.7,6.8-0.6,11"/>', '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M225.6,256.9c0,0-6.5,7,1,11"/>' ) ) ); } /// @dev Mouth N°4 => Poker function item_4() public pure returns (string memory) { return base( string( abi.encodePacked( '<line id="Poker" fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="180" y1="263" x2="226" y2="263"/>' ) ) ); } /// @dev Mouth N°5 => Angry function item_5() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M207.5,257.1c-7,1.4-17.3,0.3-21-0.9c-4-1.2-7.7,3.1-8.6,7.2c-0.5,2.5-1.2,7.4,3.4,10.1c5.9,2.4,5.6,0.1,9.2-1.9c3.4-2,10-1.1,15.3,1.9c5.4,3,13.4,2.2,17.9-0.4c2.9-1.7,3.3-7.6-4.2-14.1C217.3,257.2,215.5,255.5,207.5,257.1"/>', '<path fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M205.9,265.5l4.1-2.2c0,0,3.7,2.9,5,3s4.9-3.2,4.9-3.2l3.9,1.4"/>', '<polyline fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" points="177.8,265.3 180.2,263.4 183.3,265.5 186,265.4"/>' ) ) ); } /// @dev Mouth N°6 => Big Smile function item_6() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FFFFFF" stroke="#000000" stroke-miterlimit="10" d="M238.1,255.9c-26.1,4-68.5,0.3-68.5,0.3C170.7,256.3,199.6,296.4,238.1,255.9"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M176.4,262.7c0,0,7.1,2.2,12,2.1"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M230.6,262.8c0,0-10.4,2.1-17.7,1.8"/>' ) ) ); } /// @dev Mouth N°7 => Evil function item_7() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FFFFFF" stroke="#000000" stroke-miterlimit="10" d="M174.7,261.7c0,0,16.1-1.1,17.5-1.5s34.5,6.3,36.5,5.5s4.6-1.9,4.6-1.9s-14.1,8-43.6,7.9c0,0-3.9-0.7-4.7-1.8S177.1,262.1,174.7,261.7z"/>', '<polyline fill="none" stroke="#000000" stroke-miterlimit="10" points="181.6,266.7 185.5,265.3 189.1,266.5 190.3,265.9"/>', '<polyline fill="none" stroke="#000000" stroke-miterlimit="10" points="198.2,267 206.3,266.2 209.6,267.7 213.9,266.3 216.9,267.5 225.3,267"/>' ) ) ); } /// @dev Mouth N°8 => Tongue function item_8() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FF155D" d="M206.5,263.1c0,0,4,11.2,12.5,9.8c11.3-1.8,6.3-11.8,6.3-11.8L206.5,263.1z"/>', '<line fill="none" stroke="#73093E" stroke-miterlimit="10" x1="216.7" y1="262.5" x2="218.5" y2="267.3"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M201.9,263.4c0,0,20.7,0.1,27.7-4.3"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M178.2,259.6c0,0,9.9,4.2,19.8,3.9"/>' ) ) ); } /// @dev Mouth N°9 => Drool function item_9() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FEBCA6" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M190.4,257.5c2.5,0.6,5.1,0.8,7.7,0.5l17-2.1c0,0,13.3-1.8,12,3.6c-1.3,5.4-2.4,9.3-5.3,9.8c0,0,3.2,9.7-2.9,9c-3.7-0.4-2.4-7.7-2.4-7.7s-15.4,4.6-33.1-1.7c-1.8-0.6-3.6-2.6-4.4-3.9c-5.1-7.7-2-9.5-2-9.5S175.9,253.8,190.4,257.5z"/>' ) ) ); } /// @dev Mouth N°10 => O function item_10() public pure returns (string memory) { return base( string( abi.encodePacked( '<ellipse transform="matrix(0.9952 -9.745440e-02 9.745440e-02 0.9952 -24.6525 20.6528)" opacity="0.84" fill-rule="evenodd" clip-rule="evenodd" cx="199.1" cy="262.7" rx="3.2" ry="4.6"/>' ) ) ); } /// @dev Mouth N°11 => Dubu function item_11() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-miterlimit="10" d="M204.2,262c-8.9-7-25.1-3.5-4.6,6.6c-22-3.8-3.2,11.9,4.8,6"/>' ) ) ); } /// @dev Mouth N°12 => Stitch function item_12() public pure returns (string memory) { return base( string( abi.encodePacked( '<g opacity="0.84" fill-rule="evenodd" clip-rule="evenodd">', '<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.8992 6.2667)" cx="179.6" cy="264.5" rx="2.3" ry="4.3"/>', '<ellipse transform="matrix(0.9996 -2.866329e-02 2.866329e-02 0.9996 -7.485 5.0442)" cx="172.2" cy="263.6" rx="1.5" ry="2.9"/>', '<ellipse transform="matrix(0.9996 -2.866329e-02 2.866329e-02 0.9996 -7.4594 6.6264)" cx="227.4" cy="263.5" rx="1.5" ry="2.9"/>', '<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.8828 7.6318)" cx="219.7" cy="264.7" rx="2.5" ry="4.7"/>', '<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.9179 6.57)" cx="188.5" cy="265.2" rx="2.9" ry="5.4"/>', '<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.9153 7.3225)" cx="210.6" cy="265.5" rx="2.9" ry="5.4"/>', '<ellipse transform="matrix(0.9992 -3.983298e-02 3.983298e-02 0.9992 -10.4094 8.1532)" cx="199.4" cy="265.3" rx="4" ry="7.2"/>', "</g>" ) ) ); } /// @dev Mouth N°13 => Uwu function item_13() public pure returns (string memory) { return base( string( abi.encodePacked( '<polyline fill="#FFFFFF" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" points="212.7,262.9 216,266.5 217.5,261.7"/>', '<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M176.4,256c0,0,5.7,13.4,23.1,4.2"/>', '<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M224.7,254.8c0,0-9.5,15-25.2,5.4"/>' ) ) ); } /// @dev Mouth N°14 => Monster function item_14() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M161.4,255c0,0,0.5,0.1,1.3,0.3 c4.2,1,39.6,8.5,84.8-0.7C247.6,254.7,198.9,306.9,161.4,255z"/>', '<polyline fill="none" stroke="#000000" stroke-width="0.75" stroke-linejoin="round" stroke-miterlimit="10" points="165.1,258.9 167,256.3 170.3,264.6 175.4,257.7 179.2,271.9 187,259.1 190.8,276.5 197,259.7 202.1,277.5 207.8,259.1 213.8,275.4 217.9,258.7 224.1,271.2 226.5,257.9 232.7,266.2 235.1,256.8 238.6,262.1 241.3,255.8 243.8,257.6"/>' ) ) ); } /// @notice Return the mouth name of the given id /// @param id The mouth Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Neutral"; } else if (id == 2) { name = "Smile"; } else if (id == 3) { name = "Sulk"; } else if (id == 4) { name = "Poker"; } else if (id == 5) { name = "Angry"; } else if (id == 6) { name = "Big Smile"; } else if (id == 7) { name = "Evil"; } else if (id == 8) { name = "Tongue"; } else if (id == 9) { name = "Drool"; } else if (id == 10) { name = "O"; } else if (id == 11) { name = "Dubu"; } else if (id == 12) { name = "Stitch"; } else if (id == 13) { name = "Uwu"; } else if (id == 14) { name = "Monster"; } } /// @dev The base SVG for the mouth function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Mouth">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Nose SVG generator library NoseDetail { /// @dev Nose N°1 => Classic function item_1() public pure returns (string memory) { return ""; } /// @dev Nose N°2 => Bleeding function item_2() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#E90000" d="M205.8,254.1C205.8,254.1,205.9,254.1,205.8,254.1c0.1,0,0.1,0.1,0.1,0.1c0,0.2,0,0.5-0.2,0.7c-0.1,0.1-0.3,0.1-0.4,0.1c-0.4,0-0.8,0.1-1.2,0.1c-0.2,0-0.7,0.2-0.8,0s0.1-0.4,0.2-0.5c0.3-0.2,0.7-0.2,1-0.3C204.9,254.3,205.4,254.1,205.8,254.1z"/>', '<path fill="#E90000" d="M204.3,252.8c0.3-0.1,0.6-0.2,0.9-0.1c0.1,0.2,0.1,0.4,0.2,0.6c0,0.1,0,0.1,0,0.2c0,0.1-0.1,0.1-0.2,0.1c-0.7,0.2-1.4,0.3-2.1,0.5c-0.2,0-0.3,0.1-0.4-0.1c0-0.1-0.1-0.2,0-0.3c0.1-0.2,0.4-0.3,0.6-0.4C203.6,253.1,203.9,252.9,204.3,252.8z"/>', '<path fill="#FF0000" d="M204.7,240.2c0.3,1.1,0.1,2.3-0.1,3.5c-0.3,2-0.5,4.1,0,6.1c0.1,0.4,0.3,0.9,0.2,1.4c-0.2,0.9-1.1,1.3-2,1.6c-0.1,0-0.2,0.1-0.4,0.1c-0.3-0.1-0.4-0.5-0.4-0.8c-0.1-1.9,0.5-3.9,0.8-5.8c0.3-1.7,0.3-3.2-0.1-4.8c-0.1-0.5-0.3-0.9,0.1-1.3C203.4,239.7,204.6,239.4,204.7,240.2z"/>' ) ) ); } /// @notice Return the nose name of the given id /// @param id The nose Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Bleeding"; } } /// @dev The base SVG for the Nose function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Nose bonus">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; import "./constants/Colors.sol"; /// @title Eyes SVG generator library EyesDetail { /// @dev Eyes N°1 => Color White/Brown function item_1() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.BROWN); } /// @dev Eyes N°2 => Color White/Gray function item_2() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.GRAY); } /// @dev Eyes N°3 => Color White/Blue function item_3() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.BLUE); } /// @dev Eyes N°4 => Color White/Green function item_4() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.GREEN); } /// @dev Eyes N°5 => Color White/Black function item_5() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.BLACK_DEEP); } /// @dev Eyes N°6 => Color White/Yellow function item_6() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.YELLOW); } /// @dev Eyes N°7 => Color White/Red function item_7() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.RED); } /// @dev Eyes N°8 => Color White/Purple function item_8() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.PURPLE); } /// @dev Eyes N°9 => Color White/Pink function item_9() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.PINK); } /// @dev Eyes N°10 => Color White/White function item_10() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.WHITE); } /// @dev Eyes N°11 => Color Black/Blue function item_11() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.BLACK, Colors.BLUE); } /// @dev Eyes N°12 => Color Black/Yellow function item_12() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.BLACK, Colors.YELLOW); } /// @dev Eyes N°13 => Color Black/White function item_13() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.BLACK, Colors.WHITE); } /// @dev Eyes N°14 => Color Black/Red function item_14() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.BLACK, Colors.RED); } /// @dev Eyes N°15 => Blank White/White function item_15() public pure returns (string memory) { return eyesNoFillAndBlankPupils(Colors.WHITE, Colors.WHITE); } /// @dev Eyes N°16 => Blank Black/White function item_16() public pure returns (string memory) { return eyesNoFillAndBlankPupils(Colors.BLACK_DEEP, Colors.WHITE); } /// @dev Eyes N°17 => Shine (no-fill) function item_17() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path fill="#FFEE00" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M161.4,195.1c1.4,7.4,1.4,7.3,8.8,8.8 c-7.4,1.4-7.3,1.4-8.8,8.8c-1.4-7.4-1.4-7.3-8.8-8.8C160,202.4,159.9,202.5,161.4,195.1z"/>', '<path fill="#FFEE00" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M236.1,194.9c1.4,7.4,1.4,7.3,8.8,8.8 c-7.4,1.4-7.3,1.4-8.8,8.8c-1.4-7.4-1.4-7.3-8.8-8.8C234.8,202.3,234.7,202.3,236.1,194.9z"/>' ) ) ); } /// @dev Eyes N°18 => Stun (no-fill) function item_18() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path d="M233.6,205.2c0.2-0.8,0.6-1.7,1.3-2.3c0.4-0.3,0.9-0.5,1.3-0.4c0.5,0.1,0.9,0.4,1.2,0.8c0.5,0.8,0.6,1.8,0.6,2.7c0,0.9-0.4,1.9-1.1,2.6c-0.7,0.7-1.7,1.1-2.7,1c-1-0.1-1.8-0.7-2.5-1.2c-0.7-0.5-1.4-1.2-1.9-2c-0.5-0.8-0.8-1.8-0.7-2.8c0.1-1,0.5-1.9,1.1-2.6c0.6-0.7,1.4-1.3,2.2-1.7c1.7-0.8,3.6-1,5.3-0.6c0.9,0.2,1.8,0.5,2.5,1.1c0.7,0.6,1.2,1.5,1.3,2.4c0.3,1.8-0.3,3.7-1.4,4.9c1-1.4,1.4-3.2,1-4.8c-0.2-0.8-0.6-1.5-1.3-2c-0.6-0.5-1.4-0.8-2.2-0.9c-1.6-0.2-3.4,0-4.8,0.7c-1.4,0.7-2.7,2-2.8,3.5c-0.2,1.5,0.9,3,2.2,4c0.7,0.5,1.3,1,2.1,1.1c0.7,0.1,1.5-0.2,2.1-0.7c0.6-0.5,0.9-1.3,1-2.1c0.1-0.8,0-1.7-0.4-2.3c-0.2-0.3-0.5-0.6-0.8-0.7c-0.4-0.1-0.8,0-1.1,0.2C234.4,203.6,233.9,204.4,233.6,205.2z"/>', '<path d="M160.2,204.8c0.7-0.4,1.6-0.8,2.5-0.7c0.4,0,0.9,0.3,1.2,0.7c0.3,0.4,0.3,0.9,0.2,1.4c-0.2,0.9-0.8,1.7-1.5,2.3c-0.7,0.6-1.6,1.1-2.6,1c-1,0-2-0.4-2.6-1.2c-0.7-0.8-0.8-1.8-1-2.6c-0.1-0.9-0.1-1.8,0.1-2.8c0.2-0.9,0.7-1.8,1.5-2.4c0.8-0.6,1.7-1,2.7-1c0.9-0.1,1.9,0.1,2.7,0.4c1.7,0.6,3.2,1.8,4.2,3.3c0.5,0.7,0.9,1.6,1,2.6c0.1,0.9-0.2,1.9-0.8,2.6c-1.1,1.5-2.8,2.4-4.5,2.5c1.7-0.3,3.3-1.3,4.1-2.7c0.4-0.7,0.6-1.5,0.5-2.3c-0.1-0.8-0.5-1.5-1-2.2c-1-1.3-2.4-2.4-3.9-2.9c-1.5-0.5-3.3-0.5-4.5,0.5c-1.2,1-1.5,2.7-1.3,4.3c0.1,0.8,0.2,1.6,0.7,2.2c0.4,0.6,1.2,0.9,1.9,1c0.8,0,1.5-0.2,2.2-0.8c0.6-0.5,1.2-1.2,1.4-1.9c0.1-0.4,0.1-0.8-0.1-1.1c-0.2-0.3-0.5-0.6-0.9-0.6C161.9,204.2,161,204.4,160.2,204.8z"/>' ) ) ); } /// @dev Eyes N°19 => Squint (no-fill) function item_19() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path d="M167.3,203.7c0.1,7.7-12,7.7-11.9,0C155.3,196,167.4,196,167.3,203.7z"/>', '<path d="M244.8,205.6c-1.3,7.8-13.5,5.6-12-2.2C234.2,195.6,246.4,197.9,244.8,205.6z"/>' ) ) ); } /// @dev Eyes N°20 => Shock (no-fill) function item_20() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path fill-rule="evenodd" clip-rule="evenodd" d="M163.9,204c0,2.7-4.2,2.7-4.1,0C159.7,201.3,163.9,201.3,163.9,204z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" d="M236.7,204c0,2.7-4.2,2.7-4.1,0C232.5,201.3,236.7,201.3,236.7,204z"/>' ) ) ); } /// @dev Eyes N°21 => Cat (no-fill) function item_21() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path d="M238.4,204.2c0.1,13.1-4.5,13.1-4.5,0C233.8,191.2,238.4,191.2,238.4,204.2z"/>', '<path d="M164.8,204.2c0.1,13-4.5,13-4.5,0C160.2,191.2,164.8,191.2,164.8,204.2z"/>' ) ) ); } /// @dev Eyes N°22 => Ether (no-fill) function item_22() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path d="M161.7,206.4l-4.6-2.2l4.6,8l4.6-8L161.7,206.4z"/>', '<path d="M165.8,202.6l-4.1-7.1l-4.1,7.1l4.1-1.9L165.8,202.6z"/>', '<path d="M157.9,203.5l3.7,1.8l3.8-1.8l-3.8-1.8L157.9,203.5z"/>', '<path d="M236.1,206.6l-4.6-2.2l4.6,8l4.6-8L236.1,206.6z"/>', '<path d="M240.2,202.8l-4.1-7.1l-4.1,7.1l4.1-1.9L240.2,202.8z"/>', '<path d="M232.4,203.7l3.7,1.8l3.8-1.8l-3.8-1.8L232.4,203.7z"/>' ) ) ); } /// @dev Eyes N°23 => Feels function item_23() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M251.1,201.4c0.7,0.6,1,2.2,1,2.7c-0.1-0.4-1.4-1.1-2.2-1.7c-0.2,0.1-0.4,0.4-0.6,0.5c0.5,0.7,0.7,2,0.7,2.5c-0.1-0.4-1.3-1.1-2.1-1.6c-2.7,1.7-6.4,3.2-11.5,3.7c-8.1,0.7-16.3-1.7-20.9-6.4c5.9,3.1,13.4,4.5,20.9,3.8c6.6-0.6,12.7-2.9,17-6.3C253.4,198.9,252.6,200.1,251.1,201.4z"/>', '<path d="M250,205.6L250,205.6C250.1,205.9,250.1,205.8,250,205.6z"/>', '<path d="M252.1,204.2L252.1,204.2C252.2,204.5,252.2,204.4,252.1,204.2z"/>', '<path d="M162.9,207.9c-4.1-0.4-8-1.4-11.2-2.9c-0.7,0.3-3.1,1.4-3.3,1.9c0.1-0.6,0.3-2.2,1.3-2.8c0.1-0.1,0.2-0.1,0.3-0.1c-0.2-0.1-0.5-0.3-0.7-0.4c-0.8,0.4-3,1.3-3.2,1.9c0.1-0.6,0.3-2.2,1.3-2.8c0.1-0.1,0.3-0.1,0.5-0.1c-0.9-0.7-1.7-1.6-2.4-2.4c1.5,1.1,6.9,4.2,17.4,5.3c11.9,1.2,18.3-4,19.8-4.7C177.7,205.3,171.4,208.8,162.9,207.9z"/>', '<path d="M148.5,207L148.5,207C148.5,207.1,148.5,207.2,148.5,207z"/>', '<path d="M146.2,205.6L146.2,205.6C146.2,205.7,146.2,205.7,146.2,205.6z"/>' ) ) ); } /// @dev Eyes N°24 => Happy function item_24() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M251.5,203.5c0.7-0.7,0.9-2.5,0.9-3.2c-0.1,0.5-1.3,1.4-2.2,1.9c-0.2-0.2-0.4-0.4-0.6-0.6c0.5-0.8,0.7-2.4,0.7-3 c-0.1,0.5-1.2,1.4-2.1,1.9c-2.6-1.9-6.2-3.8-11-4.3c-7.8-0.8-15.7,2-20.1,7.5c5.7-3.6,12.9-5.3,20.1-4.5 c6.4,0.8,12.4,2.9,16.5,6.9C253.3,205.1,252.3,204,251.5,203.5z"/>', '<path d="M250.3,198.6L250.3,198.6C250.4,198.2,250.4,198.3,250.3,198.6z"/>', '<path d="M252.4,200.3L252.4,200.3C252.5,199.9,252.5,200,252.4,200.3z"/>', '<path d="M228.2,192.6c1.1-0.3,2.3-0.5,3.5-0.6c1.1-0.1,2.4-0.1,3.5,0s2.4,0.3,3.5,0.5s2.3,0.6,3.3,1.1l0,0 c-1.1-0.3-2.3-0.6-3.4-0.8c-1.1-0.3-2.3-0.4-3.4-0.5c-1.1-0.1-2.4-0.2-3.5-0.1C230.5,192.3,229.4,192.4,228.2,192.6L228.2,192.6z"/>', '<path d="M224.5,193.8c-0.9,0.6-2,1.1-3,1.7c-0.9,0.6-2,1.2-3,1.7c0.4-0.4,0.8-0.8,1.2-1.1s0.9-0.7,1.4-0.9c0.5-0.3,1-0.6,1.5-0.8C223.3,194.2,223.9,193.9,224.5,193.8z"/>', '<path d="M161.3,195.8c-3.7,0.4-7.2,1.6-10.1,3.5c-0.6-0.3-2.8-1.6-3-2.3c0.1,0.7,0.3,2.6,1.1,3.3c0.1,0.1,0.2,0.2,0.3,0.2 c-0.2,0.2-0.4,0.3-0.6,0.5c-0.7-0.4-2.7-1.5-2.9-2.2c0.1,0.7,0.3,2.6,1.1,3.3c0.1,0.1,0.3,0.2,0.4,0.2c-0.8,0.8-1.6,1.9-2.2,2.9 c1.3-1.4,6.3-5,15.8-6.3c10.9-1.4,16.7,4.7,18,5.5C174.8,198.9,169.1,194.8,161.3,195.8z"/>', '<path d="M148.2,196.9L148.2,196.9C148.2,196.8,148.2,196.7,148.2,196.9z"/>', '<path d="M146.1,198.6L146.1,198.6C146.1,198.5,146.1,198.4,146.1,198.6z"/>', '<path d="M167.5,192.2c-1.1-0.2-2.3-0.3-3.5-0.3c-1.1,0-2.4,0-3.5,0.2c-1.1,0.1-2.3,0.3-3.4,0.5c-1.1,0.3-2.3,0.5-3.4,0.8 c2.1-0.9,4.3-1.5,6.7-1.7c1.1-0.1,2.4-0.1,3.5-0.1C165.3,191.7,166.4,191.9,167.5,192.2z"/>', '<path d="M171.4,193.4c0.6,0.2,1.1,0.3,1.7,0.6c0.5,0.3,1,0.5,1.6,0.8c0.5,0.3,1,0.6,1.4,0.9c0.5,0.3,0.9,0.7,1.3,1 c-1-0.5-2.1-1.1-3-1.6C173.3,194.5,172.3,193.9,171.4,193.4z"/>' ) ) ); } /// @dev Eyes N°25 => Arrow function item_25() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-width="1.5" stroke-linejoin="round" stroke-miterlimit="10" d="M251.4,192.5l-30.8,8 c10.9,1.9,20.7,5,29.5,9.1"/>', '<path fill="none" stroke="#000000" stroke-width="1.5" stroke-linejoin="round" stroke-miterlimit="10" d="M149.4,192.5l30.8,8 c-10.9,1.9-20.7,5-29.5,9.1"/>' ) ) ); } /// @dev Eyes N°26 => Closed function item_26() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" x1="216.3" y1="200.2" x2="259" y2="198.3"/>', '<line fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" x1="179.4" y1="200.2" x2="143.4" y2="198.3"/>' ) ) ); } /// @dev Eyes N°27 => Suspicious function item_27() public pure returns (string memory) { return base( string( abi.encodePacked( '<path opacity="0.81" fill="#FFFFFF" d="M220.3,202.5c-0.6,4.6,0.1,5.8,1.6,8.3 c0.9,1.5,1,2.5,8.2-1.2c6.1,0.4,8.2-1.6,16,2.5c3,0,4-3.8,5.1-7.7c0.6-2.2-0.2-4.6-2-5.9c-3.4-2.5-9-6-13.4-5.3 c-3.9,0.7-7.7,1.9-11.3,3.6C222.3,197.9,221,197.3,220.3,202.5z"/>', '<path d="M251.6,200c0.7-0.8,0.9-2.9,0.9-3.7c-0.1,0.6-1.3,1.5-2,2.2c-0.2-0.2-0.4-0.5-0.6-0.7c0.5-1,0.7-2.7,0.7-3.4 c-0.1,0.6-1.2,1.5-1.9,2.1c-2.4-2.2-5.8-4.4-10.4-4.9c-7.4-1-14.7,2.3-18.9,8.6c5.3-4.2,12.1-6,18.9-5.1c6,0.9,11.5,4,15.4,8.5 C253.6,203.4,252.9,201.9,251.6,200z"/>', '<path d="M250.5,194.4L250.5,194.4C250.6,194,250.6,194.1,250.5,194.4z"/>', '<path d="M252.4,196.3L252.4,196.3C252.5,195.9,252.5,196,252.4,196.3z"/>', '<path d="M229.6,187.6c1.1-0.3,2.1-0.6,3.3-0.7c1.1-0.1,2.2-0.1,3.3,0s2.2,0.3,3.3,0.6s2.1,0.7,3.1,1.3l0,0 c-1.1-0.3-2.1-0.7-3.2-0.9c-1.1-0.3-2.1-0.5-3.2-0.6c-1.1-0.1-2.2-0.2-3.3-0.1C231.9,187.2,230.8,187.3,229.6,187.6L229.6,187.6 z"/>', '<path d="M226.1,189c-0.9,0.7-1.8,1.3-2.8,1.9c-0.9,0.7-1.8,1.4-2.8,1.9c0.4-0.5,0.8-0.9,1.2-1.3c0.4-0.4,0.9-0.8,1.4-1.1 s1-0.7,1.5-0.9C225.1,189.4,225.7,189.1,226.1,189z"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M222,212.8c0,0,9.8-7.3,26.9,0"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M229,195.2c0,0-4.6,8.5,0.7,14.4 c0,0,8.8-1.5,11.6,0.4c0,0,4.7-5.7,1.5-12.5S229,195.2,229,195.2z"/>', '<path opacity="0.81" fill="#FFFFFF" d="M177.1,202.5c0.6,4.6-0.1,5.8-1.6,8.3 c-0.9,1.5-1,2.5-8.2-1.2c-6.1,0.4-8.2-1.6-16,2.5c-3,0-4-3.8-5.1-7.7c-0.6-2.2,0.2-4.6,2-5.9c3.4-2.5,9-6,13.4-5.3 c3.9,0.7,7.7,1.9,11.3,3.6C175.2,197.9,176.4,197.3,177.1,202.5z"/>', '<path d="M145.9,200c-0.7-0.8-0.9-2.9-0.9-3.7c0.1,0.6,1.3,1.5,2,2.2c0.2-0.2,0.4-0.5,0.6-0.7c-0.5-1-0.7-2.7-0.7-3.4 c0.1,0.6,1.2,1.5,1.9,2.1c2.4-2.2,5.8-4.4,10.4-4.9c7.4-1,14.7,2.3,18.9,8.6c-5.3-4.2-12.1-6-18.9-5.1c-6,0.9-11.5,4-15.4,8.5 C143.8,203.4,144.5,201.9,145.9,200z"/>', '<path d="M146.9,194.4L146.9,194.4C146.9,194,146.9,194.1,146.9,194.4z"/>', abi.encodePacked( '<path d="M145,196.3L145,196.3C144.9,195.9,144.9,196,145,196.3z"/>', '<path d="M167.8,187.6c-1.1-0.3-2.1-0.6-3.3-0.7c-1.1-0.1-2.2-0.1-3.3,0s-2.2,0.3-3.3,0.6s-2.1,0.7-3.1,1.3l0,0 c1.1-0.3,2.1-0.7,3.2-0.9c1.1-0.3,2.1-0.5,3.2-0.6c1.1-0.1,2.2-0.2,3.3-0.1C165.6,187.2,166.6,187.3,167.8,187.6L167.8,187.6z"/>', '<path d="M171.3,189c0.9,0.7,1.8,1.3,2.8,1.9c0.9,0.7,1.8,1.4,2.8,1.9c-0.4-0.5-0.8-0.9-1.2-1.3c-0.4-0.4-0.9-0.8-1.4-1.1 s-1-0.7-1.5-0.9C172.4,189.4,171.8,189.1,171.3,189z"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M175.4,212.8c0,0-9.8-7.3-26.9,0"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M168.5,195.2c0,0,4.6,8.5-0.7,14.4 c0,0-8.8-1.5-11.6,0.4c0,0-4.7-5.7-1.5-12.5S168.5,195.2,168.5,195.2z"/>' ) ) ) ); } /// @dev Eyes N°28 => Annoyed 1 function item_28() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="218" y1="195.2" x2="256" y2="195.2"/>', '<path stroke="#000000" stroke-miterlimit="10" d="M234,195.5c0,5.1,4.1,9.2,9.2,9.2s9.2-4.1,9.2-9.2"/>', '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="143.2" y1="195.7" x2="181.1" y2="195.7"/>', '<path stroke="#000000" stroke-miterlimit="10" d="M158.7,196c0,5.1,4.1,9.2,9.2,9.2c5.1,0,9.2-4.1,9.2-9.2"/>' ) ) ); } /// @dev Eyes N°29 => Annoyed 2 function item_29() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="218" y1="195.2" x2="256" y2="195.2"/>', '<path stroke="#000000" stroke-miterlimit="10" d="M228,195.5c0,5.1,4.1,9.2,9.2,9.2s9.2-4.1,9.2-9.2"/>', '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="143.2" y1="195.7" x2="181.1" y2="195.7"/>', '<path stroke="#000000" stroke-miterlimit="10" d="M152.7,196c0,5.1,4.1,9.2,9.2,9.2c5.1,0,9.2-4.1,9.2-9.2"/>' ) ) ); } /// @dev Eyes N°30 => RIP function item_30() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="225.7" y1="190.8" x2="242.7" y2="207.8"/>', '<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="225.7" y1="207.8" x2="243.1" y2="190.8"/>', '<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="152.8" y1="190.8" x2="169.8" y2="207.8"/>', '<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="152.8" y1="207.8" x2="170.3" y2="190.8"/>' ) ) ); } /// @dev Eyes N°31 => Heart function item_31() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#F44336" stroke="#C90005" stroke-miterlimit="10" d="M161.1,218.1c0.2,0.2,0.4,0.3,0.7,0.3s0.5-0.1,0.7-0.3l12.8-14.1 c5.3-5.9,1.5-16-6-16c-4.6,0-6.7,3.6-7.5,4.3c-0.8-0.7-2.9-4.3-7.5-4.3c-7.6,0-11.4,10.1-6,16L161.1,218.1z"/>', '<path fill="#F44336" stroke="#C90005" stroke-miterlimit="10" d="M235.3,218.1c0.2,0.2,0.5,0.3,0.8,0.3s0.6-0.1,0.8-0.3l13.9-14.1 c5.8-5.9,1.7-16-6.6-16c-4.9,0-7.2,3.6-8.1,4.3c-0.9-0.7-3.1-4.3-8.1-4.3c-8.2,0-12.4,10.1-6.6,16L235.3,218.1z"/>' ) ) ); } /// @dev Eyes N°32 => Scribble function item_32() public pure returns (string memory) { return base( string( abi.encodePacked( '<polyline fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" points="222.5,195.2 252.2,195.2 222.5,199.4 250.5,199.4 223.9,202.8 247.4,202.8"/>', '<polyline fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" points="148.2,195.2 177.9,195.2 148.2,199.4 176.2,199.4 149.6,202.8 173.1,202.8"/>' ) ) ); } /// @dev Eyes N°33 => Wide function item_33() public pure returns (string memory) { return base( string( abi.encodePacked( '<ellipse fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" cx="236.7" cy="200.1" rx="12.6" ry="14.9"/>', '<path d="M249.4,200.1c0,3.6-1,7.3-3.2,10.3c-1.1,1.5-2.5,2.8-4.1,3.7s-3.5,1.4-5.4,1.4s-3.7-0.6-5.3-1.5s-3-2.2-4.1-3.6c-2.2-2.9-3.4-6.5-3.5-10.2c-0.1-3.6,1-7.4,3.3-10.4c1.1-1.5,2.6-2.7,4.2-3.6c1.6-0.9,3.5-1.4,5.4-1.4s3.8,0.5,5.4,1.4c1.6,0.9,3,2.2,4.1,3.7C248.4,192.9,249.4,196.5,249.4,200.1z M249.3,200.1c0-1.8-0.3-3.6-0.9-5.3c-0.6-1.7-1.5-3.2-2.6-4.6c-2.2-2.7-5.5-4.5-9-4.5s-6.7,1.8-8.9,4.6c-2.2,2.7-3.3,6.2-3.4,9.8c-0.1,3.5,1,7.2,3.2,10s5.6,4.6,9.1,4.5c3.5,0,6.8-1.9,9-4.6C248,207.3,249.3,203.7,249.3,200.1z"/>', '<ellipse fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" cx="163" cy="200.1" rx="12.6" ry="14.9"/>', '<path d="M175.6,200.1c0,3.6-1,7.3-3.2,10.3c-1.1,1.5-2.5,2.8-4.1,3.7s-3.5,1.4-5.4,1.4s-3.7-0.6-5.3-1.5s-3-2.2-4.1-3.6c-2.2-2.9-3.4-6.5-3.5-10.2c-0.1-3.6,1-7.4,3.3-10.4c1.1-1.5,2.6-2.7,4.2-3.6c1.6-0.9,3.5-1.4,5.4-1.4s3.8,0.5,5.4,1.4c1.6,0.9,3,2.2,4.1,3.7C174.6,192.9,175.6,196.5,175.6,200.1z M175.5,200.1c0-1.8-0.3-3.6-0.9-5.3c-0.6-1.7-1.5-3.2-2.6-4.6c-2.2-2.7-5.5-4.5-9-4.5s-6.7,1.8-8.9,4.6c-2.2,2.7-3.3,6.2-3.4,9.8c-0.1,3.5,1,7.2,3.2,10s5.6,4.6,9.1,4.5c3.5,0,6.8-1.9,9-4.6C174.3,207.3,175.5,203.7,175.5,200.1z"/>' ) ) ); } /// @dev Eyes N°34 => Dubu function item_34() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M241.6,195.9c-8.7-7.2-25.1-4-4.7,6.6c-21.9-4.3-3.4,11.8,4.7,6.1"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M167.6,195.9c-8.7-7.2-25.1-4-4.7,6.6c-21.9-4.3-3.4,11.8,4.7,6.1"/>' ) ) ); } /// @dev Right and left eyes (color pupils + eyes) function eyesNoFillAndColorPupils(string memory scleraColor, string memory pupilsColor) private pure returns (string memory) { return base(string(abi.encodePacked(eyesNoFill(scleraColor), colorPupils(pupilsColor)))); } /// @dev Right and left eyes (blank pupils + eyes) function eyesNoFillAndBlankPupils(string memory scleraColor, string memory pupilsColor) private pure returns (string memory) { return base(string(abi.encodePacked(eyesNoFill(scleraColor), blankPupils(pupilsColor)))); } /// @dev Right and left eyes function eyesNoFill(string memory scleraColor) private pure returns (string memory) { return string(abi.encodePacked(eyeLeftNoFill(scleraColor), eyeRightNoFill(scleraColor))); } /// @dev Eye right and no fill function eyeRightNoFill(string memory scleraColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", scleraColor, "' d='M220.9,203.6c0.5,3.1,1.7,9.6,7.1,10.1 c7,1.1,21,4.3,23.2-9.3c1.3-7.1-9.8-11.4-15.4-11.2C230.7,194.7,220.5,194.7,220.9,203.6z'/>", '<path d="M250.4,198.6c-0.2-0.2-0.4-0.5-0.6-0.7"/>', '<path d="M248.6,196.6c-7.6-7.9-23.4-6.2-29.3,3.7c10-8.2,26.2-6.7,34.4,3.4c0-0.3-0.7-1.8-2-3.7"/>', '<path d="M229.6,187.6c4.2-1.3,9.1-1,13,1.2C238.4,187.4,234,186.6,229.6,187.6L229.6,187.6z"/>', '<path d="M226.1,189c-1.8,1.3-3.7,2.7-5.6,3.9C221.9,191.1,224,189.6,226.1,189z"/>', '<path d="M224.5,212.4c5.2,2.5,19.7,3.5,24-0.9C244.2,216.8,229.6,215.8,224.5,212.4z"/>' ) ); } /// @dev Eye right and no fill function eyeLeftNoFill(string memory scleraColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", scleraColor, "' d='M175.7,199.4c2.4,7.1-0.6,13.3-4.1,13.9 c-5,0.8-15.8,1-18.8,0c-5-1.7-6.1-12.4-6.1-12.4C156.6,191.4,165,189.5,175.7,199.4z'/>", '<path d="M147.5,198.7c-0.8,1-1.5,2.1-2,3.3c7.5-8.5,24.7-10.3,31.7-0.9c-5.8-10.3-17.5-13-26.4-5.8"/>', '<path d="M149.4,196.6c-0.2,0.2-0.4,0.4-0.6,0.6"/>', '<path d="M166.2,187.1c-4.3-0.8-8.8,0.1-13,1.4C157,186.4,162,185.8,166.2,187.1z"/>', '<path d="M169.8,188.5c2.2,0.8,4.1,2.2,5.6,3.8C173.5,191.1,171.6,189.7,169.8,188.5z"/>', '<path d="M174.4,211.8c-0.2,0.5-0.8,0.8-1.2,1c-0.5,0.2-1,0.4-1.5,0.6c-1,0.3-2.1,0.5-3.1,0.7c-2.1,0.4-4.2,0.5-6.3,0.7 c-2.1,0.1-4.3,0.1-6.4-0.3c-1.1-0.2-2.1-0.5-3.1-0.9c-0.9-0.5-2-1.1-2.4-2.1c0.6,0.9,1.6,1.4,2.5,1.7c1,0.3,2,0.6,3,0.7 c2.1,0.3,4.2,0.3,6.2,0.2c2.1-0.1,4.2-0.2,6.3-0.5c1-0.1,2.1-0.3,3.1-0.5c0.5-0.1,1-0.2,1.5-0.4c0.2-0.1,0.5-0.2,0.7-0.3 C174.1,212.2,174.3,212.1,174.4,211.8z"/>' ) ); } /// @dev Generate color pupils function colorPupils(string memory pupilsColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", pupilsColor, "' d='M235,194.9c10.6-0.2,10.6,19,0,18.8C224.4,213.9,224.4,194.7,235,194.9z'/>", '<path d="M235,199.5c3.9-0.1,3.9,9.6,0,9.5C231.1,209.1,231.1,199.4,235,199.5z"/>', '<path fill="#FFFFFF" d="M239.1,200.9c3.4,0,3.4,2.5,0,2.5C235.7,203.4,235.7,200.8,239.1,200.9z"/>', "<path fill='#", pupilsColor, "' d='M161.9,194.6c10.5-0.4,11,18.9,0.4,18.9C151.7,213.9,151.3,194.6,161.9,194.6z'/>", '<path d="M162,199.2c3.9-0.2,4.1,9.5,0.2,9.5C158.2,208.9,158.1,199.2,162,199.2z"/>', '<path fill="#FFFFFF" d="M157.9,200.7c3.4-0.1,3.4,2.5,0,2.5C154.6,203.3,154.5,200.7,157.9,200.7z"/>' ) ); } /// @dev Generate blank pupils function blankPupils(string memory pupilsColor) private pure returns (string memory) { return string( abi.encodePacked( abi.encodePacked( "<path fill='#", pupilsColor, "' stroke='#000000' stroke-width='0.25' stroke-miterlimit='10' d='M169.2,204.2c0.1,11.3-14.1,11.3-13.9,0C155.1,192.9,169.3,192.9,169.2,204.2z'/>", "<path fill='#", pupilsColor, "' stroke='#000000' stroke-width='0.25' stroke-miterlimit='10' d='M243.1,204.3c0.1,11.3-14.1,11.3-13.9,0C229,193,243.2,193,243.1,204.3z'/>" ) ) ); } /// @notice Return the eyes name of the given id /// @param id The eyes Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Color White/Brown"; } else if (id == 2) { name = "Color White/Gray"; } else if (id == 3) { name = "Color White/Blue"; } else if (id == 4) { name = "Color White/Green"; } else if (id == 5) { name = "Color White/Black"; } else if (id == 6) { name = "Color White/Yellow"; } else if (id == 7) { name = "Color White/Red"; } else if (id == 8) { name = "Color White/Purple"; } else if (id == 9) { name = "Color White/Pink"; } else if (id == 10) { name = "Color White/White"; } else if (id == 11) { name = "Color Black/Blue"; } else if (id == 12) { name = "Color Black/Yellow"; } else if (id == 13) { name = "Color Black/White"; } else if (id == 14) { name = "Color Black/Red"; } else if (id == 15) { name = "Blank White/White"; } else if (id == 16) { name = "Blank Black/White"; } else if (id == 17) { name = "Shine"; } else if (id == 18) { name = "Stunt"; } else if (id == 19) { name = "Squint"; } else if (id == 20) { name = "Shock"; } else if (id == 21) { name = "Cat"; } else if (id == 22) { name = "Ether"; } else if (id == 23) { name = "Feels"; } else if (id == 24) { name = "Happy"; } else if (id == 25) { name = "Arrow"; } else if (id == 26) { name = "Closed"; } else if (id == 27) { name = "Suspicious"; } else if (id == 28) { name = "Annoyed 1"; } else if (id == 29) { name = "Annoyed 2"; } else if (id == 30) { name = "RIP"; } else if (id == 31) { name = "Heart"; } else if (id == 32) { name = "Scribble"; } else if (id == 33) { name = "Wide"; } else if (id == 34) { name = "Dubu"; } } /// @dev The base SVG for the eyes function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Eyes">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Eyebrow SVG generator library EyebrowDetail { /// @dev Eyebrow N°1 => Classic function item_1() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#150000" d="M213.9,183.1c13.9-5.6,28.6-3,42.7-0.2C244,175,225.8,172.6,213.9,183.1z"/>', '<path fill="#150000" d="M179.8,183.1c-10.7-10.5-27-8.5-38.3-0.5C154.1,179.7,167.6,177.5,179.8,183.1z"/>' ) ) ); } /// @dev Eyebrow N°2 => Thick function item_2() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M211.3,177.6c0,0,28.6-6.6,36.2-6.2c7.7,0.4,13,3,16.7,6.4c0,0-26.9,5.3-38.9,5.9C213.3,184.3,212.9,183.8,211.3,177.6z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M188.2,177.6c0,0-27.9-6.7-35.4-6.3c-7.5,0.4-12.7,2.9-16.2,6.3c0,0,26.3,5.3,38,6C186.2,184.3,186.7,183.7,188.2,177.6z"/>' ) ) ); } /// @dev Eyebrow N°3 => Punk function item_3() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M258.6,179.1l-2-2.3 c3.1,0.4,5.6,1,7.6,1.7C264.2,178.6,262,178.8,258.6,179.1z M249.7,176.3c-0.7,0-1.5,0-2.3,0c-7.6,0-36.1,3.2-36.1,3.2 c-0.4,2.9-3.8,3.5,8.1,3c6.6-0.3,23.6-2,32.3-2.8L249.7,176.3z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M140.2,179.1l1.9-2.3 c-3,0.4-5.4,1-7.3,1.7C134.8,178.6,136.9,178.8,140.2,179.1z M148.8,176.3c0.7,0,1.4,0,2.2,0c7.3,0,34.7,3.2,34.7,3.2 c0.4,2.9,3.6,3.5-7.8,3c-6.3-0.3-22.7-2-31-2.8L148.8,176.3z"/>' ) ) ); } /// @dev Eyebrow N°4 => Small function item_4() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" d="M236.3,177c-11.3-5.1-18-3.1-20.3-2.1c-0.1,0-0.2,0.1-0.3,0.2c-0.3,0.1-0.5,0.3-0.6,0.3l0,0l0,0l0,0c-1,0.7-1.7,1.7-1.9,3c-0.5,2.6,1.2,5,3.8,5.5s5-1.2,5.5-3.8c0.1-0.3,0.1-0.6,0.1-1C227.4,175.6,236.3,177,236.3,177z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" d="M160.2,176.3c10.8-4.6,17.1-2.5,19.2-1.3c0.1,0,0.2,0.1,0.3,0.2c0.3,0.1,0.4,0.3,0.5,0.3l0,0l0,0l0,0c0.9,0.7,1.6,1.8,1.8,3.1c0.4,2.6-1.2,5-3.7,5.4s-4.7-1.4-5.1-4c-0.1-0.3-0.1-0.6-0.1-1C168.6,175.2,160.2,176.3,160.2,176.3z"/>' ) ) ); } /// @dev Eyebrow N°5 => Shaved function item_5() public pure returns (string memory) { return base( string( abi.encodePacked( '<g opacity="0.06">', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M214.5,178 c0,0,20.6-3.5,26.1-3.3s9.4,1.6,12,3.4c0,0-19.4,2.8-28,3.1C215.9,181.6,215.6,181.3,214.5,178z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M180.8,178 c0,0-20.1-3.6-25.5-3.4c-5.4,0.2-9.1,1.5-11.7,3.4c0,0,18.9,2.8,27.4,3.2C179.4,181.6,179.8,181.3,180.8,178z"/>', "</g>" ) ) ); } /// @dev Eyebrow N°6 => Elektric function item_6() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" d="M208.9,177.6c14.6-1.5,47.8-6.5,51.6-6.6l-14.4,4.1l19.7,3.2 c-20.2-0.4-40.9-0.1-59.2,2.6C206.6,179.9,207.6,178.5,208.9,177.6z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" d="M185.1,177.7c-13.3-1.5-43.3-6.7-46.7-6.9l13.1,4.2l-17.8,3.1 c18.2-0.3,37,0.1,53.6,2.9C187.2,180,186.2,178.6,185.1,177.7z"/>' ) ) ); } /// @notice Return the eyebrow name of the given id /// @param id The eyebrow Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Thick"; } else if (id == 3) { name = "Punk"; } else if (id == 4) { name = "Small"; } else if (id == 5) { name = "Shaved"; } else if (id == 6) { name = "Elektric"; } } /// @dev The base SVG for the Eyebrow function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Eyebrow">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Mark SVG generator library MarkDetail { /// @dev Mark N°1 => Classic function item_1() public pure returns (string memory) { return ""; } /// @dev Mark N°2 => Blush Cheeks function item_2() public pure returns (string memory) { return base( string( abi.encodePacked( '<g opacity="0.71">', '<ellipse fill="#FF7478" cx="257.6" cy="221.2" rx="11.6" ry="3.6"/>', '<ellipse fill="#FF7478" cx="146.9" cy="221.5" rx="9.6" ry="3.6"/>', "</g>" ) ) ); } /// @dev Mark N°3 => Dark Circle function item_3() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M160.1,223.2c4.4,0.2,8.7-1.3,12.7-3.2C169.3,222.7,164.4,223.9,160.1,223.2z"/>', '<path d="M156.4,222.4c-2.2-0.4-4.3-1.6-6.1-3C152.3,220.3,154.4,221.4,156.4,222.4z"/>', '<path d="M234.5,222.7c4.9,0.1,9.7-1.4,14.1-3.4C244.7,222.1,239.3,223.4,234.5,222.7z"/>', '<path d="M230.3,221.9c-2.5-0.4-4.8-1.5-6.7-2.9C225.9,219.9,228.2,221,230.3,221.9z"/>' ) ) ); } /// @dev Mark N°4 => Chin scar function item_4() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#E83342" d="M195.5,285.7l17,8.9C212.5,294.6,206.1,288.4,195.5,285.7z"/>', '<path fill="#E83342" d="M211.2,285.7l-17,8.9C194.1,294.6,200.6,288.4,211.2,285.7z"/>' ) ) ); } /// @dev Mark N°5 => Blush function item_5() public pure returns (string memory) { return base( string( abi.encodePacked( '<ellipse opacity="0.52" fill-rule="evenodd" clip-rule="evenodd" fill="#FF7F83" cx="196.8" cy="222" rx="32.8" ry="1.9"/>' ) ) ); } /// @dev Mark N°6 => Chin function item_6() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M201.3,291.9c0.2-0.6,0.4-1.3,1-1.8c0.3-0.2,0.7-0.4,1.1-0.3c0.4,0.1,0.7,0.4,0.9,0.7c0.4,0.6,0.5,1.4,0.5,2.1 c0,0.7-0.3,1.5-0.8,2c-0.5,0.6-1.3,0.9-2.1,0.8c-0.8-0.1-1.5-0.5-2-0.9c-0.6-0.4-1.1-1-1.5-1.6c-0.4-0.6-0.6-1.4-0.6-2.2 c0.2-1.6,1.4-2.8,2.7-3.4c1.3-0.6,2.8-0.8,4.2-0.5c0.7,0.1,1.4,0.4,2,0.9c0.6,0.5,0.9,1.2,1,1.9c0.2,1.4-0.2,2.9-1.2,3.9 c0.7-1.1,1-2.5,0.7-3.8c-0.2-0.6-0.5-1.2-1-1.5c-0.5-0.4-1.1-0.6-1.7-0.6c-1.3-0.1-2.6,0-3.7,0.6c-1.1,0.5-2,1.5-2.1,2.6 c-0.1,1.1,0.7,2.2,1.6,3c0.5,0.4,1,0.8,1.5,0.8c0.5,0.1,1.1-0.1,1.5-0.5c0.4-0.4,0.7-0.9,0.7-1.6c0.1-0.6,0-1.3-0.3-1.8 c-0.1-0.3-0.4-0.5-0.6-0.6c-0.3-0.1-0.6,0-0.8,0.1C201.9,290.7,201.5,291.3,201.3,291.9z"/>' ) ) ); } /// @dev Mark N°7 => Yinyang function item_7() public pure returns (string memory) { return base( string( abi.encodePacked( '<path opacity="0.86" d="M211.5,161.1c0-8.2-6.7-14.9-14.9-14.9c-0.2,0-0.3,0-0.5,0l0,0 H196c-0.1,0-0.2,0-0.2,0c-0.2,0-0.4,0-0.5,0c-7.5,0.7-13.5,7.1-13.5,14.8c0,8.2,6.7,14.9,14.9,14.9 C204.8,176,211.5,169.3,211.5,161.1z M198.4,154.2c0,1-0.8,1.9-1.9,1.9c-1,0-1.9-0.8-1.9-1.9c0-1,0.8-1.9,1.9-1.9 C197.6,152.3,198.4,153.1,198.4,154.2z M202.9,168.2c0,3.6-3.1,6.6-6.9,6.6l0,0c-7.3-0.3-13.2-6.3-13.2-13.7c0-6,3.9-11.2,9.3-13 c-2,1.3-3.4,3.6-3.4,6.2c0,4,3.3,7.3,7.3,7.3l0,0C199.8,161.6,202.9,164.5,202.9,168.2z M196.6,170.3c-1,0-1.9-0.8-1.9-1.9 c0-1,0.8-1.9,1.9-1.9c1,0,1.9,0.8,1.9,1.9C198.4,169.5,197.6,170.3,196.6,170.3z"/>' ) ) ); } /// @dev Mark N°8 => Scar function item_8() public pure returns (string memory) { return base( string( abi.encodePacked( '<path id="Scar" fill="#FF7478" d="M236.2,148.7c0,0-7.9,48.9-1.2,97.3C235,246,243.8,201.5,236.2,148.7z"/>' ) ) ); } /// @dev Mark N°9 => Sun function item_9() public pure returns (string memory) { return base( string( abi.encodePacked( '<circle fill="#7F0068" cx="195.8" cy="161.5" r="11.5"/>', '<polygon fill="#7F0068" points="195.9,142.4 192.4,147.8 199.3,147.8"/>', '<polygon fill="#7F0068" points="209.6,158.1 209.6,164.9 214.9,161.5"/>', '<polygon fill="#7F0068" points="195.9,180.6 199.3,175.2 192.4,175.2"/>', '<polygon fill="#7F0068" points="182.1,158.1 176.8,161.5 182.1,164.9"/>', '<polygon fill="#7F0068" points="209.3,148 203.1,149.4 208,154.2"/>', '<polygon fill="#7F0068" points="209.3,175 208,168.8 203.1,173.6"/>', '<polygon fill="#7F0068" points="183.7,168.8 182.4,175 188.6,173.6"/>', '<polygon fill="#7F0068" points="188.6,149.4 182.4,148 183.7,154.2"/>' ) ) ); } /// @dev Mark N°10 => Moon function item_10() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#7F0068" d="M197.2,142.1c-5.8,0-10.9,2.9-13.9,7.3c2.3-2.3,5.4-3.7,8.9-3.7c7.1,0,12.9,5.9,12.9,13.3 s-5.8,13.3-12.9,13.3c-3.4,0-6.6-1.4-8.9-3.7c3.1,4.4,8.2,7.3,13.9,7.3c9.3,0,16.9-7.6,16.9-16.9S206.6,142.1,197.2,142.1z"/>' ) ) ); } /// @dev Mark N°11 => Third Eye function item_11() public pure returns (string memory) { return base( string( abi.encodePacked( '<path opacity="0.81" fill="#FFFFFF" d="M184.4,159.3c0.7,3.5,0.8,8.5,6.3,8.8 c5.5,1.6,23.2,4.2,23.8-7.6c1.2-6.1-10-9.5-15.5-9.3C193.8,152.6,184.1,153.5,184.4,159.3z"/>', '<path d="M213.6,155.6c-0.2-0.2-0.4-0.4-0.6-0.6"/>', '<path d="M211.8,154c-7.7-6.6-23.5-4.9-29.2,3.6c9.9-7.1,26.1-6.1,34.4,2.4c0-0.3-0.7-1.5-2-3.1"/>', '<path d="M197.3,146.8c4.3-0.6,9.1,0.3,12.7,2.7C206,147.7,201.8,146.5,197.3,146.8L197.3,146.8z M193.6,147.5 c-2,0.9-4.1,1.8-6.1,2.6C189.2,148.8,191.5,147.8,193.6,147.5z"/>', '<path d="M187.6,167.2c5.2,2,18.5,3.2,23.3,0.1C206.3,171.3,192.7,170,187.6,167.2z"/>', '<path fill="#0B1F26" d="M199.6,151c11.1-0.2,11.1,17.4,0,17.3C188.5,168.4,188.5,150.8,199.6,151z"/>' ) ) ); } /// @dev Mark N°12 => Tori function item_12() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" x1="231.2" y1="221.5" x2="231.2" y2="228.4"/>', '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M228.6,221.2c0,0,3.2,0.4,5.5,0.2"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M237.3,221.5c0,0-3.5,3.1,0,6.3C240.8,231,242.2,221.5,237.3,221.5z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M243.2,227.8l-1.2-6.4c0,0,8.7-2,1,2.8l3.2,3"/>', '<line fill-rule="evenodd" clip-rule="evenodd" fill="#FFEBB4" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" x1="248.5" y1="221" x2="248.5" y2="227.5"/>', '<path d="M254.2,226c0,0,0.1,0,0.1,0c0,0,0.1,0,0.1-0.1l1.3-2.2c0.5-0.9-0.2-2.2-1.2-2c-0.6,0.1-0.8,0.7-0.9,0.8 c-0.1-0.1-0.5-0.5-1.1-0.4c-1,0.2-1.3,1.7-0.4,2.3L254.2,226z"/>' ) ) ); } /// @dev Mark N°13 => Ether function item_13() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M196.5,159.9l-12.4-5.9l12.4,21.6l12.4-21.6L196.5,159.9z"/>', '<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M207.5,149.6l-11-19.1l-11,19.2l11-5.2L207.5,149.6z"/>', '<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M186.5,152.2l10.1,4.8l10.1-4.8l-10.1-4.8L186.5,152.2z"/>' ) ) ); } /// @notice Return the mark name of the given id /// @param id The mark Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Blush Cheeks"; } else if (id == 3) { name = "Dark Circle"; } else if (id == 4) { name = "Chin Scar"; } else if (id == 5) { name = "Blush"; } else if (id == 6) { name = "Chin"; } else if (id == 7) { name = "Yinyang"; } else if (id == 8) { name = "Scar"; } else if (id == 9) { name = "Sun"; } else if (id == 10) { name = "Moon"; } else if (id == 11) { name = "Third Eye"; } else if (id == 12) { name = "Tori"; } else if (id == 13) { name = "Ether"; } } /// @dev The base SVG for the hair function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Mark">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; import "./constants/Colors.sol"; /// @title Accessory SVG generator library AccessoryDetail { /// @dev Accessory N°1 => Classic function item_1() public pure returns (string memory) { return ""; } /// @dev Accessory N°2 => Glasses function item_2() public pure returns (string memory) { return base(glasses("D1F5FF", "000000", "0.31")); } /// @dev Accessory N°3 => Bow Tie function item_3() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-width="7" stroke-miterlimit="10" d="M176.2,312.5 c3.8,0.3,26.6,7.2,81.4-0.4"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="#DF0849" stroke="#000000" stroke-miterlimit="10" d="M211.3,322.1 c-2.5-0.3-5-0.5-7.4,0c-1.1,0-1.9-1.4-1.9-3.1v-4.5c0-1.7,0.9-3.1,1.9-3.1c2.3,0.6,4.8,0.5,7.4,0c1.1,0,1.9,1.4,1.9,3.1v4.5 C213.2,320.6,212.3,322.1,211.3,322.1z"/>', '<path fill="#DF0849" stroke="#000000" stroke-miterlimit="10" d="M202.4,321.5c0,0-14,5.6-17.7,5.3c-1.1-0.1-2.5-4.6-1.2-10.5 c0,0-1-2.2-0.3-9.5c0.4-3.4,19.2,5.1,19.2,5.1S201,316.9,202.4,321.5z"/>', '<path fill="#DF0849" stroke="#000000" stroke-miterlimit="10" d="M212.6,321.5c0,0,14,5.6,17.7,5.3c1.1-0.1,2.5-4.6,1.2-10.5 c0,0,1-2.2,0.3-9.5c-0.4-3.4-19.2,5.1-19.2,5.1S213.9,316.9,212.6,321.5z"/>', '<path opacity="0.41" d="M213.6,315.9l6.4-1.1l-3.6,1.9l4.1,1.1l-7-0.6L213.6,315.9z M201.4,316.2l-6.4-1.1l3.6,1.9l-4.1,1.1l7-0.6L201.4,316.2z"/>' ) ) ); } /// @dev Accessory N°4 => Monk Beads Classic function item_4() public pure returns (string memory) { return base(monkBeads("63205A")); } /// @dev Accessory N°5 => Monk Beads Silver function item_5() public pure returns (string memory) { return base(monkBeads("C7D2D4")); } /// @dev Accessory N°6 => Power Pole function item_6() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FF6F4F" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M272.3,331.9l55.2-74.4c0,0,3,4.3,8.7,7.5l-54,72.3"/>', '<polygon fill="#BA513A" points="335.9,265.3 334.2,264.1 279.9,336.1 281.8,337.1"/>', '<ellipse transform="matrix(0.6516 -0.7586 0.7586 0.6516 -82.3719 342.7996)" fill="#B54E36" stroke="#000000" stroke-width="0.25" stroke-miterlimit="10" cx="332" cy="261.1" rx="1.2" ry="6.1"/>', '<path fill="none" stroke="#B09E00" stroke-miterlimit="10" d="M276.9,335.3c-52.7,31.1-119.3,49.4-120.7,49"/>' ) ) ); } /// @dev Accessory N°7 => Vintage Glasses function item_7() public pure returns (string memory) { return base(glasses("FC55FF", "DFA500", "0.31")); } /// @dev Accessory N°8 => Monk Beads Gold function item_8() public pure returns (string memory) { return base(monkBeads("FFDD00")); } /// @dev Accessory N°9 => Eye Patch function item_9() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FCFEFF" stroke="#4A6362" stroke-miterlimit="10" d="M253.6,222.7H219c-4.7,0-8.5-3.8-8.5-8.5v-20.8 c0-4.7,3.8-8.5,8.5-8.5h34.6c4.7,0,8.5,3.8,8.5,8.5v20.8C262.1,218.9,258.3,222.7,253.6,222.7z"/>', '<path fill="none" stroke="#4A6362" stroke-width="0.75" stroke-miterlimit="10" d="M250.1,218.9h-27.6c-3.8,0-6.8-3.1-6.8-6.8 v-16.3c0-3.8,3.1-6.8,6.8-6.8h27.6c3.8,0,6.8,3.1,6.8,6.8V212C257,215.8,253.9,218.9,250.1,218.9z"/>', '<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="211.9" y1="188.4" x2="131.8" y2="183.1"/>', '<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="259.9" y1="188.1" x2="293.4" y2="196.7"/>', '<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="259.2" y1="220.6" x2="277.5" y2="251.6"/>', '<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="211.4" y1="219.1" x2="140.5" y2="242"/>', '<g fill-rule="evenodd" clip-rule="evenodd" fill="#636363" stroke="#4A6362" stroke-width="0.25" stroke-miterlimit="10"><ellipse cx="250.9" cy="215" rx="0.8" ry="1.1"/><ellipse cx="236.9" cy="215" rx="0.8" ry="1.1"/><ellipse cx="250.9" cy="203.9" rx="0.8" ry="1.1"/><ellipse cx="250.9" cy="193.8" rx="0.8" ry="1.1"/><ellipse cx="236.9" cy="193.8" rx="0.8" ry="1.1"/><ellipse cx="221.3" cy="215" rx="0.8" ry="1.1"/><ellipse cx="221.3" cy="203.9" rx="0.8" ry="1.1"/><ellipse cx="221.3" cy="193.8" rx="0.8" ry="1.1"/></g>' ) ) ); } /// @dev Accessory N°10 => Sun Glasses function item_10() public pure returns (string memory) { return base(glasses(Colors.BLACK, Colors.BLACK_DEEP, "1")); } /// @dev Accessory N°11 => Monk Beads Diamond function item_11() public pure returns (string memory) { return base(monkBeads("AAFFFD")); } /// @dev Accessory N°12 => Horns function item_12() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" fill="#212121" stroke="#000000" stroke-linejoin="round" stroke-miterlimit="10" d="M257.7,96.3c0,0,35-18.3,46.3-42.9c0,0-0.9,37.6-23.2,67.6C269.8,115.6,261.8,107.3,257.7,96.3z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="#212121" stroke="#000000" stroke-linejoin="round" stroke-miterlimit="10" d="M162,96.7c0,0-33-17.3-43.7-40.5c0,0,0.9,35.5,21.8,63.8C150.6,114.9,158.1,107.1,162,96.7z"/>' ) ) ); } /// @dev Accessory N°13 => Halo function item_13() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#F6FF99" stroke="#000000" stroke-miterlimit="10" d="M136,67.3c0,14.6,34.5,26.4,77,26.4s77-11.8,77-26.4s-34.5-26.4-77-26.4S136,52.7,136,67.3L136,67.3z M213,79.7c-31.4,0-56.9-6.4-56.9-14.2s25.5-14.2,56.9-14.2s56.9,6.4,56.9,14.2S244.4,79.7,213,79.7z"/>' ) ) ); } /// @dev Accessory N°14 => Saiki Power function item_14() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-width="5" stroke-miterlimit="10" x1="270.5" y1="105.7" x2="281.7" y2="91.7"/>', '<circle fill="#EB7FFF" stroke="#000000" stroke-miterlimit="10" cx="285.7" cy="85.2" r="9.2"/>', '<line fill="none" stroke="#000000" stroke-width="5" stroke-miterlimit="10" x1="155.8" y1="105.7" x2="144.5" y2="91.7"/>', '<circle fill="#EB7FFF" stroke="#000000" stroke-miterlimit="10" cx="138.7" cy="85.2" r="9.2"/>', '<path opacity="0.17" d="M287.3,76.6c0,0,10.2,8.2,0,17.1c0,0,7.8-0.7,7.4-9.5 C293,75.9,287.3,76.6,287.3,76.6z"/>', '<path opacity="0.17" d="M137,76.4c0,0-10.2,8.2,0,17.1c0,0-7.8-0.7-7.4-9.5 C131.4,75.8,137,76.4,137,76.4z"/>', '<ellipse transform="matrix(0.4588 -0.8885 0.8885 0.4588 80.0823 294.4391)" fill="#FFFFFF" cx="281.8" cy="81.5" rx="2.1" ry="1.5"/>', '<ellipse transform="matrix(0.8885 -0.4588 0.4588 0.8885 -21.756 74.6221)" fill="#FFFFFF" cx="142.7" cy="82.1" rx="1.5" ry="2.1"/>', '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M159.6,101.4c0,0-1.1,4.4-7.4,7.2"/>', '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M267.2,101.4c0,0,1.1,4.4,7.4,7.2"/>', abi.encodePacked( '<polygon opacity="0.68" fill="#7FFF35" points="126,189.5 185.7,191.8 188.6,199.6 184.6,207.4 157.3,217.9 128.6,203.7"/>', '<polygon opacity="0.68" fill="#7FFF35" points="265.7,189.5 206.7,191.8 203.8,199.6 207.7,207.4 234.8,217.9 263.2,203.7"/>', '<polyline fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="196.5,195.7 191.8,195.4 187,190.9 184.8,192.3 188.5,198.9 183,206.8 187.6,208.3 193.1,201.2 196.5,201.2"/>', '<polyline fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="196.4,195.7 201.1,195.4 205.9,190.9 208.1,192.3 204.4,198.9 209.9,206.8 205.3,208.3 199.8,201.2 196.4,201.2"/>', '<polygon fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="123.8,189.5 126.3,203 129.2,204.4 127.5,189.5"/>', '<polygon fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="265.8,189.4 263.3,203.7 284.3,200.6 285.3,189.4"/>' ) ) ) ); } /// @dev Accessory N°15 => No Face function item_15() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#F5F4F3" stroke="#000000" stroke-miterlimit="10" d="M285.5,177.9c0,68.3-19.6,127.3-77.9,128.2 c-58.4,0.9-74.4-57.1-74.4-125.4s14.4-103.5,72.7-103.5C266.7,77.2,285.5,109.6,285.5,177.9z"/>', '<path opacity="0.08" d="M285.4,176.9c0,68.3-19.4,127.6-78,129.3 c27.2-17.6,28.3-49.1,28.3-117.3s23.8-86-30-111.6C266.4,77.3,285.4,108.7,285.4,176.9z"/>', '<ellipse cx="243.2" cy="180.7" rx="16.9" ry="6.1"/>', '<path d="M231.4,273.6c0.3-7.2-12.1-6.1-27.2-6.1s-27.4-1.4-27.2,6.1c0.1,3.4,12.1,6.1,27.2,6.1S231.3,277,231.4,273.6z"/>', '<ellipse cx="162" cy="180.5" rx="16.3" ry="6"/>', '<path fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M149.7,191.4c0,0,6.7,5.8,20.5,0.6"/>', '<path fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M232.9,191.3c0,0,6.6,5.7,20.4,0.6"/>', '<path fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M192.7,285.1c0,0,9.2,3.5,21.6,0"/>', '<path fill="#996DAD" d="M150.8,200.5c1.5-3.6,17.2-3.4,18.8-0.4c1.8,3.2-4.8,45.7-6.6,46C159.8,246.8,148.1,211.1,150.8,200.5z"/>', '<path fill="#996DAD" d="M233.9,199.8c1.5-3.6,18-2.7,19.7,0.3c3.7,6.4-6.5,45.5-9.3,45.4C241,245.2,231.1,210.4,233.9,199.8z"/>', '<path fill="#996DAD" d="M231.3,160.6c1.3,2.3,14.7,2.1,16.1,0.2c1.6-2-4.1-27.7-7.2-28.2C236.9,132.2,229,154.1,231.3,160.6z"/>', '<path fill="#996DAD" d="M152.9,163.2c1.3,2.3,14.7,2.1,16.1,0.2c1.6-2-4.1-27.7-7.2-28.2C158.6,134.8,150.6,156.6,152.9,163.2z"/>' ) ) ); } /// @dev Generate glasses with the given color and opacity function glasses( string memory color, string memory stroke, string memory opacity ) private pure returns (string memory) { return string( abi.encodePacked( '<circle fill="none" stroke="#', stroke, '" stroke-miterlimit="10" cx="161.5" cy="201.7" r="23.9"/>', '<circle fill="none" stroke="#', stroke, '" stroke-miterlimit="10" cx="232.9" cy="201.7" r="23.9"/>', '<circle opacity="', opacity, '" fill="#', color, '" cx="161.5" cy="201.7" r="23.9"/>', abi.encodePacked( '<circle opacity="', opacity, '" fill="#', color, '" cx="232.9" cy="201.7" r="23.9"/>', '<path fill="none" stroke="#', stroke, '" stroke-miterlimit="10" d="M256.8,201.7l35.8-3.2 M185.5,201.7 c0,0,14.7-3.1,23.5,0 M137.6,201.7l-8.4-3.2"/>' ) ) ); } /// @dev Generate Monk Beads SVG with the given color function monkBeads(string memory color) private pure returns (string memory) { return string( abi.encodePacked( '<g fill="#', color, '" stroke="#2B232B" stroke-miterlimit="10" stroke-width="0.75">', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.3439 3.0256)" cx="176.4" cy="317.8" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.458 3.2596)" cx="190.2" cy="324.6" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.5085 3.5351)" cx="206.4" cy="327.8" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.4607 4.0856)" cx="239.1" cy="325.2" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.693338e-02 1.693338e-02 0.9999 -5.386 4.3606)" cx="254.8" cy="320.2" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.5015 3.8124)" cx="222.9" cy="327.5" rx="7.9" ry="8"/>', "</g>", '<path opacity="0.14" d="M182,318.4 c0.7,1.3-0.4,3.4-2.5,4.6c-2.1,1.2-4.5,1-5.2-0.3c-0.7-1.3,0.4-3.4,2.5-4.6C178.9,316.9,181.3,317,182,318.4z M190.5,325.7 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3s3.2-3.2,2.5-4.6C195,324.6,192.7,324.5,190.5,325.7z M206.7,328.6 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6C211.1,327.6,208.8,327.5,206.7,328.6z M223.2,328.4 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6S225.3,327.3,223.2,328.4z M239.8,325.7 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6C244.3,324.7,242,324.5,239.8,325.7z M255.7,320.9 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6C260.1,319.9,257.8,319.7,255.7,320.9z"/>', abi.encodePacked( '<g fill="#FFFFFF" stroke="#FFFFFF" stroke-miterlimit="10">', '<path d="M250.4,318.9c0.6,0.6,0.5-0.9,1.3-2c0.8-1,2.4-1.2,1.8-1.8 c-0.6-0.6-1.9-0.2-2.8,0.9C250,317,249.8,318.3,250.4,318.9z"/>', '<path d="M234.4,323.6c0.7,0.6,0.5-0.9,1.4-1.9c1-1,2.5-1.1,1.9-1.7 c-0.7-0.6-1.9-0.3-2.8,0.7C234.1,321.7,233.8,323,234.4,323.6z"/>', '<path d="M218.2,325.8c0.6,0.6,0.6-0.9,1.4-1.8c1-1,2.5-1,1.9-1.6 c-0.6-0.6-1.9-0.4-2.8,0.6C217.8,323.9,217.6,325.2,218.2,325.8z"/>', '<path d="M202.1,325.5c0.6,0.6,0.6-0.9,1.7-1.7s2.6-0.8,2-1.5 c-0.6-0.6-1.8-0.5-2.9,0.4C202,323.5,201.5,324.8,202.1,325.5z"/>', '<path d="M186.2,322c0.6,0.6,0.6-0.9,1.7-1.7c1-0.8,2.6-0.8,2-1.5 c-0.6-0.6-1.8-0.5-2.9,0.3C186,320.1,185.7,321.4,186.2,322z"/>', '<path d="M171.7,315.4c0.6,0.6,0.6-0.9,1.5-1.8s2.5-0.9,1.9-1.6 s-1.9-0.4-2.8,0.5C171.5,313.5,171.1,314.9,171.7,315.4z"/>', "</g>" ) ) ); } /// @notice Return the accessory name of the given id /// @param id The accessory Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Glasses"; } else if (id == 3) { name = "Bow Tie"; } else if (id == 4) { name = "Monk Beads Classic"; } else if (id == 5) { name = "Monk Beads Silver"; } else if (id == 6) { name = "Power Pole"; } else if (id == 7) { name = "Vintage Glasses"; } else if (id == 8) { name = "Monk Beads Gold"; } else if (id == 9) { name = "Eye Patch"; } else if (id == 10) { name = "Sun Glasses"; } else if (id == 11) { name = "Monk Beads Diamond"; } else if (id == 12) { name = "Horns"; } else if (id == 13) { name = "Halo"; } else if (id == 14) { name = "Saiki Power"; } else if (id == 15) { name = "No Face"; } } /// @dev The base SVG for the accessory function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Accessory">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Earrings SVG generator library EarringsDetail { /// @dev Earrings N°1 => Classic function item_1() public pure returns (string memory) { return ""; } /// @dev Earrings N°2 => Circle function item_2() public pure returns (string memory) { return base(circle("000000")); } /// @dev Earrings N°3 => Circle Silver function item_3() public pure returns (string memory) { return base(circle("C7D2D4")); } /// @dev Earrings N°4 => Ring function item_4() public pure returns (string memory) { return base(ring("000000")); } /// @dev Earrings N°5 => Circle Gold function item_5() public pure returns (string memory) { return base(circle("FFDD00")); } /// @dev Earrings N°6 => Ring Gold function item_6() public pure returns (string memory) { return base(ring("FFDD00")); } /// @dev Earrings N°7 => Heart function item_7() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M284.3,247.9c0.1,0.1,0.1,0.1,0.2,0.1s0.2,0,0.2-0.1l3.7-3.8c1.5-1.6,0.4-4.3-1.8-4.3c-1.3,0-1.9,1-2.2,1.2c-0.2-0.2-0.8-1.2-2.2-1.2c-2.2,0-3.3,2.7-1.8,4.3L284.3,247.9z"/>', '<path d="M135,246.6c0,0,0.1,0.1,0.2,0.1s0.1,0,0.2-0.1l3.1-3.1c1.3-1.3,0.4-3.6-1.5-3.6c-1.1,0-1.6,0.8-1.8,1c-0.2-0.2-0.7-1-1.8-1c-1.8,0-2.8,2.3-1.5,3.6L135,246.6z"/>' ) ) ); } /// @dev Earrings N°8 => Gold function item_8() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M298.7,228.1l-4.7-1.6c0,0-0.1,0-0.1-0.1v-0.1c2.8-2.7,7.1-17.2,7.2-17.4c0-0.1,0.1-0.1,0.1-0.1l0,0c5.3,1.1,5.6,2.2,5.7,2.4c-3.1,5.4-8,16.7-8.1,16.8C298.9,228,298.8,228.1,298.7,228.1C298.8,228.1,298.8,228.1,298.7,228.1z" style="fill: #fff700;stroke: #000;stroke-miterlimit: 10;stroke-width: 0.75px"/>' ) ) ); } /// @dev Earrings N°9 => Circle Diamond function item_9() public pure returns (string memory) { return base(circle("AAFFFD")); } /// @dev Earrings N°10 => Drop Heart function item_10() public pure returns (string memory) { return base( string( abi.encodePacked( drop(true), '<path fill="#F44336" d="M285.4,282.6c0.1,0.1,0.2,0.2,0.4,0.2s0.3-0.1,0.4-0.2l6.7-6.8c2.8-2.8,0.8-7.7-3.2-7.7c-2.4,0-3.5,1.8-3.9,2.1c-0.4-0.3-1.5-2.1-3.9-2.1c-4,0-6,4.9-3.2,7.7L285.4,282.6z"/>', drop(false), '<path fill="#F44336" d="M134.7,282.5c0.1,0.1,0.2,0.2,0.4,0.2s0.3-0.1,0.4-0.2l6.7-6.8c2.8-2.8,0.8-7.7-3.2-7.7c-2.4,0-3.5,1.8-3.9,2.1c-0.4-0.3-1.5-2.1-3.9-2.1c-4,0-6,4.9-3.2,7.7L134.7,282.5z"/>' ) ) ); } /// @dev Earrings N11 => Ether function item_11() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M285.7,242.7l-4.6-2.2l4.6,8l4.6-8L285.7,242.7z"/>', '<path d="M289.8,238.9l-4.1-7.1l-4.1,7.1l4.1-1.9L289.8,238.9z"/>', '<path d="M282,239.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,239.9z"/>', '<path d="M134.5,241.8l-3.4-1.9l3.7,7.3l2.8-7.7L134.5,241.8z"/>', '<path d="M137.3,238l-3.3-6.5l-2.5,6.9l2.8-2L137.3,238z"/>', '<path d="M131.7,239.2l2.8,1.5l2.6-1.8l-2.8-1.5L131.7,239.2z"/>' ) ) ); } /// @dev Earrings N°12 => Drop Ether function item_12() public pure returns (string memory) { return base( string( abi.encodePacked( drop(true), '<path d="M285.7,279.7l-4.6-2.2l4.6,8l4.6-8L285.7,279.7z"/>', '<path d="M289.8,275.9l-4.1-7.1l-4.1,7.1l4.1-1.9L289.8,275.9z"/>', '<path d="M282,276.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,276.9z"/><path d="M282,276.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,276.9z"/>', drop(false), '<path d="M135.1,279.7l-4-2.2l4,8l4-8L135.1,279.7z"/>', '<path d="M138.7,275.9l-3.6-7.1l-3.6,7.1l3.6-1.9L138.7,275.9z"/>', '<path d="M131.8,276.9l3.3,1.8l3.3-1.8l-3.3-1.8L131.8,276.9z"/>' ) ) ); } /// @dev earring drop function drop(bool right) private pure returns (string memory) { return string( right ? abi.encodePacked( '<circle cx="285.7" cy="243.2" r="3.4"/>', '<line fill="none" stroke="#000000" stroke-miterlimit="10" x1="285.7" y1="243.2" x2="285.7" y2="270.2"/>' ) : abi.encodePacked( '<ellipse cx="135.1" cy="243.2" rx="3" ry="3.4"/>', '<line fill="none" stroke="#000000" stroke-miterlimit="10" x1="135.1" y1="243.2" x2="135.1" y2="270.2"/>' ) ); } /// @dev Generate circle SVG with the given color function circle(string memory color) private pure returns (string memory) { return string( abi.encodePacked( '<ellipse fill="#', color, '" stroke="#000000" cx="135.1" cy="243.2" rx="3" ry="3.4"/>', '<ellipse fill="#', color, '" stroke="#000000" cx="286.1" cy="243.2" rx="3.3" ry="3.4"/>' ) ); } /// @dev Generate ring SVG with the given color function ring(string memory color) private pure returns (string memory) { return string( abi.encodePacked( '<path fill="none" stroke="#', color, '" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M283.5,246c0,0-4.2,2-3.1,6.1c1,4.1,5.1,3.6,5.4,3.5s3.1-0.9,3-5"/>', '<path fill="none" stroke="#', color, '" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M134.3,244.7c0,0-4.2,2-3.1,6.1c1,4.1,5.1,3.6,5.4,3.5c0.3-0.1,3.1-0.9,3-5"/>' ) ); } /// @notice Return the earring name of the given id /// @param id The earring Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Circle"; } else if (id == 3) { name = "Circle Silver"; } else if (id == 4) { name = "Ring"; } else if (id == 5) { name = "Circle Gold"; } else if (id == 6) { name = "Ring Gold"; } else if (id == 7) { name = "Heart"; } else if (id == 8) { name = "Gold"; } else if (id == 9) { name = "Circle Diamond"; } else if (id == 10) { name = "Drop Heart"; } else if (id == 11) { name = "Ether"; } else if (id == 12) { name = "Drop Ether"; } } /// @dev The base SVG for the earrings function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Earrings">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; import "./constants/Colors.sol"; /// @title Masks SVG generator library MaskDetail { /// @dev Mask N°1 => Maskless function item_1() public pure returns (string memory) { return ""; } /// @dev Mask N°2 => Classic function item_2() public pure returns (string memory) { return base(classicMask("575673")); } /// @dev Mask N°3 => Blue function item_3() public pure returns (string memory) { return base(classicMask(Colors.BLUE)); } /// @dev Mask N°4 => Pink function item_4() public pure returns (string memory) { return base(classicMask(Colors.PINK)); } /// @dev Mask N°5 => Black function item_5() public pure returns (string memory) { return base(classicMask(Colors.BLACK)); } /// @dev Mask N°6 => Bandage White function item_6() public pure returns (string memory) { return base(string(abi.encodePacked(classicMask("F5F5F5"), bandage()))); } /// @dev Mask N°7 => Bandage Classic function item_7() public pure returns (string memory) { return base(string(abi.encodePacked(classicMask("575673"), bandage()))); } /// @dev Mask N°8 => Nihon function item_8() public pure returns (string memory) { return base( string( abi.encodePacked( classicMask("F5F5F5"), '<ellipse opacity="0.87" fill="#FF0039" cx="236.1" cy="259.8" rx="13.4" ry="14.5"/>' ) ) ); } /// @dev Generate classic mask SVG with the given color function classicMask(string memory color) public pure returns (string memory) { return string( abi.encodePacked( '<path fill="#', color, '" stroke="#000000" stroke-miterlimit="10" d=" M175.7,317.7c0,0,20,15.1,82.2,0c0,0-1.2-16.2,3.7-46.8l14-18.7c0,0-41.6-27.8-77.6-37.1c-1.1-0.3-3-0.7-4-0.2 c-19.1,8.1-51.5,33-51.5,33s7.5,20.9,9.9,22.9s24.8,19.4,24.8,19.4s0,0,0,0.1C177.3,291.2,178,298.3,175.7,317.7z"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M177.1,290.1 c0,0,18.3,14.7,26.3,15s15.1-3.8,15.9-4.3c0.9-0.4,11.6-4.5,25.2-14.1"/>', '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="266.6" y1="264.4" x2="254.5" y2="278.7"/>', '<path opacity="0.21" d="M197.7,243.5l-7.9-3.5c-0.4-0.2-0.5-0.7-0.2-1.1l3.2-3.3 c0.4-0.4,1-0.5,1.5-0.3l12.7,4.6c0.6,0.2,0.6,1.1-0.1,1.3l-8.7,2.4C198,243.6,197.8,243.6,197.7,243.5z"/>', '<path opacity="0.24" fill-rule="evenodd" clip-rule="evenodd" d="M177.2,291.1 c0,0,23,32.3,39.1,28.1s41.9-20.9,41.9-20.9c1.2-8.7,2.1-18.9,3.2-27.6c-4.6,4.7-12.8,13.2-20.9,18.3c-5,3.1-21.2,14.5-34.9,16 C198.3,305.8,177.2,291.1,177.2,291.1z"/>' ) ); } /// @dev Generate bandage SVG function bandage() public pure returns (string memory) { return string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M142.9,247.9c34.3-21.9,59.3-27.4,92.4-18.5 M266.1,264.1c-21-16.2-60.8-36.4-73.9-29.1c-12.8,7.1-36.4,15.6-45.8,22.7 M230.9,242.8c-32.4,2.5-54.9,0.1-81.3,22.7 M259.8,272.3c-19.7-13.9-46.1-24.1-70.3-25.9 M211.6,250.1c-18.5,1.9-41.8,11.2-56.7,22 M256.7,276.1c-46-11.9-50.4-25.6-94,2.7 M229,267.5c-19.9,0.3-42,9.7-60.6,15.9 M238.4,290.6c-11-3.9-39.3-14.6-51.2-14 M214.5,282.5c-10.3-2.8-23,7.6-30.7,12.6 M221.6,299.8c-3.8-5.5-22.1-7.1-27-11.4 M176.2,312.4c8.2,7.3,65.1,6.4,81.2-2.6 M177.3,305.3c11.1,3.6,15.5,4.2,34.6,2.9 c14.5-1,33.2-2.7,46.2-9.2 M224.4,298.4c9,0,25.6-3.3,34.1-6 M249,285.8c3.6-0.2,7.1-1,10.5-2.3 M215.1,225.7 c-6-1.3-11.9-2.3-17.9-3.6c-4.8-1-9.8-2.1-14.7-1.3"/>' ) ); } /// @notice Return the mask name of the given id /// @param id The mask Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Maskless"; } else if (id == 2) { name = "Classic"; } else if (id == 3) { name = "Blue"; } else if (id == 4) { name = "Pink"; } else if (id == 5) { name = "Black"; } else if (id == 6) { name = "Bandage White"; } else if (id == 7) { name = "Bandage Classic"; } else if (id == 8) { name = "Nihon"; } } /// @dev The base SVG for the eyes function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Mask">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; /// @title Color constants library Colors { string internal constant BLACK = "33333D"; string internal constant BLACK_DEEP = "000000"; string internal constant BLUE = "7FBCFF"; string internal constant BROWN = "735742"; string internal constant GRAY = "7F8B8C"; string internal constant GREEN = "2FC47A"; string internal constant PINK = "FF78A9"; string internal constant PURPLE = "A839A4"; string internal constant RED = "D9005E"; string internal constant SAIKI = "F02AB6"; string internal constant WHITE = "F7F7F7"; string internal constant YELLOW = "EFED8F"; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } }
@dev Mouth N°13 => Uwu
function item_13() public pure returns (string memory) { return base( string( abi.encodePacked( '<polyline fill="#FFFFFF" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" points="212.7,262.9 216,266.5 217.5,261.7"/>', '<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M176.4,256c0,0,5.7,13.4,23.1,4.2"/>', '<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M224.7,254.8c0,0-9.5,15-25.2,5.4"/>' ) ) ); }
5,890,243
[ 1, 49, 15347, 423, 131, 113, 3437, 516, 587, 91, 89, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 761, 67, 3437, 1435, 1071, 16618, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 203, 5411, 1026, 12, 203, 7734, 533, 12, 203, 10792, 24126, 18, 3015, 4420, 329, 12, 203, 13491, 2368, 16353, 1369, 3636, 1546, 7, 18343, 6, 11040, 1546, 7, 9449, 6, 11040, 17, 2819, 1546, 20, 18, 25, 6, 11040, 17, 1938, 264, 3595, 1546, 2163, 6, 3143, 1546, 22, 2138, 18, 27, 16, 5558, 22, 18, 29, 576, 2313, 16, 5558, 26, 18, 25, 576, 4033, 18, 25, 16, 5558, 21, 18, 27, 6, 18280, 16, 203, 13491, 2368, 803, 3636, 1546, 6102, 6, 11040, 1546, 7, 9449, 6, 11040, 17, 2819, 1546, 20, 18, 5877, 6, 11040, 17, 7511, 557, 438, 1546, 2260, 6, 11040, 17, 1369, 5701, 1546, 2260, 6, 11040, 17, 1938, 264, 3595, 1546, 2163, 6, 302, 1546, 49, 28493, 18, 24, 16, 5034, 71, 20, 16, 20, 16, 25, 18, 27, 16, 3437, 18, 24, 16, 4366, 18, 21, 16, 24, 18, 22, 6, 18280, 16, 203, 13491, 2368, 803, 3636, 1546, 6102, 6, 11040, 1546, 7, 9449, 6, 11040, 17, 2819, 1546, 20, 18, 5877, 6, 11040, 17, 7511, 557, 438, 1546, 2260, 6, 11040, 17, 1369, 5701, 1546, 2260, 6, 11040, 17, 1938, 264, 3595, 1546, 2163, 6, 302, 1546, 49, 23622, 18, 27, 16, 26261, 18, 28, 71, 20, 16, 20, 17, 29, 18, 25, 16, 3600, 17, 2947, 18, 22, 16, 25, 18, 24, 6, 18280, 203, 10792, 262, 203, 7734, 262, 203, 5411, 11272, 203, 565, 2 ]
pragma solidity ^0.4.24; // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @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 relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @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 { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ 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(); } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting '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; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: zeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } // File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: zeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: contracts/NectarToken.sol contract NectarToken is MintableToken { string public name = "Nectar"; string public symbol = "NCT"; uint8 public decimals = 18; bool public transfersEnabled = false; event TransfersEnabled(); // Disable transfers until after the sale modifier whenTransfersEnabled() { require(transfersEnabled, "Transfers not enabled"); _; } modifier whenTransfersNotEnabled() { require(!transfersEnabled, "Transfers enabled"); _; } function enableTransfers() public onlyOwner whenTransfersNotEnabled { transfersEnabled = true; emit TransfersEnabled(); } function transfer(address to, uint256 value) public whenTransfersEnabled returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenTransfersEnabled returns (bool) { return super.transferFrom(from, to, value); } // Approves and then calls the receiving contract function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit 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. // solium-disable-next-line security/no-low-level-calls, indentation require(_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData), "receiveApproval failed"); return true; } } // File: contracts/ArbiterStaking.sol //import "./ArbiterStaking.sol"; contract BountyRegistry is Pausable { using SafeMath for uint256; using SafeERC20 for NectarToken; string public constant VERSION = "1.0.0"; struct Bounty { uint128 guid; address author; uint256 amount; string artifactURI; uint256 numArtifacts; uint256 expirationBlock; address assignedArbiter; bool quorumReached; uint256 quorumBlock; uint256 quorumMask; } struct Assertion { address author; uint256 bid; uint256 mask; uint256 commitment; uint256 nonce; uint256 verdicts; string metadata; } struct Vote { address author; uint256 votes; bool validBloom; } event AddedArbiter( address arbiter, uint256 blockNumber ); event RemovedArbiter( address arbiter, uint256 blockNumber ); event NewBounty( uint128 guid, address author, uint256 amount, string artifactURI, uint256 expirationBlock ); event NewAssertion( uint128 bountyGuid, address author, uint256 index, uint256 bid, uint256 mask, uint256 numArtifacts, uint256 commitment ); event RevealedAssertion( uint128 bountyGuid, address author, uint256 index, uint256 nonce, uint256 verdicts, uint256 numArtifacts, string metadata ); event NewVote( uint128 bountyGuid, uint256 votes, uint256 numArtifacts, address voter ); event QuorumReached( uint128 bountyGuid ); event SettledBounty( uint128 bountyGuid, address settler, uint256 payout ); ArbiterStaking public staking; NectarToken internal token; uint256 public constant BOUNTY_FEE = 62500000000000000; uint256 public constant ASSERTION_FEE = 31250000000000000; uint256 public constant BOUNTY_AMOUNT_MINIMUM = 62500000000000000; uint256 public constant ASSERTION_BID_MINIMUM = 62500000000000000; uint256 public constant ARBITER_LOOKBACK_RANGE = 100; uint256 public constant MAX_DURATION = 100; // BLOCKS uint256 public constant ASSERTION_REVEAL_WINDOW = 25; // BLOCKS uint256 public constant MALICIOUS_VOTE_COEFFICIENT = 10; uint256 public constant BENIGN_VOTE_COEFFICIENT = 1; uint256 public constant VALID_HASH_PERIOD = 256; // number of blocks in the past you can still get a blockhash uint256 public arbiterCount; uint256 public arbiterVoteWindow; uint128[] public bountyGuids; mapping (uint128 => Bounty) public bountiesByGuid; mapping (uint128 => Assertion[]) public assertionsByGuid; mapping (uint128 => Vote[]) public votesByGuid; mapping (uint128 => uint256[8]) public bloomByGuid; mapping (uint128 => mapping (uint256 => uint256)) public quorumVotesByGuid; mapping (address => bool) public arbiters; mapping (uint256 => mapping (uint256 => uint256)) public voteCountByGuid; mapping (uint256 => mapping (address => bool)) public arbiterVoteRegistryByGuid; mapping (uint256 => mapping (address => bool)) public expertAssertionResgistryByGuid; mapping (uint128 => mapping (address => bool)) public bountySettled; /** * Construct a new BountyRegistry * * @param _token address of NCT token to use */ constructor(address _token, address _arbiterStaking, uint256 _arbiterVoteWindow) Ownable() public { owner = msg.sender; token = NectarToken(_token); staking = ArbiterStaking(_arbiterStaking); arbiterVoteWindow = _arbiterVoteWindow; } /** * Function to check if an address is a valid arbiter * * @param addr The address to check * @return true if addr is a valid arbiter else false */ function isArbiter(address addr) public view returns (bool) { // Remove arbiter requirements for now, while we are whitelisting // arbiters on the platform //return arbiters[addr] && staking.isEligible(addr); return arbiters[addr]; } /** Function only callable by arbiter */ modifier onlyArbiter() { require(isArbiter(msg.sender), "msg.sender is not an arbiter"); _; } /** * Function called to add an arbiter, emits an evevnt with the added arbiter * and block number used to calculate their arbiter status based on public * arbiter selection algorithm. * * @param newArbiter the arbiter to add * @param blockNumber the block number the determination to add was * calculated from */ function addArbiter(address newArbiter, uint256 blockNumber) external whenNotPaused onlyOwner { require(newArbiter != address(0), "Invalid arbiter address"); require(!arbiters[newArbiter], "Address is already an arbiter"); arbiterCount = arbiterCount.add(1); arbiters[newArbiter] = true; emit AddedArbiter(newArbiter, blockNumber); } /** * Function called to remove an arbiter, emits an evevnt with the removed * arbiter and block number used to calculate their arbiter status based on * public arbiter selection algorithm. * * @param arbiter the arbiter to remove * @param blockNumber the block number the determination to remove was * calculated from */ function removeArbiter(address arbiter, uint256 blockNumber) external whenNotPaused onlyOwner { arbiters[arbiter] = false; arbiterCount = arbiterCount.sub(1); emit RemovedArbiter(arbiter, blockNumber); } /** * Function called by end users and ambassadors to post a bounty * * @param guid the guid of the bounty, must be unique * @param amount the amount of NCT to post as a reward * @param artifactURI uri of the artifacts comprising this bounty * @param durationBlocks duration of this bounty in blocks */ function postBounty( uint128 guid, uint256 amount, string artifactURI, uint256 numArtifacts, uint256 durationBlocks, uint256[8] bloom ) external whenNotPaused { // Check if a bounty with this GUID has already been initialized require(bountiesByGuid[guid].author == address(0), "GUID already in use"); // Check that our bounty amount is sufficient require(amount >= BOUNTY_AMOUNT_MINIMUM, "Bounty amount below minimum"); // Check that our URI is non-empty require(bytes(artifactURI).length > 0, "Invalid artifact URI"); // Check that our number of artifacts is valid require(numArtifacts <= 256, "Too many artifacts in bounty"); require(numArtifacts > 0, "Not enough artifacts in bounty"); // Check that our duration is non-zero and less than or equal to the max require(durationBlocks > 0 && durationBlocks <= MAX_DURATION, "Invalid bounty duration"); // Assess fees and transfer bounty amount into escrow token.safeTransferFrom(msg.sender, address(this), amount.add(BOUNTY_FEE)); bountiesByGuid[guid].guid = guid; bountiesByGuid[guid].author = msg.sender; bountiesByGuid[guid].amount = amount; bountiesByGuid[guid].artifactURI = artifactURI; // Number of artifacts is submitted as part of the bounty, we have no // way to check how many exist in this IPFS resource. For an IPFS // resource with N artifacts, if numArtifacts < N only the first // numArtifacts artifacts are included in this bounty, if numArtifacts > // N then the last N - numArtifacts bounties are considered benign. bountiesByGuid[guid].numArtifacts = numArtifacts; bountiesByGuid[guid].expirationBlock = durationBlocks.add(block.number); bountyGuids.push(guid); bloomByGuid[guid] = bloom; emit NewBounty( bountiesByGuid[guid].guid, bountiesByGuid[guid].author, bountiesByGuid[guid].amount, bountiesByGuid[guid].artifactURI, bountiesByGuid[guid].expirationBlock ); } /** * Function called by security experts to post an assertion on a bounty * * @param bountyGuid the guid of the bounty to assert on * @param bid the amount of NCT to stake * @param mask the artifacts to assert on from the set in the bounty * @param commitment a commitment hash of the verdicts being asserted, equal * to keccak256(verdicts ^ keccak256(nonce)) where nonce != 0 */ function postAssertion( uint128 bountyGuid, uint256 bid, uint256 mask, uint256 commitment ) external whenNotPaused { // Check if this bounty has been initialized require(bountiesByGuid[bountyGuid].author != address(0), "Bounty has not been initialized"); // Check that our bid amount is sufficient require(bid >= ASSERTION_BID_MINIMUM, "Assertion bid below minimum"); // Check if this bounty is active require(bountiesByGuid[bountyGuid].expirationBlock > block.number, "Bounty inactive"); // Check if the sender has already made an assertion require(expertAssertionResgistryByGuid[bountyGuid][msg.sender] == false, "Sender has already asserted"); // Assess fees and transfer bid amount into escrow token.safeTransferFrom(msg.sender, address(this), bid.add(ASSERTION_FEE)); expertAssertionResgistryByGuid[bountyGuid][msg.sender] = true; Assertion memory a = Assertion( msg.sender, bid, mask, commitment, 0, 0, "" ); uint256 index = assertionsByGuid[bountyGuid].push(a) - 1; uint256 numArtifacts = bountiesByGuid[bountyGuid].numArtifacts; emit NewAssertion( bountyGuid, a.author, index, a.bid, a.mask, numArtifacts, a.commitment ); } // https://ethereum.stackexchange.com/questions/4170/how-to-convert-a-uint-to-bytes-in-solidity function uint256_to_bytes(uint256 x) internal pure returns (bytes b) { b = new bytes(32); // solium-disable-next-line security/no-inline-assembly assembly { mstore(add(b, 32), x) } } /** * Function called by security experts to reveal an assertion after bounty * expiration * * @param bountyGuid the guid of the bounty to assert on * @param assertionId the id of the assertion to reveal * @param assertionId the id of the assertion to reveal * @param nonce the nonce used to generate the commitment hash * @param verdicts the verdicts making up this assertion * @param metadata optional metadata to include in the assertion */ function revealAssertion( uint128 bountyGuid, uint256 assertionId, uint256 nonce, uint256 verdicts, string metadata ) external whenNotPaused { // Check if this bounty has been initialized require(bountiesByGuid[bountyGuid].author != address(0), "Bounty has not been initialized"); // Check that the bounty is no longer active require(bountiesByGuid[bountyGuid].expirationBlock <= block.number, "Bounty is still active"); // Check if the reveal round has closed require(bountiesByGuid[bountyGuid].expirationBlock.add(ASSERTION_REVEAL_WINDOW) > block.number, "Reveal round has closed"); // Get numArtifacts to help decode all zero verdicts uint256 numArtifacts = bountiesByGuid[bountyGuid].numArtifacts; // Zero is defined as an invalid nonce require(nonce != 0, "Invalid nonce"); // Check our id require(assertionId < assertionsByGuid[bountyGuid].length, "Invalid assertion ID"); Assertion storage a = assertionsByGuid[bountyGuid][assertionId]; require(a.author == msg.sender, "Incorrect assertion author"); require(a.nonce == 0, "Bounty already revealed"); // Check our commitment hash, by xor-ing verdicts with the hashed nonce // and the sender's address prevent copying assertions by submitting the // same commitment hash and nonce during the reveal round uint256 hashed_nonce = uint256(keccak256(uint256_to_bytes(nonce))); uint256 commitment = uint256(keccak256(uint256_to_bytes(verdicts ^ hashed_nonce ^ uint256(msg.sender)))); require(commitment == a.commitment, "Commitment hash mismatch"); a.nonce = nonce; a.verdicts = verdicts; a.metadata = metadata; emit RevealedAssertion( bountyGuid, a.author, assertionId, a.nonce, a.verdicts, numArtifacts, a.metadata ); } /** * Function called by arbiter after bounty expiration to settle with their * ground truth determination and pay out assertion rewards * * @param bountyGuid the guid of the bounty to settle * @param votes bitset of votes representing ground truth for the * bounty's artifacts */ function voteOnBounty( uint128 bountyGuid, uint256 votes, bool validBloom ) external onlyArbiter whenNotPaused { Bounty storage bounty = bountiesByGuid[bountyGuid]; Vote[] storage bountyVotes = votesByGuid[bountyGuid]; // Check if this bounty has been initialized require(bounty.author != address(0), "Bounty has not been initialized"); // Check that the reveal round has closed require(bounty.expirationBlock.add(ASSERTION_REVEAL_WINDOW) <= block.number, "Reveal round is still active"); // Check if the voting round has closed require(bounty.expirationBlock.add(ASSERTION_REVEAL_WINDOW).add(arbiterVoteWindow) > block.number, "Voting round has closed"); // Check to make sure arbiters can't double vote require(arbiterVoteRegistryByGuid[bountyGuid][msg.sender] == false, "Arbiter has already voted"); Vote memory a = Vote( msg.sender, votes, validBloom ); votesByGuid[bountyGuid].push(a); staking.recordBounty(msg.sender, bountyGuid, block.number); arbiterVoteRegistryByGuid[bountyGuid][msg.sender] = true; uint256 tempQuorumMask = 0; uint256 quorumCount = 0; mapping (uint256 => uint256) quorumVotes = quorumVotesByGuid[bountyGuid]; for (uint256 i = 0; i < bounty.numArtifacts; i++) { if (bounty.quorumMask != 0 && (bounty.quorumMask & (1 << i) != 0)) { tempQuorumMask = tempQuorumMask.add(calculateMask(i, 1)); quorumCount = quorumCount.add(1); continue; } if (votes & (1 << i) != 0) { quorumVotes[i] = quorumVotes[i].add(1); } uint256 benignVotes = bountyVotes.length.sub(quorumVotes[i]); uint256 maxBenignValue = arbiterCount.sub(quorumVotes[i]).mul(BENIGN_VOTE_COEFFICIENT); uint256 maxMalValue = arbiterCount.sub(benignVotes).mul(MALICIOUS_VOTE_COEFFICIENT); if (quorumVotes[i].mul(MALICIOUS_VOTE_COEFFICIENT) >= maxBenignValue || benignVotes.mul(BENIGN_VOTE_COEFFICIENT) > maxMalValue) { tempQuorumMask = tempQuorumMask.add(calculateMask(i, 1)); quorumCount = quorumCount.add(1); } } // set new mask bounty.quorumMask = tempQuorumMask; // check if all arbiters have voted or if we have quorum for all the artifacts if ((bountyVotes.length == arbiterCount || quorumCount == bounty.numArtifacts) && !bounty.quorumReached) { bounty.quorumReached = true; bounty.quorumBlock = block.number.sub(bountiesByGuid[bountyGuid].expirationBlock); emit QuorumReached(bountyGuid); } emit NewVote(bountyGuid, votes, bounty.numArtifacts, msg.sender); } // This struct exists to move state from settleBounty into memory from stack // to avoid solidity limitations struct ArtifactPot { uint256 numWinners; uint256 numLosers; uint256 winnerPool; uint256 loserPool; } /** * Function to calculate the reward disbursment of a bounty * * @param bountyGuid the guid of the bounty to calculate * @return Rewards distributed by the bounty */ function calculateBountyRewards( uint128 bountyGuid ) public view returns (uint256 bountyRefund, uint256 arbiterReward, uint256[] expertRewards) { Bounty storage bounty = bountiesByGuid[bountyGuid]; Assertion[] storage assertions = assertionsByGuid[bountyGuid]; Vote[] storage votes = votesByGuid[bountyGuid]; mapping (uint256 => uint256) quorumVotes = quorumVotesByGuid[bountyGuid]; // Check if this bountiesByGuid[bountyGuid] has been initialized require(bounty.author != address(0), "Bounty has not been initialized"); // Check if this bounty has been previously resolved for the sender require(!bountySettled[bountyGuid][msg.sender], "Bounty has already been settled for sender"); // Check that the voting round has closed // solium-disable-next-line indentation require(bounty.expirationBlock.add(ASSERTION_REVEAL_WINDOW).add(arbiterVoteWindow) <= block.number || bounty.quorumReached, "Voting round is still active and quorum has not been reached"); expertRewards = new uint256[](assertions.length); ArtifactPot memory ap = ArtifactPot({numWinners: 0, numLosers: 0, winnerPool: 0, loserPool: 0}); uint256 i = 0; uint256 j = 0; if (assertions.length == 0 && votes.length == 0) { // Refund the bounty amount and fees to ambassador bountyRefund = bounty.numArtifacts.mul(bounty.amount.add(BOUNTY_FEE)); } else if (assertions.length == 0) { // Refund the bounty amount ambassador bountyRefund = bounty.amount.mul(bounty.numArtifacts); } else if (votes.length == 0) { // Refund bids, fees, and distribute the bounty amount evenly to experts bountyRefund = BOUNTY_FEE.mul(bounty.numArtifacts); for (j = 0; j < assertions.length; j++) { expertRewards[j] = expertRewards[j].add(ASSERTION_FEE); expertRewards[j] = expertRewards[j].add(assertions[j].bid); expertRewards[j] = expertRewards[j].add(bounty.amount.div(assertions.length)); expertRewards[j] = expertRewards[j].mul(bounty.numArtifacts); } } else { for (i = 0; i < bounty.numArtifacts; i++) { ap = ArtifactPot({numWinners: 0, numLosers: 0, winnerPool: 0, loserPool: 0}); bool consensus = quorumVotes[i].mul(MALICIOUS_VOTE_COEFFICIENT) >= votes.length.sub(quorumVotes[i]).mul(BENIGN_VOTE_COEFFICIENT); for (j = 0; j < assertions.length; j++) { bool malicious; // If we didn't assert on this artifact if (assertions[j].mask & (1 << i) == 0) { continue; } // If we haven't revealed set to incorrect value if (assertions[j].nonce == 0) { malicious = !consensus; } else { malicious = (assertions[j].verdicts & assertions[j].mask) & (1 << i) != 0; } if (malicious == consensus) { ap.numWinners = ap.numWinners.add(1); ap.winnerPool = ap.winnerPool.add(assertions[j].bid); } else { ap.numLosers = ap.numLosers.add(1); ap.loserPool = ap.loserPool.add(assertions[j].bid); } } // If nobody asserted on this artifact, refund the ambassador if (ap.numWinners == 0 && ap.numLosers == 0) { bountyRefund = bountyRefund.add(bounty.amount); for (j = 0; j < assertions.length; j++) { expertRewards[j] = expertRewards[j].add(assertions[j].bid); } } else { for (j = 0; j < assertions.length; j++) { expertRewards[j] = expertRewards[j].add(assertions[j].bid); // If we didn't assert on this artifact if (assertions[j].mask & (1 << i) == 0) { continue; } // If we haven't revealed set to incorrect value if (assertions[j].nonce == 0) { malicious = !consensus; } else { malicious = (assertions[j].verdicts & assertions[j].mask) & (1 << i) != 0; } if (malicious == consensus) { expertRewards[j] = expertRewards[j].add(assertions[j].bid.mul(ap.loserPool).div(ap.winnerPool)); expertRewards[j] = expertRewards[j].add(bounty.amount.mul(assertions[j].bid).div(ap.winnerPool)); } else { expertRewards[j] = expertRewards[j].sub(assertions[j].bid); } } } } } // Calculate rewards uint256 pot = bounty.amount.add(BOUNTY_FEE.add(ASSERTION_FEE.mul(assertions.length))); for (i = 0; i < assertions.length; i++) { pot = pot.add(assertions[i].bid); } bountyRefund = bountyRefund.div(bounty.numArtifacts); pot = pot.sub(bountyRefund); for (i = 0; i < assertions.length; i++) { expertRewards[i] = expertRewards[i].div(bounty.numArtifacts); pot = pot.sub(expertRewards[i]); } arbiterReward = pot; } /** * Function called after window has closed to handle reward disbursal * * This function will pay out rewards if the the bounty has a super majority * @param bountyGuid the guid of the bounty to settle */ function settleBounty(uint128 bountyGuid) external whenNotPaused { Bounty storage bounty = bountiesByGuid[bountyGuid]; Assertion[] storage assertions = assertionsByGuid[bountyGuid]; // Check if this bountiesByGuid[bountyGuid] has been initialized require(bounty.author != address(0), "Bounty has not been initialized"); // Check if this bounty has been previously resolved for the sender require(!bountySettled[bountyGuid][msg.sender], "Bounty has already been settled for sender"); // Check that the voting round has closed // solium-disable-next-line indentation require(bounty.expirationBlock.add(ASSERTION_REVEAL_WINDOW).add(arbiterVoteWindow) <= block.number || bounty.quorumReached, "Voting round is still active and quorum has not been reached"); if (isArbiter(msg.sender)) { require(bounty.expirationBlock.add(ASSERTION_REVEAL_WINDOW).add(arbiterVoteWindow) <= block.number, "Voting round still active"); if (bounty.assignedArbiter == address(0)) { if (bounty.expirationBlock.add(ASSERTION_REVEAL_WINDOW).add(arbiterVoteWindow).add(VALID_HASH_PERIOD) >= block.number) { bounty.assignedArbiter = getWeightedRandomArbiter(bountyGuid); } else { bounty.assignedArbiter = msg.sender; } } } uint256 payout = 0; uint256 bountyRefund; uint256 arbiterReward; uint256[] memory expertRewards; (bountyRefund, arbiterReward, expertRewards) = calculateBountyRewards(bountyGuid); bountySettled[bountyGuid][msg.sender] = true; // Disburse rewards if (bountyRefund != 0 && bounty.author == msg.sender) { token.safeTransfer(bounty.author, bountyRefund); payout = payout.add(bountyRefund); } for (uint256 i = 0; i < assertions.length; i++) { if (expertRewards[i] != 0 && assertions[i].author == msg.sender) { token.safeTransfer(assertions[i].author, expertRewards[i]); payout = payout.add(expertRewards[i]); } } if (arbiterReward != 0 && bounty.assignedArbiter == msg.sender) { token.safeTransfer(bounty.assignedArbiter, arbiterReward); payout = payout.add(arbiterReward); } emit SettledBounty(bountyGuid, msg.sender, payout); } /** * Generates a random number from 0 to range based on the last block hash * * @param seed random number for reproducing * @param range end range for random number */ function randomGen(uint256 targetBlock, uint seed, uint256 range) private view returns (int256 randomNumber) { return int256(uint256(keccak256(abi.encodePacked(blockhash(targetBlock), seed))) % range); } /** * Gets a random Arbiter weighted by the amount of Nectar they have * * @param bountyGuid the guid of the bounty */ function getWeightedRandomArbiter(uint128 bountyGuid) public view returns (address voter) { require(bountiesByGuid[bountyGuid].author != address(0), "Bounty has not been initialized"); Bounty memory bounty = bountiesByGuid[bountyGuid]; Vote[] memory votes = votesByGuid[bountyGuid]; if (votes.length == 0) { return address(0); } uint i; uint256 sum = 0; int256 randomNum; for (i = 0; i < votes.length; i++) { sum = sum.add(staking.balanceOf(votes[i].author)); } randomNum = randomGen(bounty.expirationBlock.add(ASSERTION_REVEAL_WINDOW).add(arbiterVoteWindow), block.number, sum); for (i = 0; i < votes.length; i++) { randomNum -= int256(staking.balanceOf(votes[i].author)); if (randomNum <= 0) { voter = votes[i].author; break; } } } /** * Get the total number of bounties tracked by the contract * @return total number of bounties */ function getNumberOfBounties() external view returns (uint) { return bountyGuids.length; } /** * Get the current round for a bounty * * @param bountyGuid the guid of the bounty * @return the current round * 0 = assertions being accepted * 1 = assertions being revealed * 2 = arbiters voting * 3 = bounty finished */ function getCurrentRound(uint128 bountyGuid) external view returns (uint) { // Check if this bounty has been initialized require(bountiesByGuid[bountyGuid].author != address(0), "Bounty has not been initialized"); Bounty memory bounty = bountiesByGuid[bountyGuid]; if (bounty.expirationBlock > block.number) { return 0; } else if (bounty.expirationBlock.add(ASSERTION_REVEAL_WINDOW) > block.number) { return 1; } else if (bounty.expirationBlock.add(ASSERTION_REVEAL_WINDOW).add(arbiterVoteWindow) > block.number && !bounty.quorumReached) { return 2; } else { return 3; } } /** * Gets the number of assertions for a bounty * * @param bountyGuid the guid of the bounty * @return number of assertions for the given bounty */ function getNumberOfAssertions(uint128 bountyGuid) external view returns (uint) { // Check if this bounty has been initialized require(bountiesByGuid[bountyGuid].author != address(0), "Bounty has not been initialized"); return assertionsByGuid[bountyGuid].length; } /** * Gets the vote count for a specific bounty * * @param bountyGuid the guid of the bounty */ function getNumberOfVotes(uint128 bountyGuid) external view returns (uint) { require(bountiesByGuid[bountyGuid].author != address(0), "Bounty has not been initialized"); return votesByGuid[bountyGuid].length; } /** * Gets all the voters for a specific bounty * * @param bountyGuid the guid of the bounty */ function getVoters(uint128 bountyGuid) external view returns (address[]) { require(bountiesByGuid[bountyGuid].author != address(0), "Bounty has not been initialized"); Vote[] memory votes = votesByGuid[bountyGuid]; uint count = votes.length; address[] memory voters = new address[](count); for (uint i = 0; i < count; i++) { voters[i] = votes[i].author; } return voters; } /** Candidate for future arbiter */ struct Candidate { address addr; uint256 count; } /** * View function displays most active bounty posters over past * ARBITER_LOOKBACK_RANGE bounties to select future arbiters * * @return sorted array of most active bounty posters */ function getArbiterCandidates() external view returns (address[]) { require(bountyGuids.length > 0, "No bounties have been placed"); uint256 count = 0; Candidate[] memory candidates = new Candidate[](ARBITER_LOOKBACK_RANGE); uint256 lastBounty = 0; if (bountyGuids.length > ARBITER_LOOKBACK_RANGE) { lastBounty = bountyGuids.length.sub(ARBITER_LOOKBACK_RANGE); } for (uint256 i = bountyGuids.length; i > lastBounty; i--) { address addr = bountiesByGuid[bountyGuids[i.sub(1)]].author; bool found = false; for (uint256 j = 0; j < count; j++) { if (candidates[j].addr == addr) { candidates[j].count = candidates[j].count.add(1); found = true; break; } } if (!found) { candidates[count] = Candidate(addr, 1); count = count.add(1); } } address[] memory ret = new address[](count); for (i = 0; i < ret.length; i++) { uint256 next = 0; uint256 value = candidates[0].count; for (j = 0; j < count; j++) { if (candidates[j].count > value) { next = j; value = candidates[j].count; } } ret[i] = candidates[next].addr; candidates[next] = candidates[count.sub(1)]; count = count.sub(1); } return ret; } function calculateMask(uint256 i, uint256 b) public pure returns(uint256) { if (b != 0) { return 1 << i; } return 0; } /** * View function displays the most active bounty voters over past * ARBITER_LOOKBACK_RANGE bounties to select future arbiters * * @return a sorted array of most active bounty voters and a boolean array of whether * or not they were active in 90% of bounty votes */ function getActiveArbiters() external view returns (address[], bool[]) { require(bountyGuids.length > 0, "No bounties have been placed"); uint256 count = 0; uint256 threshold = bountyGuids.length.div(10).mul(9); address[] memory ret_addr = new address[](count); bool[] memory ret_arbiter_ativity_threshold = new bool[](count); Candidate[] memory candidates = new Candidate[](ARBITER_LOOKBACK_RANGE); uint256 lastBounty = 0; if (bountyGuids.length > ARBITER_LOOKBACK_RANGE) { lastBounty = bountyGuids.length.sub(ARBITER_LOOKBACK_RANGE); threshold = lastBounty.div(10).mul(9); } for (uint256 i = bountyGuids.length.sub(1); i > lastBounty; i--) { Vote[] memory votes = votesByGuid[bountyGuids[i]]; for (uint256 j = 0; j < votes.length; j++) { bool found = false; address addr = votes[j].author; for (uint256 k = 0; k < count; k++) { if (candidates[k].addr == addr) { candidates[k].count = candidates[k].count.add(1); found = true; break; } } if (!found) { candidates[count] = Candidate(addr, 1); count = count.add(1); } } } for (i = 0; i < ret_addr.length; i++) { uint256 next = 0; uint256 value = candidates[0].count; for (j = 0; j < count; j++) { if (candidates[j].count > value) { next = j; value = candidates[j].count; } } ret_addr[i] = candidates[next].addr; if (candidates[next].count.div(10).mul(9) < threshold) { ret_arbiter_ativity_threshold[i] = false; } else { ret_arbiter_ativity_threshold[i] = true; } count = count.sub(1); candidates[next] = candidates[count]; } return (ret_addr, ret_arbiter_ativity_threshold); } } pragma solidity ^0.4.21; //import "./BountyRegistry.sol"; contract ArbiterStaking is Pausable { using SafeMath for uint256; using SafeERC20 for NectarToken; uint256 public constant MINIMUM_STAKE = 10000000 * 10 ** 18; uint256 public constant MAXIMUM_STAKE = 100000000 * 10 ** 18; uint8 public constant VOTE_RATIO_NUMERATOR = 9; uint8 public constant VOTE_RATIO_DENOMINATOR = 10; string public constant VERSION = "1.0.0"; // Deposits struct Deposit { uint256 blockNumber; uint256 value; } event NewDeposit( address indexed from, uint256 value ); event NewWithdrawal( address indexed to, uint256 value ); mapping(address => Deposit[]) public deposits; // Bounties event BountyRecorded( uint128 indexed guid, uint256 blockNumber ); event BountyVoteRecorded( address arbiter ); uint256 public numBounties; mapping(uint128 => bool) public bounties; mapping(address => uint256) public bountyResponses; mapping(uint128 => mapping(address => bool)) public bountyResponseByGuidAndAddress; uint256 public stakeDuration; NectarToken internal token; BountyRegistry internal registry; /** * Construct a new ArbiterStaking * * @param _token address of NCT token to use */ constructor(address _token, uint256 _stakeDuration) Ownable() public { token = NectarToken(_token); stakeDuration = _stakeDuration; } /** * Sets the registry value with the live BountyRegistry * @param _bountyRegistry Address of BountyRegistry contract */ function setBountyRegistry(address _bountyRegistry) public onlyOwner { registry = BountyRegistry(_bountyRegistry); } /** * Handle a deposit upon receiving approval for a token transfer * Called from NectarToken.approveAndCall * * @param _from Account depositing NCT * @param _value Amount of NCT being deposited * @param _tokenContract Address of the NCT contract * @return true if successful else false */ function receiveApproval( address _from, uint256 _value, address _tokenContract, bytes ) public whenNotPaused returns (bool) { require(msg.sender == address(token), "Must be called from the token."); return receiveApprovalInternal(_from, _value, _tokenContract, new bytes(0)); } function receiveApprovalInternal( address _from, uint256 _value, address _tokenContract, bytes ) internal whenNotPaused returns (bool) { require(registry.isArbiter(_from), "Deposit target is not an arbiter"); // Ensure we are depositing something require(_value > 0, "Zero value being deposited"); // Ensure we are called from he right token contract require(_tokenContract == address(token), "Invalid token being deposited"); // Ensure that we are not staking more than the maximum require(balanceOf(_from).add(_value) <= MAXIMUM_STAKE, "Value greater than maximum stake"); token.safeTransferFrom(_from, this, _value); deposits[_from].push(Deposit(block.number, _value)); emit NewDeposit(_from, _value); return true; } /** * Deposit NCT (requires prior approval) * * @param value The amount of NCT to deposit */ function deposit(uint256 value) public whenNotPaused { require(receiveApprovalInternal(msg.sender, value, token, new bytes(0)), "Depositing stake failed"); } /** * Retrieve the (total) current balance of staked NCT for an account * * @param addr The account whos balance to retrieve * @return The current (total) balance of the account */ function balanceOf(address addr) public view returns (uint256) { uint256 ret = 0; Deposit[] storage ds = deposits[addr]; for (uint256 i = 0; i < ds.length; i++) { ret = ret.add(ds[i].value); } return ret; } /** * Retrieve the withdrawable current balance of staked NCT for an account * * @param addr The account whos balance to retrieve * @return The current withdrawable balance of the account */ function withdrawableBalanceOf(address addr) public view returns (uint256) { uint256 ret = 0; if (block.number < stakeDuration) { return ret; } uint256 latest_block = block.number.sub(stakeDuration); Deposit[] storage ds = deposits[addr]; for (uint256 i = 0; i < ds.length; i++) { if (ds[i].blockNumber <= latest_block) { ret = ret.add(ds[i].value); } else { break; } } return ret; } /** * Withdraw staked NCT * @param value The amount of NCT to withdraw */ function withdraw(uint256 value) public whenNotPaused { require(deposits[msg.sender].length > 0, "Cannot withdraw without some deposits."); uint256 remaining = value; uint256 latest_block = block.number.sub(stakeDuration); Deposit[] storage ds = deposits[msg.sender]; require(value <= withdrawableBalanceOf(msg.sender), "Value exceeds withdrawable balance"); // Determine which deposits we will modifiy for (uint256 end = 0; end < ds.length; end++) { if (ds[end].blockNumber <= latest_block) { if (ds[end].value >= remaining) { ds[end].value = ds[end].value.sub(remaining); if (ds[end].value == 0) { end++; } remaining = 0; break; } else { remaining = remaining.sub(ds[end].value); } } else { break; } } // If we haven't hit our value by now, we don't have enough available // funds require(remaining == 0, "Value exceeds withdrawable balance"); // Delete the obsolete deposits for (uint256 i = 0; i < ds.length.sub(end); i++) { ds[i] = ds[i.add(end)]; } for (i = ds.length.sub(end); i < ds.length; i++) { delete ds[i]; } ds.length = ds.length.sub(end); // Do the transfer token.safeTransfer(msg.sender, value); emit NewWithdrawal(msg.sender, value); } /** * Is an address an eligible arbiter? * @param addr The address to validate * @return true if address is eligible else false */ function isEligible(address addr) public view returns (bool) { uint256 num; uint256 den; (num, den) = arbiterResponseRate(addr); return balanceOf(addr) >= MINIMUM_STAKE && (den < VOTE_RATIO_DENOMINATOR || num.mul(VOTE_RATIO_DENOMINATOR).div(den) >= VOTE_RATIO_NUMERATOR); } /** * Record a bounty that an arbiter has voted on * * @param arbiter The address of the arbiter * @param bountyGuid The guid of the bounty */ function recordBounty(address arbiter, uint128 bountyGuid, uint256 blockNumber) public { require(msg.sender == address(registry), "Can only be called by the BountyRegistry."); require(arbiter != address(0), "Invalid arbiter address"); require(blockNumber != 0, "Invalid block number"); // New bounty if (!bounties[bountyGuid]) { bounties[bountyGuid] = true; numBounties = numBounties.add(1); emit BountyRecorded(bountyGuid, blockNumber); } // First response to this bounty by this arbiter if (!bountyResponseByGuidAndAddress[bountyGuid][arbiter]) { bountyResponseByGuidAndAddress[bountyGuid][arbiter] = true; bountyResponses[arbiter] = bountyResponses[arbiter].add(1); } emit BountyVoteRecorded(arbiter); } /** * Determines the ratio of past bounties that the arbiter has responded to * * @param arbiter The address of the arbiter * @return number of bounties responded to, number of bounties considered */ function arbiterResponseRate(address arbiter) public view returns (uint256 num, uint256 den) { num = bountyResponses[arbiter]; den = numBounties; } }
* Generates a random number from 0 to range based on the last block hash @param seed random number for reproducing @param range end range for random number/
function randomGen(uint256 targetBlock, uint seed, uint256 range) private view returns (int256 randomNumber) { return int256(uint256(keccak256(abi.encodePacked(blockhash(targetBlock), seed))) % range); }
11,803,214
[ 1, 6653, 279, 2744, 1300, 628, 374, 358, 1048, 2511, 603, 326, 1142, 1203, 1651, 282, 5009, 2744, 1300, 364, 283, 11776, 2822, 282, 1048, 679, 1048, 364, 2744, 1300, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2744, 7642, 12, 11890, 5034, 1018, 1768, 16, 2254, 5009, 16, 2254, 5034, 1048, 13, 3238, 1476, 1135, 261, 474, 5034, 2744, 1854, 13, 288, 203, 3639, 327, 509, 5034, 12, 11890, 5034, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 2629, 2816, 12, 3299, 1768, 3631, 5009, 20349, 738, 1048, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x1e9Ed83e5CA1a7fdb20bde3C4751473975667f86/sources/contracts/StakingPool.sol
@notice A public function to sweep accidental ERC20 transfers to this contract. Tokens are sent to owner @param token The address of the ERC20 token to sweep
function sweepToken(IERC20 token) external onlyOwner { require(address(token) != address(stakingToken), "can not sweep Staking token"); uint256 balance = token.balanceOf(address(this)); token.transfer(msg.sender, balance); emit EmergencySweepWithdraw(msg.sender, token, balance); }
4,685,187
[ 1, 37, 1071, 445, 358, 17462, 25961, 287, 4232, 39, 3462, 29375, 358, 333, 6835, 18, 282, 13899, 854, 3271, 358, 3410, 225, 1147, 1021, 1758, 434, 326, 4232, 39, 3462, 1147, 358, 17462, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 17462, 1345, 12, 45, 654, 39, 3462, 1147, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 2867, 12, 2316, 13, 480, 1758, 12, 334, 6159, 1345, 3631, 315, 4169, 486, 17462, 934, 6159, 1147, 8863, 203, 3639, 2254, 5034, 11013, 273, 1147, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 1147, 18, 13866, 12, 3576, 18, 15330, 16, 11013, 1769, 203, 3639, 3626, 512, 6592, 75, 2075, 55, 25236, 1190, 9446, 12, 3576, 18, 15330, 16, 1147, 16, 11013, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; contract Checkpoints { /// @dev Official record of token balances for each account mapping(address => uint96) internal balances; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice An event thats emitted when a delegate account's vote balance changes event CheckpointBalanceChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); constructor() public {} /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint256) { return balances[account]; } /// @dev The exact copy from CVP token /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /// @dev The exact copy from CVP token /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Checkpoints::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } /** * @notice Writes checkpoint number, old and new balance to checkpoint for account address * @param account The address to write balance * @param balance New account balance */ function _writeBalance(address account, uint96 balance) internal { uint32 srcRepNum = numCheckpoints[account]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[account][srcRepNum - 1].votes : 0; uint96 srcRepNew = safe96(balance, "Checkpoints::_writeBalance: vote amount overflow"); _writeCheckpoint(account, srcRepNum, srcRepOld, srcRepNew); } /// @dev A copy from CVP token, only the event name changed function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, "Checkpoints::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit CheckpointBalanceChanged(delegatee, oldVotes, newVotes); } /// @dev The exact copy from CVP token function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /// @dev The exact copy from CVP token function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } }
@notice An event thats emitted when a delegate account's vote balance changes
event CheckpointBalanceChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
6,465,819
[ 1, 979, 871, 716, 87, 17826, 1347, 279, 7152, 2236, 1807, 12501, 11013, 3478, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 871, 25569, 13937, 5033, 12, 2867, 8808, 7152, 16, 2254, 5034, 2416, 13937, 16, 2254, 5034, 394, 13937, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.2; /** @author Egidio Casati - January the 14th 2019 * @title sum and store * @notice this smart contract calculates the sum of two addendums and store it in an array, * @notice together with the sender address who sent the transaction, who actually became the sum's owner */ contract sumandstore { /** @notice when a new sum is calculated by a new owner, an event is fired */ event newSum (uint sumID, uint sumResult, address sumOwner); /** @notice sum is a data structure modelling a single sum */ struct sum { uint add1; uint add2; uint sumResult; } /** @notice sums is an array of sums */ sum[] public sums; /** @notice every sum has its owner, i.e. the address that sent the sum transaction request */ mapping (uint => address) public sumIsOwnedBy; /** @notice owner owned sums is store and updated */ mapping (address => uint) sumsPerOwnerCount; /** @notice mapping to resolve what is the sumId owned by a particular address */ mapping (address => uint) addressOwnsSum; function _sumThem(uint _add1, uint _add2) internal { /** @notice calculates the sum of two addendums, store the result and stores its onwing address; * @notice this function is only for internal use. * @param _add1 first addendum * @param _add2 second addendum */ uint _sumResult = _add1 + _add2; uint id = sums.push(sum(_add1, _add2, _sumResult)) - 1; sumIsOwnedBy[id] = msg.sender; sumsPerOwnerCount[msg.sender]++; addressOwnsSum[msg.sender]=id; emit newSum(id, _sumResult, msg.sender); } function mySum(uint _add1, uint _add2) public { require(sumsPerOwnerCount[msg.sender] == 0); _sumThem(_add1, _add2); } function getSum (address _owner) external view returns ( uint sumId, uint add1, uint add2, uint sumResult) { uint _id = addressOwnsSum[_owner]; sum memory ownerSum = sums[_id]; return (_id, ownerSum.add1, ownerSum.add2, ownerSum.sumResult); } }
* @notice when a new sum is calculated by a new owner, an event is fired */* @notice sum is a data structure modelling a single sum */
struct sum { uint add1; uint add2; uint sumResult; }
2,537,730
[ 1, 13723, 279, 394, 2142, 353, 8894, 635, 279, 394, 3410, 16, 392, 871, 353, 15950, 342, 225, 2142, 353, 279, 501, 3695, 938, 2456, 279, 2202, 2142, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 2142, 288, 203, 3639, 2254, 527, 21, 31, 203, 3639, 2254, 527, 22, 31, 203, 3639, 2254, 2142, 1253, 31, 203, 565, 289, 203, 203, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x839F3578A952a28990e28A45b083c71f5a19b39C/sources/src/Vault.sol
@notice Emitted when liquidation premium is updated @param sender Sender of the call (msg.sender) @param liquidationPremiumD The new liquidation premium (multiplied by DENOMINATOR)
event LiquidationPremiumChanged(address indexed sender, uint32 liquidationPremiumD);
4,775,631
[ 1, 1514, 11541, 1347, 4501, 26595, 367, 23020, 5077, 353, 3526, 225, 5793, 15044, 434, 326, 745, 261, 3576, 18, 15330, 13, 225, 4501, 26595, 367, 23890, 5077, 40, 1021, 394, 4501, 26595, 367, 23020, 5077, 261, 7027, 3110, 635, 463, 1157, 1872, 706, 3575, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 511, 18988, 350, 367, 23890, 5077, 5033, 12, 2867, 8808, 5793, 16, 2254, 1578, 4501, 26595, 367, 23890, 5077, 40, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.26; library SafeMath { /** SafeMath ** * SafeMath based on the OpenZeppelin framework * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } 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; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function abs128(int128 a) internal pure returns (int128) { return a < 0 ? a * -1 : a; } } contract Accessible { /** Access Right Management ** * Copyright 2019 * Florian Weigand * Synalytix UG, Munich * florian(at)synalytix.de */ address public owner; mapping(address => bool) public accessAllowed; constructor() public { owner = msg.sender; } modifier ownership() { require(owner == msg.sender, "Accessible: Only the owner of contract can call this method"); _; } modifier accessible() { require(accessAllowed[msg.sender], "Accessible: This address has no allowence to access this method"); _; } function allowAccess(address _address) public ownership { if (_address != address(0)) { accessAllowed[_address] = true; } } function denyAccess(address _address) public ownership { if (_address != address(0)) { accessAllowed[_address] = false; } } function transferOwnership(address _address) public ownership { if (_address != address(0)) { owner = _address; } } } contract Repaying is Accessible { /** Repaying Contract ** * Idea based on https://ethereum.stackexchange.com/a/38517/55678 * Stackexchange user: medvedev1088 * --------------------- * ReentrancyGuard based on the OpenZeppelin framework * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol * --------------------- * Copyright 2019 (only modifications) * Florian Weigand * Synalytix UG, Munich * florian(at)synalytix.de */ using SafeMath for uint256; uint256 private guardCounter; bool stopRepaying = false; // the max gas price is set to 65 gwei this is the same as local server max fee setting uint256 maxGasPrice = 65000000000; // gas consomption of the repayable function uint256 additionalGasConsumption = 42492; constructor () internal { // the counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. guardCounter = 1; } modifier repayable { guardCounter += 1; uint256 localCounter = guardCounter; // repayable logic with kill swtich if(!stopRepaying) { uint256 startGas = gasleft(); _; uint256 gasUsed = startGas.sub(gasleft()); // use maxGasPrice as upper bound for the gas price uint256 gasPrice = maxGasPrice.min256(tx.gasprice); uint256 repayal = gasPrice.mul(gasUsed.add(additionalGasConsumption)); msg.sender.transfer(repayal); } else { _; } // if the counters don't match a reentrance is happening, stop the execution require(localCounter == guardCounter, "Repaying: reentrant call detected"); } function() external payable { require(msg.data.length == 0, "Repaying: You can only transfer Ether to this contract *without* any data"); } function withdraw(address _address) public ownership { require(_address != address(0) && (accessAllowed[_address] || _address == owner), "Repaying: Address is not allowed to withdraw the balance"); _address.transfer(address(this).balance); } function setMaxGasPrice(uint256 _maxGasPrice) public ownership { // define absolute max. with 125 gwei maxGasPrice = _maxGasPrice.min256(125000000000); } function getMaxGasPrice() external view returns (uint256) { return maxGasPrice; } function setAdditionalGasConsumption(uint256 _additionalGasConsumption) public ownership { // define absolute max. with 65.000 gas limit additionalGasConsumption = _additionalGasConsumption.min256(65000); } function getAdditionalGasConsumption() external view returns (uint256) { return additionalGasConsumption; } function setStopRepaying(bool _stopRepaying) public ownership { stopRepaying = _stopRepaying; } } contract TrueProfileStorage is Accessible { /** Data Storage Contract ** * Copyright 2019 * Florian Weigand * Synalytix UG, Munich * florian(at)synalytix.de */ /**** signature struct ****/ struct Signature { uint8 v; bytes32 r; bytes32 s; uint8 revocationReasonId; bool isValue; } /**** signature storage ****/ mapping(bytes32 => Signature) public signatureStorage; /**** general storage of non-struct data which might be needed for further development of main contract ****/ mapping(bytes32 => uint256) public uIntStorage; mapping(bytes32 => string) public stringStorage; mapping(bytes32 => address) public addressStorage; mapping(bytes32 => bytes) public bytesStorage; mapping(bytes32 => bool) public boolStorage; mapping(bytes32 => int256) public intStorage; /**** CRUD for Signature storage ****/ function getSignature(bytes32 _key) external view returns (uint8 v, bytes32 r, bytes32 s, uint8 revocationReasonId) { Signature memory tempSignature = signatureStorage[_key]; if (tempSignature.isValue) { return(tempSignature.v, tempSignature.r, tempSignature.s, tempSignature.revocationReasonId); } else { return(0, bytes32(0), bytes32(0), 0); } } function setSignature(bytes32 _key, uint8 _v, bytes32 _r, bytes32 _s, uint8 _revocationReasonId) external accessible { require(ecrecover(_key, _v, _r, _s) != 0x0, "TrueProfileStorage: Signature does not resolve to valid address"); Signature memory tempSignature = Signature({ v: _v, r: _r, s: _s, revocationReasonId: _revocationReasonId, isValue: true }); signatureStorage[_key] = tempSignature; } function deleteSignature(bytes32 _key) external accessible { require(signatureStorage[_key].isValue, "TrueProfileStorage: Signature to delete was not found"); Signature memory tempSignature = Signature({ v: 0, r: bytes32(0), s: bytes32(0), revocationReasonId: 0, isValue: false }); signatureStorage[_key] = tempSignature; } /**** Get Methods for additional storage ****/ function getAddress(bytes32 _key) external view returns (address) { return addressStorage[_key]; } function getUint(bytes32 _key) external view returns (uint) { return uIntStorage[_key]; } function getString(bytes32 _key) external view returns (string) { return stringStorage[_key]; } function getBytes(bytes32 _key) external view returns (bytes) { return bytesStorage[_key]; } function getBool(bytes32 _key) external view returns (bool) { return boolStorage[_key]; } function getInt(bytes32 _key) external view returns (int) { return intStorage[_key]; } /**** Set Methods for additional storage ****/ function setAddress(bytes32 _key, address _value) external accessible { addressStorage[_key] = _value; } function setUint(bytes32 _key, uint _value) external accessible { uIntStorage[_key] = _value; } function setString(bytes32 _key, string _value) external accessible { stringStorage[_key] = _value; } function setBytes(bytes32 _key, bytes _value) external accessible { bytesStorage[_key] = _value; } function setBool(bytes32 _key, bool _value) external accessible { boolStorage[_key] = _value; } function setInt(bytes32 _key, int _value) external accessible { intStorage[_key] = _value; } /**** Delete Methods for additional storage ****/ function deleteAddress(bytes32 _key) external accessible { delete addressStorage[_key]; } function deleteUint(bytes32 _key) external accessible { delete uIntStorage[_key]; } function deleteString(bytes32 _key) external accessible { delete stringStorage[_key]; } function deleteBytes(bytes32 _key) external accessible { delete bytesStorage[_key]; } function deleteBool(bytes32 _key) external accessible { delete boolStorage[_key]; } function deleteInt(bytes32 _key) external accessible { delete intStorage[_key]; } } contract TrueProfileLogic is Repaying { /** Logic Contract (updatable) ** * Copyright 2019 * Florian Weigand * Synalytix UG, Munich * florian(at)synalytix.de */ TrueProfileStorage trueProfileStorage; constructor(address _trueProfileStorage) public { trueProfileStorage = TrueProfileStorage(_trueProfileStorage); } /**** Signature logic methods ****/ // add or update TrueProof // if not present add to array // if present the old TrueProof can be replaced with a new TrueProof function addTrueProof(bytes32 _key, uint8 _v, bytes32 _r, bytes32 _s) external repayable accessible { require(accessAllowed[ecrecover(_key, _v, _r, _s)], "TrueProfileLogic: Signature creator has no access to this contract"); // the certifcate is valid, so set the revokationReasonId to 0 uint8 revokationReasonId = 0; trueProfileStorage.setSignature(_key, _v, _r, _s, revokationReasonId); } // if the TrueProof was issued by error it can be revoked // for revocation a reason id needs to be given function revokeTrueProof(bytes32 _key, uint8 _revocationReasonId) external repayable accessible { require(_revocationReasonId != 0, "TrueProfileLogic: Revocation reason needs to be unequal to 0"); uint8 v; bytes32 r; bytes32 s; uint8 oldRevocationReasonId; (v, r, s, oldRevocationReasonId) = trueProfileStorage.getSignature(_key); require(v != 0, "TrueProfileLogic: This TrueProof was already revoked"); // set the revokation reason id to the new value trueProfileStorage.setSignature(_key, v, r, s, _revocationReasonId); } function isValidTrueProof(bytes32 _key) external view returns (bool) { // needs to be not revoked AND needs to have a valid signature return this.isValidSignatureTrueProof(_key) && this.isNotRevokedTrueProof(_key); } function isValidSignatureTrueProof(bytes32 _key) external view returns (bool) { uint8 v; bytes32 r; bytes32 s; uint8 revocationReasonId; (v, r, s, revocationReasonId) = trueProfileStorage.getSignature(_key); // needs to have a valid signature return accessAllowed[ecrecover(_key, v, r, s)]; } function isNotRevokedTrueProof(bytes32 _key) external view returns (bool) { uint8 v; bytes32 r; bytes32 s; uint8 revocationReasonId; (v, r, s, revocationReasonId) = trueProfileStorage.getSignature(_key); // needs to be not revoked return revocationReasonId == 0; } function getSignature(bytes32 _key) external view returns (uint8 v, bytes32 r, bytes32 s, uint8 revocationReasonId) { return trueProfileStorage.getSignature(_key); } function getRevocationReasonId(bytes32 _key) external view returns (uint8) { uint8 v; bytes32 r; bytes32 s; uint8 revocationReasonId; (v, r, s, revocationReasonId) = trueProfileStorage.getSignature(_key); return revocationReasonId; } }
* Logic Contract (updatable) ** Copyright 2019 Florian Weigand Synalytix UG, Munich florian(at)synalytix.de/
constructor(address _trueProfileStorage) public { trueProfileStorage = TrueProfileStorage(_trueProfileStorage); }
2,570,942
[ 1, 20556, 13456, 261, 416, 3404, 429, 13, 225, 25417, 30562, 3857, 280, 2779, 1660, 360, 464, 16091, 7834, 697, 587, 43, 16, 490, 318, 1354, 1183, 280, 2779, 12, 270, 13, 11982, 7834, 697, 18, 323, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 2867, 389, 3767, 4029, 3245, 13, 1071, 288, 203, 3639, 638, 4029, 3245, 273, 1053, 4029, 3245, 24899, 3767, 4029, 3245, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x5C7795Baa167701E8fa04EdF852996Be245C5653/sources/src/boring/ERC20.sol
* @dev Sets the values for {name} and {symbol}. The default value of {decimals} is 18. To select a different value for {decimals} you should overload it. All two of these values are immutable: they can only be set once during construction./
constructor(string memory name_, string memory symbol_, uint8 decimals_, address deployer_) { _name = name_; _symbol = symbol_; _decimals = decimals_; _deployer = deployer_; }
2,974,547
[ 1, 2785, 326, 924, 364, 288, 529, 97, 471, 288, 7175, 5496, 1021, 805, 460, 434, 288, 31734, 97, 353, 6549, 18, 2974, 2027, 279, 3775, 460, 364, 288, 31734, 97, 1846, 1410, 30402, 518, 18, 4826, 2795, 434, 4259, 924, 854, 11732, 30, 2898, 848, 1338, 506, 444, 3647, 4982, 16171, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 16, 2254, 28, 15105, 67, 16, 1758, 7286, 264, 67, 13, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 3639, 389, 31734, 273, 15105, 67, 31, 203, 3639, 389, 12411, 264, 273, 7286, 264, 67, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; // solhint-disable-line // similar as shrimpfarmer, with below changes: // A. one fifth of your owls die when you sell eggs // B. you can transfer ownership of the devfee through sacrificing owls // C. the "free" 300 owls cost 0.001 eth (in line with the mining fee) // D. Inflation has been reduced by 20% (More Earnings!) // bots should have a harder time, and whales can compete for the devfee contract EthOwls{ //uint256 EGGS_PER_SHRIMP_PER_SECOND=1; uint256 public EGGS_TO_HATCH_1SHRIMP=86400; //seconds in a day uint256 public STARTING_SHRIMP=300; uint256 PSN=10000; uint256 PSNH=5000; uint256 r=6; uint256 inf=5; uint256 RINF = r / inf; // Inflation reducer bool public initialized=false; address public ceoAddress; mapping (address => uint256) public hatcheryShrimp; mapping (address => uint256) public claimedEggs; mapping (address => uint256) public lastHatch; mapping (address => address) public referrals; uint256 public marketEggs; uint256 public owlmasterReq=100000; function ShrimpFarmer() public{ ceoAddress=msg.sender; } function becomeOwlmaster() public{ require(initialized); require(hatcheryShrimp[msg.sender]>=owlmasterReq); hatcheryShrimp[msg.sender]=SafeMath.sub(hatcheryShrimp[msg.sender],owlmasterReq); owlmasterReq=SafeMath.add(owlmasterReq,100000);//+100k owls each time ceoAddress=msg.sender; } function hatchEggs(address ref) public{ require(initialized); if(referrals[msg.sender]==0 && referrals[msg.sender]!=msg.sender){ referrals[msg.sender]=ref; } uint256 eggsUsed=getMyEggs(); uint256 newShrimp=SafeMath.div(eggsUsed,EGGS_TO_HATCH_1SHRIMP); hatcheryShrimp[msg.sender]=SafeMath.add(hatcheryShrimp[msg.sender],newShrimp); claimedEggs[msg.sender]=0; lastHatch[msg.sender]=now; //send referral eggs claimedEggs[referrals[msg.sender]]=SafeMath.add(claimedEggs[referrals[msg.sender]],SafeMath.div(eggsUsed,5)); //boost market to nerf shrimp hoarding marketEggs=SafeMath.add(marketEggs,SafeMath.div(eggsUsed,10)); } function sellEggs() public{ require(initialized); uint256 hasEggs=getMyEggs(); uint256 eggValue=calculateEggSell(hasEggs); uint256 fee=devFee(eggValue); // kill one fifth of the owner's owls on egg sale hatcheryShrimp[msg.sender]=SafeMath.mul(SafeMath.div(hatcheryShrimp[msg.sender],5),4); claimedEggs[msg.sender]=0; lastHatch[msg.sender]=now; marketEggs=SafeMath.add(marketEggs,hasEggs); ceoAddress.transfer(fee); msg.sender.transfer(SafeMath.sub(eggValue,fee)); } function buyEggs() public payable{ require(initialized); uint256 eggsBought=calculateEggBuy(msg.value,SafeMath.sub(this.balance,msg.value)); eggsBought=SafeMath.sub(eggsBought,devFee(eggsBought)); ceoAddress.transfer(devFee(msg.value)); claimedEggs[msg.sender]=SafeMath.add(claimedEggs[msg.sender],eggsBought); } //magic trade balancing algorithm function calculateTrade(uint256 rt,uint256 rs, uint256 bs) public view returns(uint256){ //(PSN*bs)/(PSNH+((PSN*rs+PSNH*rt)/(RINF*rt))); return SafeMath.div(SafeMath.mul(PSN,bs),SafeMath.add(PSNH,SafeMath.div(SafeMath.add(SafeMath.mul(PSN,rs),SafeMath.mul(PSNH,rt)),SafeMath.mul(RINF,rt)))); } function calculateEggSell(uint256 eggs) public view returns(uint256){ return calculateTrade(eggs,marketEggs,this.balance); } function calculateEggBuy(uint256 eth,uint256 contractBalance) public view returns(uint256){ return calculateTrade(eth,contractBalance,marketEggs); } function calculateEggBuySimple(uint256 eth) public view returns(uint256){ return calculateEggBuy(eth,this.balance); } function devFee(uint256 amount) public view returns(uint256){ return SafeMath.div(SafeMath.mul(amount,4),100); } function seedMarket(uint256 eggs) public payable{ require(marketEggs==0); initialized=true; marketEggs=eggs; } function getFreeShrimp() public payable{ require(initialized); require(msg.value==0.001 ether); //similar to mining fee, prevents bots ceoAddress.transfer(msg.value); //owlmaster gets this entrance fee require(hatcheryShrimp[msg.sender]==0); lastHatch[msg.sender]=now; hatcheryShrimp[msg.sender]=STARTING_SHRIMP; } function getBalance() public view returns(uint256){ return this.balance; } function getMyShrimp() public view returns(uint256){ return hatcheryShrimp[msg.sender]; } function getOwlmasterReq() public view returns(uint256){ return owlmasterReq; } function getMyEggs() public view returns(uint256){ return SafeMath.add(claimedEggs[msg.sender],getEggsSinceLastHatch(msg.sender)); } function getEggsSinceLastHatch(address adr) public view returns(uint256){ uint256 secondsPassed=min(EGGS_TO_HATCH_1SHRIMP,SafeMath.sub(now,lastHatch[adr])); return SafeMath.mul(secondsPassed,hatcheryShrimp[adr]); } function min(uint256 a, uint256 b) private pure returns (uint256) { return a < b ? a : b; } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
magic trade balancing algorithm(PSN*bs)/(PSNH+((PSN*rs+PSNH*rt)/(RINF*rt)));
function calculateTrade(uint256 rt,uint256 rs, uint256 bs) public view returns(uint256){ return SafeMath.div(SafeMath.mul(PSN,bs),SafeMath.add(PSNH,SafeMath.div(SafeMath.add(SafeMath.mul(PSN,rs),SafeMath.mul(PSNH,rt)),SafeMath.mul(RINF,rt)))); }
11,732,032
[ 1, 11179, 18542, 324, 16142, 4886, 12, 5857, 50, 2038, 13176, 12, 5857, 50, 44, 15, 12443, 5857, 50, 5453, 15, 5857, 50, 44, 3797, 13176, 12, 54, 19212, 3797, 3719, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4604, 22583, 12, 11890, 5034, 8253, 16, 11890, 5034, 3597, 16, 2254, 5034, 7081, 13, 1071, 1476, 1135, 12, 11890, 5034, 15329, 203, 3639, 327, 14060, 10477, 18, 2892, 12, 9890, 10477, 18, 16411, 12, 5857, 50, 16, 2038, 3631, 9890, 10477, 18, 1289, 12, 5857, 50, 44, 16, 9890, 10477, 18, 2892, 12, 9890, 10477, 18, 1289, 12, 9890, 10477, 18, 16411, 12, 5857, 50, 16, 5453, 3631, 9890, 10477, 18, 16411, 12, 5857, 50, 44, 16, 3797, 13, 3631, 9890, 10477, 18, 16411, 12, 54, 19212, 16, 3797, 3719, 10019, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xf9208661ffE1607D96cF386B84B2BE621620097C/sources/FreeShop.sol
override to always return 1 token per 'purchase'
function calculateTokens() internal returns(uint) {
9,314,585
[ 1, 10601, 358, 3712, 327, 404, 1147, 1534, 296, 12688, 12104, 11, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4604, 5157, 1435, 2713, 1135, 12, 11890, 13, 288, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x999512dC124371E6B9ff43CE8D1AF83252F0C851/sources/lib/joe-v2/src/libraries/math/SafeCast.sol
* @dev Returns x on uint200 and check that it does not overflow @param x The value as an uint256 @return y The value as an uint200/
function safe200(uint256 x) internal pure returns (uint200 y) { if ((y = uint200(x)) != x) revert SafeCast__Exceeds200Bits(); }
1,894,140
[ 1, 1356, 619, 603, 2254, 6976, 471, 866, 716, 518, 1552, 486, 9391, 225, 619, 1021, 460, 487, 392, 2254, 5034, 327, 677, 1021, 460, 487, 392, 2254, 6976, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4183, 6976, 12, 11890, 5034, 619, 13, 2713, 16618, 1135, 261, 11890, 6976, 677, 13, 288, 203, 3639, 309, 14015, 93, 273, 2254, 6976, 12, 92, 3719, 480, 619, 13, 15226, 14060, 9735, 972, 424, 5288, 87, 6976, 6495, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IOwnable { function policy() external view returns (address); function renounceManagement() external; function pushManagement( address newOwner_ ) external; function pullManagement() external; } contract Ownable is IOwnable { address internal _owner; address internal _newOwner; event OwnershipPushed(address indexed previousOwner, address indexed newOwner); event OwnershipPulled(address indexed previousOwner, address indexed newOwner); constructor () { _owner = msg.sender; emit OwnershipPushed( address(0), _owner ); } function policy() public view override returns (address) { return _owner; } modifier onlyPolicy() { require( _owner == msg.sender, "Ownable: caller is not the owner" ); _; } function renounceManagement() public virtual override onlyPolicy() { emit OwnershipPushed( _owner, address(0) ); _owner = address(0); } function pushManagement( address newOwner_ ) public virtual override onlyPolicy() { require( newOwner_ != address(0), "Ownable: new owner is the zero address"); emit OwnershipPushed( _owner, newOwner_ ); _newOwner = newOwner_; } function pullManagement() public virtual override { require( msg.sender == _newOwner, "Ownable: must be new owner to pull"); emit OwnershipPulled( _owner, _newOwner ); _owner = _newOwner; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = add( div( a, 2), 1 ); while (b < c) { c = b; b = div( add( div( a, b ), b), 2 ); } } else if (a != 0) { c = 1; } } } library Address { function isContract(address account) internal view returns (bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } function addressToString(address _address) internal pure returns(string memory) { bytes32 _bytes = bytes32(uint256(_address)); bytes memory HEX = "0123456789abcdef"; bytes memory _addr = new bytes(42); _addr[0] = '0'; _addr[1] = 'x'; for(uint256 i = 0; i < 20; i++) { _addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)]; _addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)]; } return string(_addr); } } interface IERC20 { function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } abstract contract ERC20 is IERC20 { using SafeMath for uint256; // TODO comment actual hash value. bytes32 constant private ERC20TOKEN_ERC1820_INTERFACE_ID = keccak256( "ERC20Token" ); mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 internal _totalSupply; string internal _name; string internal _symbol; uint8 internal _decimals; constructor (string memory name_, string memory symbol_, uint8 decimals_) { _name = name_; _symbol = symbol_; _decimals = decimals_; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view override returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account_, uint256 ammount_) internal virtual { require(account_ != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address( this ), account_, ammount_); _totalSupply = _totalSupply.add(ammount_); _balances[account_] = _balances[account_].add(ammount_); emit Transfer(address( this ), account_, ammount_); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer( address from_, address to_, uint256 amount_ ) internal virtual { } } interface IERC2612Permit { function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function nonces(address owner) external view returns (uint256); } library Counters { using SafeMath for uint256; struct Counter { uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } abstract contract ERC20Permit is ERC20, IERC2612Permit { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; bytes32 public DOMAIN_SEPARATOR; constructor() { uint256 chainID; assembly { chainID := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name())), keccak256(bytes("1")), // Version chainID, address(this) ) ); } function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "Permit: expired deadline"); bytes32 hashStruct = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline)); bytes32 _hash = keccak256(abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct)); address signer = ecrecover(_hash, v, r, s); require(signer != address(0) && signer == owner, "ZeroSwapPermit: Invalid signature"); _nonces[owner].increment(); _approve(owner, spender, amount); } function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library FullMath { function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; require(h < d, 'FullMath::mulDiv: overflow'); return fullDiv(l, h, d); } } library FixedPoint { struct uq112x112 { uint224 _x; } struct uq144x112 { uint256 _x; } uint8 private constant RESOLUTION = 112; uint256 private constant Q112 = 0x10000000000000000000000000000; uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } function decode112with18(uq112x112 memory self) internal pure returns (uint) { return uint(self._x) / 5192296858534827; } function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } } interface ITreasury { function deposit( uint _amount, address _token, uint _profit ) external returns ( bool ); function valueOf( address _token, uint _amount ) external view returns ( uint value_ ); } interface IBondCalculator { function valuation( address _LP, uint _amount ) external view returns ( uint ); function markdown( address _LP ) external view returns ( uint ); } interface IStaking { function stake( uint _amount, address _recipient ) external returns ( bool ); } interface IStakingHelper { function stake( uint _amount, address _recipient ) external; } contract ManifestBondDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMath for uint; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInOHM ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInOHM, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable MNFST; // token given as payment for bond address public immutable principle; // token used to create bond address public immutable treasury; // mints MNFST when receives principle address public immutable DAO; // receives profit share from bond bool public immutable isLiquidityBond; // LP and Reserve bonds are treated slightly different address public immutable bondCalculator; // calculates value of LP tokens address public staking; // to auto-stake payout address public stakingHelper; // to stake and claim if no staking warmup bool public useHelper; Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint controlVariable; // scaling variable for price uint vestingTerm; // in blocks uint minimumPrice; // vs principle value uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint fee; // as % of bond payout, in hundreths. ( 500 = 5% = 0.05 for every 1 paid) uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint payout; // MNFST remaining to be paid uint vesting; // Blocks left to vest uint lastBlock; // Last interaction uint pricePaid; // In OHM per 1, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint buffer; // minimum length (in blocks) between adjustments uint lastBlock; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _MNFST, address _principle, address _treasury, address _DAO, address _bondCalculator ) { require( _MNFST != address(0) ); MNFST = _MNFST; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; // bondCalculator should be address(0) if not LP bond bondCalculator = _bondCalculator; isLiquidityBond = ( _bondCalculator != address(0) ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _fee uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms( uint _controlVariable, uint _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _fee, uint _maxDebt, uint _initialDebt ) external onlyPolicy() { require( terms.controlVariable == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, fee: _fee, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = block.number; } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, FEE, DEBT } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyPolicy() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 10000, "Vesting must be longer than 36 hours" ); terms.vestingTerm = _input; } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.FEE ) { // 2 require( _input <= 10000, "DAO fee cannot exceed payout" ); terms.fee = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 3 terms.maxDebt = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint _buffer ) external onlyPolicy() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastBlock: block.number }); } /** * @notice set contract for auto stake * @param _staking address * @param _helper bool */ function setStaking( address _staking, bool _helper ) external onlyPolicy() { require( _staking != address(0) ); if ( _helper ) { useHelper = true; stakingHelper = _staking; } else { useHelper = false; staking = _staking; } } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor ) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); uint priceInOHM = bondPriceInOHM(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOf( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 MNFST ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage // profits are calculated uint fee = payout.mul( terms.fee ).div( 10000 ); uint profit = value.sub( payout ).sub( fee ); /** principle is transferred in approved and deposited into the treasury, returning (_amount - profit) MNFST */ IERC20( principle ).safeTransferFrom( msg.sender, address(this), _amount ); IERC20( principle ).approve( address( treasury ), _amount ); ITreasury( treasury ).deposit( _amount, principle, profit ); if ( fee != 0 ) { // fee is transferred to dao IERC20( MNFST ).safeTransfer( DAO, fee ); } // total debt is increased totalDebt = totalDebt.add( value ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastBlock: block.number, pricePaid: priceInOHM }); // indexed events are emitted emit BondCreated( _amount, payout, block.number.add( terms.vestingTerm ), priceInOHM ); emit BondPriceChanged( bondPriceInOHM(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data return stakeOrSend( _recipient, _stake, info.payout ); // pay user everything due } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub( block.number.sub( info.lastBlock ) ), lastBlock: block.number, pricePaid: info.pricePaid }); emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout ); return stakeOrSend( _recipient, _stake, payout ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to stake payout automatically * @param _stake bool * @param _amount uint * @return uint */ function stakeOrSend( address _recipient, bool _stake, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake IERC20( MNFST ).transfer( _recipient, _amount ); // send payout } else { // if user wants to stake if ( useHelper ) { // use if staking warmup is 0 IERC20( MNFST ).approve( stakingHelper, _amount ); IStakingHelper( stakingHelper ).stake( _amount, _recipient ); } else { IERC20( MNFST ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient ); } } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint blockCanAdjust = adjustment.lastBlock.add( adjustment.buffer ); if( adjustment.rate != 0 && block.number >= blockCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target ) { adjustment.rate = 0; } } adjustment.lastBlock = block.number; emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = block.number; } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( MNFST ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e16 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice converts bond price to OHM for 1000 value * @return price_ uint */ function bondPriceInOHM() public view returns ( uint price_ ) { if( isLiquidityBond ) { price_ = bondPrice().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 100 ).div(1000); } else { price_ = bondPrice().mul( 10 ** IERC20( principle ).decimals() ).div( 100 ).div( 1000 ); } } /** * @notice calculate current ratio of debt to MNFST supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( MNFST ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms for reserve or liquidity bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { if ( isLiquidityBond ) { return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 ); } else { return debtRatio(); } } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint blocksSinceLast = block.number.sub( lastDecay ); decay_ = totalDebt.mul( blocksSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint blocksSinceLast = block.number.sub( bond.lastBlock ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = blocksSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of MNFST available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or MNFST) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != MNFST ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } }
Stored in bond info
uint priceInOHM = bondPriceInOHM();
475,070
[ 1, 18005, 316, 8427, 1123, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 6205, 382, 51, 44, 49, 273, 8427, 5147, 382, 51, 44, 49, 5621, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. **/ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. **/ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). **/ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. **/ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". **/ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @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 { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic interface * @dev Basic ERC20 interface **/ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 **/ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. **/ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence **/ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. **/ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. **/ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred **/ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. **/ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. **/ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. **/ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. **/ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Configurable * @dev Configurable varriables of the contract **/ contract Configurable { uint256 public constant cap = 35000*10**18; uint256 public constant basePrice = 3*10**18; // tokens per 1 ether uint256 public tokensSold = 0; uint256 public constant tokenReserve = 35000*10**18; uint256 public remainingTokens = 0; } /** * @title CrowdsaleToken * @dev Contract to preform crowd sale with token **/ contract CrowdsaleToken is StandardToken, Configurable, Ownable { /** * @dev enum of current crowd sale state **/ enum Stages { none, icoStart, icoEnd } Stages currentStage; /** * @dev constructor of CrowdsaleToken **/ constructor() public { currentStage = Stages.none; balances[owner] = balances[owner].add(tokenReserve); totalSupply_ = totalSupply_.add(tokenReserve); remainingTokens = cap; emit Transfer(address(this), owner, tokenReserve); } /** * @dev fallback function to send ether to for Crowd sale **/ function () public payable { require(currentStage == Stages.icoStart); require(msg.value > 0); require(remainingTokens > 0); uint256 weiAmount = msg.value; // Calculate tokens to sell uint256 tokens = weiAmount.mul(basePrice).div(1 ether); uint256 returnWei = 0; if(tokensSold.add(tokens) > cap){ uint256 newTokens = cap.sub(tokensSold); uint256 newWei = newTokens.div(basePrice).mul(1 ether); returnWei = weiAmount.sub(newWei); weiAmount = newWei; tokens = newTokens; } tokensSold = tokensSold.add(tokens); // Increment raised amount remainingTokens = cap.sub(tokensSold); if(returnWei > 0){ msg.sender.transfer(returnWei); emit Transfer(address(this), msg.sender, returnWei); } balances[msg.sender] = balances[msg.sender].add(tokens); emit Transfer(address(this), msg.sender, tokens); totalSupply_ = totalSupply_.add(tokens); owner.transfer(weiAmount);// Send money to owner } /** * @dev startIco starts the public ICO **/ function startIco() public onlyOwner { require(currentStage != Stages.icoEnd); currentStage = Stages.icoStart; } /** * @dev endIco closes down the ICO **/ function endIco() internal { currentStage = Stages.icoEnd; // Transfer any remaining tokens if(remainingTokens > 0) balances[owner] = balances[owner].add(remainingTokens); // transfer any remaining ETH balance in the contract to the owner owner.transfer(address(this).balance); } /** * @dev finalizeIco closes down the ICO and sets needed varriables **/ function finalizeIco() public onlyOwner { require(currentStage != Stages.icoEnd); endIco(); } } /** * @title BlackcutFinanceToken * @dev Contract to create the BlackcutFinance Token **/ contract BlackcutFinance is CrowdsaleToken { string public constant name = "Blackcut Finance"; string public constant symbol = "BCFI"; uint32 public constant decimals = 18; }
* @title BlackcutFinanceToken @dev Contract to create the BlackcutFinance Token/
contract BlackcutFinance is CrowdsaleToken { string public constant name = "Blackcut Finance"; string public constant symbol = "BCFI"; uint32 public constant decimals = 18; }
6,503,914
[ 1, 13155, 5150, 6187, 1359, 1345, 225, 13456, 358, 752, 326, 22467, 5150, 6187, 1359, 3155, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 22467, 5150, 6187, 1359, 353, 385, 492, 2377, 5349, 1345, 288, 203, 565, 533, 1071, 5381, 508, 273, 315, 13155, 5150, 9458, 1359, 14432, 203, 565, 533, 1071, 5381, 3273, 273, 315, 16283, 1653, 14432, 203, 565, 2254, 1578, 1071, 5381, 15105, 273, 6549, 31, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x614AE4e43498773A9b31B0Ca88d3568975562DB0/sources/gitarg.sol
https:eips.ethereum.org/EIPS/eip-20#name function definition can be changed to pure - not in standard
function name() public view returns (string memory) { return "gitarg"; }
17,085,872
[ 1, 4528, 30, 73, 7146, 18, 546, 822, 379, 18, 3341, 19, 41, 2579, 55, 19, 73, 625, 17, 3462, 529, 445, 2379, 848, 506, 3550, 358, 16618, 300, 486, 316, 4529, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 508, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 565, 327, 315, 6845, 3175, 14432, 21281, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1287/0xA535E7ECA76BF1dbdbED9d8745b9158632Dca0d7/sources/project_/contracts/voting/VotingHubContract.sol
@notice @dev This function removes address from voting contract array @param index index of the contract to remove from the list
function removeVotingContract(uint256 index) public _ownerOnly { require( index < VOTING_CONTRACTS_ADDRESS.length, "INVALID: INCORRECT_INDEX" ); VOTING_CONTRACTS_ADDRESS[index] = VOTING_CONTRACTS_ADDRESS[ VOTING_CONTRACTS_ADDRESS.length - 1 ]; VOTING_CONTRACTS_ADDRESS.pop(); }
7,096,890
[ 1, 2503, 445, 7157, 1758, 628, 331, 17128, 6835, 526, 225, 770, 770, 434, 326, 6835, 358, 1206, 628, 326, 666, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 58, 17128, 8924, 12, 11890, 5034, 770, 13, 1071, 389, 8443, 3386, 288, 203, 3639, 2583, 12, 203, 5411, 770, 411, 776, 1974, 1360, 67, 6067, 2849, 1268, 55, 67, 15140, 18, 2469, 16, 203, 5411, 315, 9347, 30, 2120, 9428, 4512, 67, 9199, 6, 203, 3639, 11272, 203, 3639, 776, 1974, 1360, 67, 6067, 2849, 1268, 55, 67, 15140, 63, 1615, 65, 273, 776, 1974, 1360, 67, 6067, 2849, 1268, 55, 67, 15140, 63, 203, 5411, 776, 1974, 1360, 67, 6067, 2849, 1268, 55, 67, 15140, 18, 2469, 300, 404, 203, 3639, 308, 31, 203, 3639, 776, 1974, 1360, 67, 6067, 2849, 1268, 55, 67, 15140, 18, 5120, 5621, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0xb0b2dD90491Bc9091604793321b98aC863dE8C0C/sources/project_/contracts/CollectionFactory.sol
* @notice Deatils for a collection. @param name The name of the collection. @param symbol The symbol of a collection. @param URI The collection uri. @param contractAddress the address of the deployed collection. @param owner The collection owner. @param description The collection description/
struct CollectionMeta { string name; string symbol; string URI; address contractAddress; address owner; string description; } mapping(address => uint256) public addressToCollectionId; uint256 public collectionId; event CollectionURISet(uint256 collectionId, string uri); event CollectionNameSet(uint256 collectionId, string name); event CollectionDescriptionSet(uint256 collectionId, string Description); event CollectionSymbolSet(uint256 collectionId, string Symbol); event CollectionCreated(uint256 collectionId, address CollectionAddress); event CollectionRoyaltiesSet( uint256 indexed collectionId, LibShare.Share[] royalties ); address collectionMethodAddress;
3,282,860
[ 1, 758, 270, 14573, 364, 279, 1849, 18, 225, 508, 1021, 508, 434, 326, 1849, 18, 225, 3273, 1021, 3273, 434, 279, 1849, 18, 225, 3699, 1021, 1849, 2003, 18, 225, 6835, 1887, 326, 1758, 434, 326, 19357, 1849, 18, 225, 3410, 1021, 1849, 3410, 18, 225, 2477, 1021, 1849, 2477, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 2200, 2781, 288, 203, 3639, 533, 508, 31, 203, 3639, 533, 3273, 31, 203, 3639, 533, 3699, 31, 203, 3639, 1758, 6835, 1887, 31, 203, 3639, 1758, 3410, 31, 203, 3639, 533, 2477, 31, 203, 565, 289, 203, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 1758, 774, 2532, 548, 31, 203, 203, 203, 565, 2254, 5034, 1071, 1849, 548, 31, 203, 203, 565, 871, 2200, 3098, 694, 12, 11890, 5034, 1849, 548, 16, 533, 2003, 1769, 203, 203, 565, 871, 2200, 461, 694, 12, 11890, 5034, 1849, 548, 16, 533, 508, 1769, 203, 203, 565, 871, 2200, 3291, 694, 12, 11890, 5034, 1849, 548, 16, 533, 6507, 1769, 203, 203, 565, 871, 2200, 5335, 694, 12, 11890, 5034, 1849, 548, 16, 533, 8565, 1769, 203, 203, 565, 871, 2200, 6119, 12, 11890, 5034, 1849, 548, 16, 1758, 2200, 1887, 1769, 203, 203, 565, 871, 2200, 54, 13372, 2390, 606, 694, 12, 203, 3639, 2254, 5034, 8808, 1849, 548, 16, 203, 3639, 10560, 9535, 18, 9535, 8526, 721, 93, 2390, 606, 203, 565, 11272, 203, 203, 565, 1758, 1849, 1305, 1887, 31, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) public pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) public pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) public pure returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) public pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @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) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * The Bank Token (BANK) has a fixed supply and restricts the ability * to transfer tokens until the owner has called the enableTransfer() * function. * * The owner can associate the token with a token sale contract. In that * case, the token balance is moved to the token sale contract, which * in turn can transfer its tokens to contributors to the sale. */ /** * The Bank Token (BANK) has a fixed supply and restricts the ability * to transfer tokens until the owner has called the enableTransfer() * function. * * The owner can associate the token with a token sale contract. In that * case, the token balance is moved to the token sale contract, which * in turn can transfer its tokens to contributors to the sale. */ contract BankToken is StandardToken, Ownable { using SafeMath for uint256; // Constants string public constant name = "Bank Token"; string public constant symbol = "BANK"; uint8 public constant decimals = 0; uint256 public constant INITIAL_SUPPLY = 10000000000; uint256 public constant CROWDSALE_ALLOWANCE = 3000000000; uint256 public constant ADMIN_ALLOWANCE = 7000000000; // Properties uint256 public crowdSaleAllowance; // the number of tokens available for crowdsales uint256 public adminAllowance; // the number of tokens available for the administrator address public crowdSaleAddr; // the address of crowdsale currently selling this token address public adminAddr; // the address of admin account holding the token bool public transferEnabled = false; // indicates if transferring tokens is enabled or not // Events event LogTransfer(address indexed beneficiary, uint amount); // Modifiers modifier onlyWhenTransferEnabled() { if (!transferEnabled) { require(msg.sender == adminAddr || msg.sender == crowdSaleAddr); } _; } /** * The listed addresses are not valid recipients of tokens. * * 0x0 - the zero address is not valid * this - the contract itself should not receive tokens * owner - the owner has all the initial tokens, but cannot receive any back * adminAddr - the admin has an allowance of tokens to transfer, but does not receive any * crowdSaleAddr - the crowdsale has an allowance of tokens to transfer, but does not receive any */ modifier validDestination(address _to) { require(_to != address(0x0)); require(_to != address(this)); require(_to != owner); require(_to != address(adminAddr)); require(_to != address(crowdSaleAddr)); _; } /** * Constructor - instantiates token supply and allocates balanace of * to the owner (msg.sender). */ constructor (address admin) public { // the owner is a custodian of tokens that can give an allowance of tokens for crowdsales // or to the admin, but cannot itself transfer tokens; hence, this requirement require(admin != address(0x0)); totalSupply = INITIAL_SUPPLY; crowdSaleAllowance = CROWDSALE_ALLOWANCE; adminAllowance = ADMIN_ALLOWANCE; // mint all tokens balances[msg.sender] = totalSupply; emit LogTransfer(msg.sender, totalSupply); adminAddr = admin; approve(adminAddr, adminAllowance); } /** * Associates this token with a current crowdsale, giving the crowdsale * an allowance of tokens from the crowdsale supply. This gives the * crowdsale the ability to call transferFrom to transfer tokens to * whomever has purchased them. * * Note that if _amountForSale is 0, then it is assumed that the full * remaining crowdsale supply is made available to the crowdsale. * * @param _crowdSaleAddr The address of a crowdsale contract that will sell this token * @param _amountForSale The supply of tokens provided to the crowdsale */ function setCrowdsale(address _crowdSaleAddr, uint256 _amountForSale) public onlyOwner { require(!transferEnabled); require(_amountForSale <= crowdSaleAllowance); // if 0, then full available crowdsale supply is assumed uint amount = (_amountForSale == 0) ? crowdSaleAllowance : _amountForSale; // Clear allowance of old values, set allowance using new ones approve(crowdSaleAddr, 0); approve(_crowdSaleAddr, amount); crowdSaleAddr = _crowdSaleAddr; } /** * Overrides ERC20 transfer function with modifier that prevents * ability to transfer tokens until after transfers have been enabled. */ function transfer(address _to, uint256 _value) public onlyWhenTransferEnabled validDestination(_to) returns (bool) { //require(msg.sender==owner,'only owner can send funds'); emit LogTransfer(_to, _value); return super.transfer(_to, _value); //return bool; } /** * Overrides ERC20 transferFrom function with modifier that prevents the * ability to transfer tokens until after transfers have been enabled. * function transferFrom(address _from, address _to, uint256 _value) public onlyWhenTransferEnabled validDestination(_to) returns (bool) { */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { bool result = super.transferFrom(_from, _to, _value); if (result) { if (msg.sender == crowdSaleAddr) crowdSaleAllowance = crowdSaleAllowance.sub(_value); if (msg.sender == adminAddr) adminAllowance = adminAllowance.sub(_value); } return true; } function enableTransfer() public onlyOwner { transferEnabled = true; } function crowdSaleAllowance() public view returns (uint) { return crowdSaleAllowance; } }
* @title Standard ERC20 token @dev Implementation of the basic standard token./
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } else { }
6,460,925
[ 1, 8336, 4232, 39, 3462, 1147, 225, 25379, 434, 326, 5337, 4529, 1147, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 8263, 1345, 353, 4232, 39, 3462, 16, 7651, 1345, 288, 203, 203, 225, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 2935, 31, 203, 203, 225, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 13, 288, 203, 565, 2583, 24899, 869, 480, 1758, 12, 20, 10019, 203, 203, 565, 2254, 5034, 389, 5965, 1359, 273, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 15533, 203, 203, 203, 565, 324, 26488, 63, 67, 2080, 65, 273, 324, 26488, 63, 67, 2080, 8009, 1717, 24899, 1132, 1769, 203, 565, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 869, 8009, 1289, 24899, 1132, 1769, 203, 565, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 65, 273, 389, 5965, 1359, 18, 1717, 24899, 1132, 1769, 203, 565, 3626, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 225, 445, 6617, 537, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 13, 288, 203, 565, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 389, 1132, 31, 203, 565, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 389, 87, 1302, 264, 16, 389, 1132, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 225, 445, 1699, 1359, 12, 2867, 389, 8443, 16, 1758, 389, 87, 1302, 264, 13, 1071, 5381, 1135, 261, 11890, 5034, 4463, 2 ]
./full_match/56/0xB8b6935C5D47559d51F3512031568358cA91aE29/sources/project_/contracts/ERC721Staking.sol
* @notice Function used to calculate the rewards for a user. @return _rewards - The rewards for the user./ return ( ((((block.timestamp - staker.timeOfLastUpdate) * staker.stakedTokenIds.length)) * rewardsPerHour) / SECONDS_IN_HOUR );
function calculateRewards(address _staker) internal view returns (uint256 _rewards) { Staker memory staker = stakers[_staker]; uint256 _totalnft = nftCollection.balanceOf(address(this)); uint256 _myporc = 1 / (_totalnft / staker.stakedTokenIds.length); return ( ((((block.timestamp - staker.timeOfLastUpdate) * _myporc)) * rewardsPerHour) / SECONDS_IN_HOUR ); }
3,248,521
[ 1, 2083, 1399, 358, 4604, 326, 283, 6397, 364, 279, 729, 18, 327, 389, 266, 6397, 300, 1021, 283, 6397, 364, 326, 729, 18, 19, 327, 261, 377, 261, 12443, 12, 2629, 18, 5508, 300, 384, 6388, 18, 957, 951, 3024, 1891, 13, 225, 384, 6388, 18, 334, 9477, 1345, 2673, 18, 2469, 3719, 225, 283, 6397, 2173, 13433, 13, 540, 342, 17209, 67, 706, 67, 21372, 11272, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4604, 17631, 14727, 12, 2867, 389, 334, 6388, 13, 2713, 1476, 1135, 261, 11890, 5034, 389, 266, 6397, 13, 288, 203, 3639, 934, 6388, 3778, 384, 6388, 273, 384, 581, 414, 63, 67, 334, 6388, 15533, 203, 3639, 2254, 5034, 389, 4963, 82, 1222, 273, 290, 1222, 2532, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 5034, 389, 81, 879, 280, 71, 273, 404, 342, 261, 67, 4963, 82, 1222, 342, 384, 6388, 18, 334, 9477, 1345, 2673, 18, 2469, 1769, 203, 203, 3639, 327, 261, 203, 5411, 261, 12443, 12, 2629, 18, 5508, 300, 384, 6388, 18, 957, 951, 3024, 1891, 13, 380, 389, 81, 879, 280, 71, 3719, 380, 283, 6397, 2173, 13433, 13, 203, 7734, 342, 17209, 67, 706, 67, 21372, 203, 3639, 11272, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0x278F790FC5f1A7a438bca43253e02d40f7835e1e/sources/MakaContract.sol
Send the reward to the caller
function claimBNB(address user, uint256 bnbAmount) private returns (bool) { if (bnbAmount == 0) { return true; } if (_sendWeiGasLimit > 0) { if (!sent) { return false; } if (!sent) { return false; } } _bnbRewardClaimed[user] += bnbAmount; _totalBNBClaimed += bnbAmount; return true; }
5,033,333
[ 1, 3826, 326, 19890, 358, 326, 4894, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 7516, 15388, 38, 12, 2867, 729, 16, 2254, 5034, 324, 6423, 6275, 13, 3238, 1135, 261, 6430, 13, 288, 203, 202, 202, 430, 261, 70, 6423, 6275, 422, 374, 13, 288, 203, 1082, 202, 2463, 638, 31, 203, 202, 202, 97, 203, 203, 202, 202, 430, 261, 67, 4661, 3218, 77, 27998, 3039, 405, 374, 13, 288, 203, 1082, 202, 430, 16051, 7569, 13, 288, 203, 9506, 202, 2463, 629, 31, 203, 1082, 202, 97, 203, 1082, 202, 430, 16051, 7569, 13, 288, 203, 9506, 202, 2463, 629, 31, 203, 1082, 202, 97, 203, 202, 202, 97, 203, 203, 202, 203, 202, 202, 67, 70, 6423, 17631, 1060, 9762, 329, 63, 1355, 65, 1011, 324, 6423, 6275, 31, 203, 202, 202, 67, 4963, 15388, 38, 9762, 329, 1011, 324, 6423, 6275, 31, 203, 202, 202, 2463, 638, 31, 203, 202, 97, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.13; interface FundInterface { // EVENTS event PortfolioContent(address[] assets, uint[] holdings, uint[] prices); event RequestUpdated(uint id); event Redeemed(address indexed ofParticipant, uint atTimestamp, uint shareQuantity); event FeesConverted(uint atTimestamp, uint shareQuantityConverted, uint unclaimed); event CalculationUpdate(uint atTimestamp, uint managementFee, uint performanceFee, uint nav, uint sharePrice, uint totalSupply); event ErrorMessage(string errorMessage); // EXTERNAL METHODS // Compliance by Investor function requestInvestment(uint giveQuantity, uint shareQuantity, address investmentAsset) external; function executeRequest(uint requestId) external; function cancelRequest(uint requestId) external; function redeemAllOwnedAssets(uint shareQuantity) external returns (bool); // Administration by Manager function enableInvestment(address[] ofAssets) external; function disableInvestment(address[] ofAssets) external; function shutDown() external; // PUBLIC METHODS function emergencyRedeem(uint shareQuantity, address[] requestedAssets) public returns (bool success); function calcSharePriceAndAllocateFees() public returns (uint); // PUBLIC VIEW METHODS // Get general information function getModules() view returns (address, address, address); function getLastRequestId() view returns (uint); function getManager() view returns (address); // Get accounting information function performCalculations() view returns (uint, uint, uint, uint, uint, uint, uint); function calcSharePrice() view returns (uint); } interface AssetInterface { /* * Implements ERC 20 standard. * https://github.com/ethereum/EIPs/blob/f90864a3d2b2b45c4decf95efd26b3f0c276051a/EIPS/eip-20-token-standard.md * https://github.com/ethereum/EIPs/issues/20 * * Added support for the ERC 223 "tokenFallback" method in a "transfer" function with a payload. * https://github.com/ethereum/EIPs/issues/223 */ // Events event Approval(address indexed _owner, address indexed _spender, uint _value); // There is no ERC223 compatible Transfer event, with `_data` included. //ERC 223 // PUBLIC METHODS function transfer(address _to, uint _value, bytes _data) public returns (bool success); // ERC 20 // PUBLIC METHODS function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); // PUBLIC VIEW METHODS function balanceOf(address _owner) view public returns (uint balance); function allowance(address _owner, address _spender) public view returns (uint remaining); } contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } interface SharesInterface { event Created(address indexed ofParticipant, uint atTimestamp, uint shareQuantity); event Annihilated(address indexed ofParticipant, uint atTimestamp, uint shareQuantity); // VIEW METHODS function getName() view returns (bytes32); function getSymbol() view returns (bytes8); function getDecimals() view returns (uint); function getCreationTime() view returns (uint); function toSmallestShareUnit(uint quantity) view returns (uint); function toWholeShareUnit(uint quantity) view returns (uint); } interface CompetitionInterface { // EVENTS event Register(uint withId, address fund, address manager); event ClaimReward(address registrant, address fund, uint shares); // PRE, POST, INVARIANT CONDITIONS function termsAndConditionsAreSigned(address byManager, uint8 v, bytes32 r, bytes32 s) view returns (bool); function isWhitelisted(address x) view returns (bool); function isCompetitionActive() view returns (bool); // CONSTANT METHODS function getMelonAsset() view returns (address); function getRegistrantId(address x) view returns (uint); function getRegistrantFund(address x) view returns (address); function getCompetitionStatusOfRegistrants() view returns (address[], address[], bool[]); function getTimeTillEnd() view returns (uint); function getEtherValue(uint amount) view returns (uint); function calculatePayout(uint payin) view returns (uint); // PUBLIC METHODS function registerForCompetition(address fund, uint8 v, bytes32 r, bytes32 s) payable; function batchAddToWhitelist(uint maxBuyinQuantity, address[] whitelistants); function withdrawMln(address to, uint amount); function claimReward(); } interface ComplianceInterface { // PUBLIC VIEW METHODS /// @notice Checks whether investment is permitted for a participant /// @param ofParticipant Address requesting to invest in a Melon fund /// @param giveQuantity Quantity of Melon token times 10 ** 18 offered to receive shareQuantity /// @param shareQuantity Quantity of shares times 10 ** 18 requested to be received /// @return Whether identity is eligible to invest in a Melon fund. function isInvestmentPermitted( address ofParticipant, uint256 giveQuantity, uint256 shareQuantity ) view returns (bool); /// @notice Checks whether redemption is permitted for a participant /// @param ofParticipant Address requesting to redeem from a Melon fund /// @param shareQuantity Quantity of shares times 10 ** 18 offered to redeem /// @param receiveQuantity Quantity of Melon token times 10 ** 18 requested to receive for shareQuantity /// @return Whether identity is eligible to redeem from a Melon fund. function isRedemptionPermitted( address ofParticipant, uint256 shareQuantity, uint256 receiveQuantity ) view returns (bool); } contract DBC { // MODIFIERS modifier pre_cond(bool condition) { require(condition); _; } modifier post_cond(bool condition) { _; assert(condition); } modifier invariant(bool condition) { require(condition); _; assert(condition); } } contract Owned is DBC { // FIELDS address public owner; // NON-CONSTANT METHODS function Owned() { owner = msg.sender; } function changeOwner(address ofNewOwner) pre_cond(isOwner()) { owner = ofNewOwner; } // PRE, POST, INVARIANT CONDITIONS function isOwner() internal returns (bool) { return msg.sender == owner; } } contract CompetitionCompliance is ComplianceInterface, DBC, Owned { address public competitionAddress; // CONSTRUCTOR /// @dev Constructor /// @param ofCompetition Address of the competition contract function CompetitionCompliance(address ofCompetition) public { competitionAddress = ofCompetition; } // PUBLIC VIEW METHODS /// @notice Checks whether investment is permitted for a participant /// @param ofParticipant Address requesting to invest in a Melon fund /// @param giveQuantity Quantity of Melon token times 10 ** 18 offered to receive shareQuantity /// @param shareQuantity Quantity of shares times 10 ** 18 requested to be received /// @return Whether identity is eligible to invest in a Melon fund. function isInvestmentPermitted( address ofParticipant, uint256 giveQuantity, uint256 shareQuantity ) view returns (bool) { return competitionAddress == ofParticipant; } /// @notice Checks whether redemption is permitted for a participant /// @param ofParticipant Address requesting to redeem from a Melon fund /// @param shareQuantity Quantity of shares times 10 ** 18 offered to redeem /// @param receiveQuantity Quantity of Melon token times 10 ** 18 requested to receive for shareQuantity /// @return isEligible Whether identity is eligible to redeem from a Melon fund. function isRedemptionPermitted( address ofParticipant, uint256 shareQuantity, uint256 receiveQuantity ) view returns (bool) { return competitionAddress == ofParticipant; } /// @notice Checks whether an address is whitelisted in the competition contract and competition is active /// @param x Address /// @return Whether the address is whitelisted function isCompetitionAllowed( address x ) view returns (bool) { return CompetitionInterface(competitionAddress).isWhitelisted(x) && CompetitionInterface(competitionAddress).isCompetitionActive(); } // PUBLIC METHODS /// @notice Changes the competition address /// @param ofCompetition Address of the competition contract function changeCompetitionAddress( address ofCompetition ) pre_cond(isOwner()) { competitionAddress = ofCompetition; } } contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; function DSAuth() public { owner = msg.sender; LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, this, sig); } } } contract DSExec { function tryExec( address target, bytes calldata, uint value) internal returns (bool call_ret) { return target.call.value(value)(calldata); } function exec( address target, bytes calldata, uint value) internal { if(!tryExec(target, calldata, value)) { revert(); } } // Convenience aliases function exec( address t, bytes c ) internal { exec(t, c, 0); } function exec( address t, uint256 v ) internal { bytes memory c; exec(t, c, v); } function tryExec( address t, bytes c ) internal returns (bool) { return tryExec(t, c, 0); } function tryExec( address t, uint256 v ) internal returns (bool) { bytes memory c; return tryExec(t, c, v); } } contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract Asset is DSMath, ERC20Interface { // DATA STRUCTURES mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowed; uint public _totalSupply; // PUBLIC METHODS /** * @notice Send `_value` tokens to `_to` from `msg.sender` * @dev Transfers sender's tokens to a given address * @dev Similar to transfer(address, uint, bytes), but without _data parameter * @param _to Address of token receiver * @param _value Number of tokens to transfer * @return Returns success of function call */ function transfer(address _to, uint _value) public returns (bool success) { require(balances[msg.sender] >= _value); // sanity checks require(balances[_to] + _value >= balances[_to]); balances[msg.sender] = sub(balances[msg.sender], _value); balances[_to] = add(balances[_to], _value); emit Transfer(msg.sender, _to, _value); return true; } /// @notice Transfer `_value` tokens from `_from` to `_to` if `msg.sender` is allowed. /// @notice Restriction: An account can only use this function to send to itself /// @dev Allows for an approved third party to transfer tokens from one /// address to another. Returns success. /// @param _from Address from where tokens are withdrawn. /// @param _to Address to where tokens are sent. /// @param _value Number of tokens to transfer. /// @return Returns success of function call. function transferFrom(address _from, address _to, uint _value) public returns (bool) { require(_from != address(0)); require(_to != address(0)); require(_to != address(this)); require(balances[_from] >= _value); require(allowed[_from][msg.sender] >= _value); require(balances[_to] + _value >= balances[_to]); // require(_to == msg.sender); // can only use transferFrom to send to self balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } /// @notice Allows `_spender` to transfer `_value` tokens from `msg.sender` to any address. /// @dev Sets approved amount of tokens for spender. Returns success. /// @param _spender Address of allowed account. /// @param _value Number of approved tokens. /// @return Returns success of function call. function approve(address _spender, uint _value) public returns (bool) { require(_spender != address(0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } // PUBLIC VIEW METHODS /// @dev Returns number of allowed tokens that a spender can transfer on /// behalf of a token owner. /// @param _owner Address of token owner. /// @param _spender Address of token spender. /// @return Returns remaining allowance for spender. function allowance(address _owner, address _spender) constant public returns (uint) { return allowed[_owner][_spender]; } /// @dev Returns number of tokens owned by the given address. /// @param _owner Address of token owner. /// @return Returns balance of owner. function balanceOf(address _owner) constant public returns (uint) { return balances[_owner]; } function totalSupply() view public returns (uint) { return _totalSupply; } } contract Shares is SharesInterface, Asset { // FIELDS // Constructor fields bytes32 public name; bytes8 public symbol; uint public decimal; uint public creationTime; // METHODS // CONSTRUCTOR /// @param _name Name these shares /// @param _symbol Symbol of shares /// @param _decimal Amount of decimals sharePrice is denominated in, defined to be equal as deciamls in REFERENCE_ASSET contract /// @param _creationTime Timestamp of share creation function Shares(bytes32 _name, bytes8 _symbol, uint _decimal, uint _creationTime) { name = _name; symbol = _symbol; decimal = _decimal; creationTime = _creationTime; } // PUBLIC METHODS /** * @notice Send `_value` tokens to `_to` from `msg.sender` * @dev Transfers sender's tokens to a given address * @dev Similar to transfer(address, uint, bytes), but without _data parameter * @param _to Address of token receiver * @param _value Number of tokens to transfer * @return Returns success of function call */ function transfer(address _to, uint _value) public returns (bool success) { require(balances[msg.sender] >= _value); // sanity checks require(balances[_to] + _value >= balances[_to]); balances[msg.sender] = sub(balances[msg.sender], _value); balances[_to] = add(balances[_to], _value); emit Transfer(msg.sender, _to, _value); return true; } // PUBLIC VIEW METHODS function getName() view returns (bytes32) { return name; } function getSymbol() view returns (bytes8) { return symbol; } function getDecimals() view returns (uint) { return decimal; } function getCreationTime() view returns (uint) { return creationTime; } function toSmallestShareUnit(uint quantity) view returns (uint) { return mul(quantity, 10 ** getDecimals()); } function toWholeShareUnit(uint quantity) view returns (uint) { return quantity / (10 ** getDecimals()); } // INTERNAL METHODS /// @param recipient Address the new shares should be sent to /// @param shareQuantity Number of shares to be created function createShares(address recipient, uint shareQuantity) internal { _totalSupply = add(_totalSupply, shareQuantity); balances[recipient] = add(balances[recipient], shareQuantity); emit Created(msg.sender, now, shareQuantity); emit Transfer(address(0), recipient, shareQuantity); } /// @param recipient Address the new shares should be taken from when destroyed /// @param shareQuantity Number of shares to be annihilated function annihilateShares(address recipient, uint shareQuantity) internal { _totalSupply = sub(_totalSupply, shareQuantity); balances[recipient] = sub(balances[recipient], shareQuantity); emit Annihilated(msg.sender, now, shareQuantity); emit Transfer(recipient, address(0), shareQuantity); } } contract Fund is DSMath, DBC, Owned, Shares, FundInterface { event OrderUpdated(address exchange, bytes32 orderId, UpdateType updateType); // TYPES struct Modules { // Describes all modular parts, standardised through an interface CanonicalPriceFeed pricefeed; // Provides all external data ComplianceInterface compliance; // Boolean functions regarding invest/redeem RiskMgmtInterface riskmgmt; // Boolean functions regarding make/take orders } struct Calculations { // List of internal calculations uint gav; // Gross asset value uint managementFee; // Time based fee uint performanceFee; // Performance based fee measured against QUOTE_ASSET uint unclaimedFees; // Fees not yet allocated to the fund manager uint nav; // Net asset value uint highWaterMark; // A record of best all-time fund performance uint totalSupply; // Total supply of shares uint timestamp; // Time when calculations are performed in seconds } enum UpdateType { make, take, cancel } enum RequestStatus { active, cancelled, executed } struct Request { // Describes and logs whenever asset enter and leave fund due to Participants address participant; // Participant in Melon fund requesting investment or redemption RequestStatus status; // Enum: active, cancelled, executed; Status of request address requestAsset; // Address of the asset being requested uint shareQuantity; // Quantity of Melon fund shares uint giveQuantity; // Quantity in Melon asset to give to Melon fund to receive shareQuantity uint receiveQuantity; // Quantity in Melon asset to receive from Melon fund for given shareQuantity uint timestamp; // Time of request creation in seconds uint atUpdateId; // Pricefeed updateId when this request was created } struct Exchange { address exchange; address exchangeAdapter; bool takesCustody; // exchange takes custody before making order } struct OpenMakeOrder { uint id; // Order Id from exchange uint expiresAt; // Timestamp when the order expires } struct Order { // Describes an order event (make or take order) address exchangeAddress; // address of the exchange this order is on bytes32 orderId; // Id as returned from exchange UpdateType updateType; // Enum: make, take (cancel should be ignored) address makerAsset; // Order maker's asset address takerAsset; // Order taker's asset uint makerQuantity; // Quantity of makerAsset to be traded uint takerQuantity; // Quantity of takerAsset to be traded uint timestamp; // Time of order creation in seconds uint fillTakerQuantity; // Quantity of takerAsset to be filled } // FIELDS // Constant fields uint public constant MAX_FUND_ASSETS = 20; // Max ownable assets by the fund supported by gas limits uint public constant ORDER_EXPIRATION_TIME = 86400; // Make order expiration time (1 day) // Constructor fields uint public MANAGEMENT_FEE_RATE; // Fee rate in QUOTE_ASSET per managed seconds in WAD uint public PERFORMANCE_FEE_RATE; // Fee rate in QUOTE_ASSET per delta improvement in WAD address public VERSION; // Address of Version contract Asset public QUOTE_ASSET; // QUOTE asset as ERC20 contract // Methods fields Modules public modules; // Struct which holds all the initialised module instances Exchange[] public exchanges; // Array containing exchanges this fund supports Calculations public atLastUnclaimedFeeAllocation; // Calculation results at last allocateUnclaimedFees() call Order[] public orders; // append-only list of makes/takes from this fund mapping (address => mapping(address => OpenMakeOrder)) public exchangesToOpenMakeOrders; // exchangeIndex to: asset to open make orders bool public isShutDown; // Security feature, if yes than investing, managing, allocateUnclaimedFees gets blocked Request[] public requests; // All the requests this fund received from participants mapping (address => bool) public isInvestAllowed; // If false, fund rejects investments from the key asset address[] public ownedAssets; // List of all assets owned by the fund or for which the fund has open make orders mapping (address => bool) public isInAssetList; // Mapping from asset to whether the asset exists in ownedAssets mapping (address => bool) public isInOpenMakeOrder; // Mapping from asset to whether the asset is in a open make order as buy asset // METHODS // CONSTRUCTOR /// @dev Should only be called via Version.setupFund(..) /// @param withName human-readable descriptive name (not necessarily unique) /// @param ofQuoteAsset Asset against which mgmt and performance fee is measured against and which can be used to invest using this single asset /// @param ofManagementFee A time based fee expressed, given in a number which is divided by 1 WAD /// @param ofPerformanceFee A time performance based fee, performance relative to ofQuoteAsset, given in a number which is divided by 1 WAD /// @param ofCompliance Address of compliance module /// @param ofRiskMgmt Address of risk management module /// @param ofPriceFeed Address of price feed module /// @param ofExchanges Addresses of exchange on which this fund can trade /// @param ofDefaultAssets Addresses of assets to enable invest for (quote asset is already enabled) /// @return Deployed Fund with manager set as ofManager function Fund( address ofManager, bytes32 withName, address ofQuoteAsset, uint ofManagementFee, uint ofPerformanceFee, address ofCompliance, address ofRiskMgmt, address ofPriceFeed, address[] ofExchanges, address[] ofDefaultAssets ) Shares(withName, "MLNF", 18, now) { require(ofManagementFee < 10 ** 18); // Require management fee to be less than 100 percent require(ofPerformanceFee < 10 ** 18); // Require performance fee to be less than 100 percent isInvestAllowed[ofQuoteAsset] = true; owner = ofManager; MANAGEMENT_FEE_RATE = ofManagementFee; // 1 percent is expressed as 0.01 * 10 ** 18 PERFORMANCE_FEE_RATE = ofPerformanceFee; // 1 percent is expressed as 0.01 * 10 ** 18 VERSION = msg.sender; modules.compliance = ComplianceInterface(ofCompliance); modules.riskmgmt = RiskMgmtInterface(ofRiskMgmt); modules.pricefeed = CanonicalPriceFeed(ofPriceFeed); // Bridged to Melon exchange interface by exchangeAdapter library for (uint i = 0; i < ofExchanges.length; ++i) { require(modules.pricefeed.exchangeIsRegistered(ofExchanges[i])); var (ofExchangeAdapter, takesCustody, ) = modules.pricefeed.getExchangeInformation(ofExchanges[i]); exchanges.push(Exchange({ exchange: ofExchanges[i], exchangeAdapter: ofExchangeAdapter, takesCustody: takesCustody })); } QUOTE_ASSET = Asset(ofQuoteAsset); // Quote Asset always in owned assets list ownedAssets.push(ofQuoteAsset); isInAssetList[ofQuoteAsset] = true; require(address(QUOTE_ASSET) == modules.pricefeed.getQuoteAsset()); // Sanity check for (uint j = 0; j < ofDefaultAssets.length; j++) { require(modules.pricefeed.assetIsRegistered(ofDefaultAssets[j])); isInvestAllowed[ofDefaultAssets[j]] = true; } atLastUnclaimedFeeAllocation = Calculations({ gav: 0, managementFee: 0, performanceFee: 0, unclaimedFees: 0, nav: 0, highWaterMark: 10 ** getDecimals(), totalSupply: _totalSupply, timestamp: now }); } // EXTERNAL METHODS // EXTERNAL : ADMINISTRATION /// @notice Enable investment in specified assets /// @param ofAssets Array of assets to enable investment in function enableInvestment(address[] ofAssets) external pre_cond(isOwner()) { for (uint i = 0; i < ofAssets.length; ++i) { require(modules.pricefeed.assetIsRegistered(ofAssets[i])); isInvestAllowed[ofAssets[i]] = true; } } /// @notice Disable investment in specified assets /// @param ofAssets Array of assets to disable investment in function disableInvestment(address[] ofAssets) external pre_cond(isOwner()) { for (uint i = 0; i < ofAssets.length; ++i) { isInvestAllowed[ofAssets[i]] = false; } } function shutDown() external pre_cond(msg.sender == VERSION) { isShutDown = true; } // EXTERNAL : PARTICIPATION /// @notice Give melon tokens to receive shares of this fund /// @dev Recommended to give some leeway in prices to account for possibly slightly changing prices /// @param giveQuantity Quantity of Melon token times 10 ** 18 offered to receive shareQuantity /// @param shareQuantity Quantity of shares times 10 ** 18 requested to be received /// @param investmentAsset Address of asset to invest in function requestInvestment( uint giveQuantity, uint shareQuantity, address investmentAsset ) external pre_cond(!isShutDown) pre_cond(isInvestAllowed[investmentAsset]) // investment using investmentAsset has not been deactivated by the Manager pre_cond(modules.compliance.isInvestmentPermitted(msg.sender, giveQuantity, shareQuantity)) // Compliance Module: Investment permitted { requests.push(Request({ participant: msg.sender, status: RequestStatus.active, requestAsset: investmentAsset, shareQuantity: shareQuantity, giveQuantity: giveQuantity, receiveQuantity: shareQuantity, timestamp: now, atUpdateId: modules.pricefeed.getLastUpdateId() })); emit RequestUpdated(getLastRequestId()); } /// @notice Executes active investment and redemption requests, in a way that minimises information advantages of investor /// @dev Distributes melon and shares according to the request /// @param id Index of request to be executed /// @dev Active investment or redemption request executed function executeRequest(uint id) external pre_cond(!isShutDown) pre_cond(requests[id].status == RequestStatus.active) pre_cond( _totalSupply == 0 || ( now >= add(requests[id].timestamp, modules.pricefeed.getInterval()) && modules.pricefeed.getLastUpdateId() >= add(requests[id].atUpdateId, 2) ) ) // PriceFeed Module: Wait at least one interval time and two updates before continuing (unless it is the first investment) { Request request = requests[id]; var (isRecent, , ) = modules.pricefeed.getPriceInfo(address(request.requestAsset)); require(isRecent); // sharePrice quoted in QUOTE_ASSET and multiplied by 10 ** fundDecimals uint costQuantity = toWholeShareUnit(mul(request.shareQuantity, calcSharePriceAndAllocateFees())); // By definition quoteDecimals == fundDecimals if (request.requestAsset != address(QUOTE_ASSET)) { var (isPriceRecent, invertedRequestAssetPrice, requestAssetDecimal) = modules.pricefeed.getInvertedPriceInfo(request.requestAsset); if (!isPriceRecent) { revert(); } costQuantity = mul(costQuantity, invertedRequestAssetPrice) / 10 ** requestAssetDecimal; } if ( isInvestAllowed[request.requestAsset] && costQuantity <= request.giveQuantity ) { request.status = RequestStatus.executed; require(AssetInterface(request.requestAsset).transferFrom(request.participant, address(this), costQuantity)); // Allocate Value createShares(request.participant, request.shareQuantity); // Accounting if (!isInAssetList[request.requestAsset]) { ownedAssets.push(request.requestAsset); isInAssetList[request.requestAsset] = true; } } else { revert(); // Invalid Request or invalid giveQuantity / receiveQuantity } } /// @notice Cancels active investment and redemption requests /// @param id Index of request to be executed function cancelRequest(uint id) external pre_cond(requests[id].status == RequestStatus.active) // Request is active pre_cond(requests[id].participant == msg.sender || isShutDown) // Either request creator or fund is shut down { requests[id].status = RequestStatus.cancelled; } /// @notice Redeems by allocating an ownership percentage of each asset to the participant /// @dev Independent of running price feed! /// @param shareQuantity Number of shares owned by the participant, which the participant would like to redeem for individual assets /// @return Whether all assets sent to shareholder or not function redeemAllOwnedAssets(uint shareQuantity) external returns (bool success) { return emergencyRedeem(shareQuantity, ownedAssets); } // EXTERNAL : MANAGING /// @notice Universal method for calling exchange functions through adapters /// @notice See adapter contracts for parameters needed for each exchange /// @param exchangeIndex Index of the exchange in the "exchanges" array /// @param method Signature of the adapter method to call (as per ABI spec) /// @param orderAddresses [0] Order maker /// @param orderAddresses [1] Order taker /// @param orderAddresses [2] Order maker asset /// @param orderAddresses [3] Order taker asset /// @param orderAddresses [4] Fee recipient /// @param orderValues [0] Maker token quantity /// @param orderValues [1] Taker token quantity /// @param orderValues [2] Maker fee /// @param orderValues [3] Taker fee /// @param orderValues [4] Timestamp (seconds) /// @param orderValues [5] Salt/nonce /// @param orderValues [6] Fill amount: amount of taker token to be traded /// @param orderValues [7] Dexy signature mode /// @param identifier Order identifier /// @param v ECDSA recovery id /// @param r ECDSA signature output r /// @param s ECDSA signature output s function callOnExchange( uint exchangeIndex, bytes4 method, address[5] orderAddresses, uint[8] orderValues, bytes32 identifier, uint8 v, bytes32 r, bytes32 s ) external { require( modules.pricefeed.exchangeMethodIsAllowed( exchanges[exchangeIndex].exchange, method ) ); require( exchanges[exchangeIndex].exchangeAdapter.delegatecall( method, exchanges[exchangeIndex].exchange, orderAddresses, orderValues, identifier, v, r, s ) ); } function addOpenMakeOrder( address ofExchange, address ofSellAsset, uint orderId ) pre_cond(msg.sender == address(this)) { isInOpenMakeOrder[ofSellAsset] = true; exchangesToOpenMakeOrders[ofExchange][ofSellAsset].id = orderId; exchangesToOpenMakeOrders[ofExchange][ofSellAsset].expiresAt = add(now, ORDER_EXPIRATION_TIME); } function removeOpenMakeOrder( address ofExchange, address ofSellAsset ) pre_cond(msg.sender == address(this)) { delete exchangesToOpenMakeOrders[ofExchange][ofSellAsset]; } function orderUpdateHook( address ofExchange, bytes32 orderId, UpdateType updateType, address[2] orderAddresses, // makerAsset, takerAsset uint[3] orderValues // makerQuantity, takerQuantity, fillTakerQuantity (take only) ) pre_cond(msg.sender == address(this)) { // only save make/take if (updateType == UpdateType.make || updateType == UpdateType.take) { orders.push(Order({ exchangeAddress: ofExchange, orderId: orderId, updateType: updateType, makerAsset: orderAddresses[0], takerAsset: orderAddresses[1], makerQuantity: orderValues[0], takerQuantity: orderValues[1], timestamp: block.timestamp, fillTakerQuantity: orderValues[2] })); } emit OrderUpdated(ofExchange, orderId, updateType); } // PUBLIC METHODS // PUBLIC METHODS : ACCOUNTING /// @notice Calculates gross asset value of the fund /// @dev Decimals in assets must be equal to decimals in PriceFeed for all entries in AssetRegistrar /// @dev Assumes that module.pricefeed.getPriceInfo(..) returns recent prices /// @return gav Gross asset value quoted in QUOTE_ASSET and multiplied by 10 ** shareDecimals function calcGav() returns (uint gav) { // prices quoted in QUOTE_ASSET and multiplied by 10 ** assetDecimal uint[] memory allAssetHoldings = new uint[](ownedAssets.length); uint[] memory allAssetPrices = new uint[](ownedAssets.length); address[] memory tempOwnedAssets; tempOwnedAssets = ownedAssets; delete ownedAssets; for (uint i = 0; i < tempOwnedAssets.length; ++i) { address ofAsset = tempOwnedAssets[i]; // assetHoldings formatting: mul(exchangeHoldings, 10 ** assetDecimal) uint assetHoldings = add( uint(AssetInterface(ofAsset).balanceOf(address(this))), // asset base units held by fund quantityHeldInCustodyOfExchange(ofAsset) ); // assetPrice formatting: mul(exchangePrice, 10 ** assetDecimal) var (isRecent, assetPrice, assetDecimals) = modules.pricefeed.getPriceInfo(ofAsset); if (!isRecent) { revert(); } allAssetHoldings[i] = assetHoldings; allAssetPrices[i] = assetPrice; // gav as sum of mul(assetHoldings, assetPrice) with formatting: mul(mul(exchangeHoldings, exchangePrice), 10 ** shareDecimals) gav = add(gav, mul(assetHoldings, assetPrice) / (10 ** uint256(assetDecimals))); // Sum up product of asset holdings of this vault and asset prices if (assetHoldings != 0 || ofAsset == address(QUOTE_ASSET) || isInOpenMakeOrder[ofAsset]) { // Check if asset holdings is not zero or is address(QUOTE_ASSET) or in open make order ownedAssets.push(ofAsset); } else { isInAssetList[ofAsset] = false; // Remove from ownedAssets if asset holdings are zero } } emit PortfolioContent(tempOwnedAssets, allAssetHoldings, allAssetPrices); } /// @notice Add an asset to the list that this fund owns function addAssetToOwnedAssets (address ofAsset) public pre_cond(isOwner() || msg.sender == address(this)) { isInOpenMakeOrder[ofAsset] = true; if (!isInAssetList[ofAsset]) { ownedAssets.push(ofAsset); isInAssetList[ofAsset] = true; } } /** @notice Calculates unclaimed fees of the fund manager @param gav Gross asset value in QUOTE_ASSET and multiplied by 10 ** shareDecimals @return { "managementFees": "A time (seconds) based fee in QUOTE_ASSET and multiplied by 10 ** shareDecimals", "performanceFees": "A performance (rise of sharePrice measured in QUOTE_ASSET) based fee in QUOTE_ASSET and multiplied by 10 ** shareDecimals", "unclaimedfees": "The sum of both managementfee and performancefee in QUOTE_ASSET and multiplied by 10 ** shareDecimals" } */ function calcUnclaimedFees(uint gav) view returns ( uint managementFee, uint performanceFee, uint unclaimedFees) { // Management fee calculation uint timePassed = sub(now, atLastUnclaimedFeeAllocation.timestamp); uint gavPercentage = mul(timePassed, gav) / (1 years); managementFee = wmul(gavPercentage, MANAGEMENT_FEE_RATE); // Performance fee calculation // Handle potential division through zero by defining a default value uint valuePerShareExclMgmtFees = _totalSupply > 0 ? calcValuePerShare(sub(gav, managementFee), _totalSupply) : toSmallestShareUnit(1); if (valuePerShareExclMgmtFees > atLastUnclaimedFeeAllocation.highWaterMark) { uint gainInSharePrice = sub(valuePerShareExclMgmtFees, atLastUnclaimedFeeAllocation.highWaterMark); uint investmentProfits = wmul(gainInSharePrice, _totalSupply); performanceFee = wmul(investmentProfits, PERFORMANCE_FEE_RATE); } // Sum of all FEES unclaimedFees = add(managementFee, performanceFee); } /// @notice Calculates the Net asset value of this fund /// @param gav Gross asset value of this fund in QUOTE_ASSET and multiplied by 10 ** shareDecimals /// @param unclaimedFees The sum of both managementFee and performanceFee in QUOTE_ASSET and multiplied by 10 ** shareDecimals /// @return nav Net asset value in QUOTE_ASSET and multiplied by 10 ** shareDecimals function calcNav(uint gav, uint unclaimedFees) view returns (uint nav) { nav = sub(gav, unclaimedFees); } /// @notice Calculates the share price of the fund /// @dev Convention for valuePerShare (== sharePrice) formatting: mul(totalValue / numShares, 10 ** decimal), to avoid floating numbers /// @dev Non-zero share supply; value denominated in [base unit of melonAsset] /// @param totalValue the total value in QUOTE_ASSET and multiplied by 10 ** shareDecimals /// @param numShares the number of shares multiplied by 10 ** shareDecimals /// @return valuePerShare Share price denominated in QUOTE_ASSET and multiplied by 10 ** shareDecimals function calcValuePerShare(uint totalValue, uint numShares) view pre_cond(numShares > 0) returns (uint valuePerShare) { valuePerShare = toSmallestShareUnit(totalValue) / numShares; } /** @notice Calculates essential fund metrics @return { "gav": "Gross asset value of this fund denominated in [base unit of melonAsset]", "managementFee": "A time (seconds) based fee", "performanceFee": "A performance (rise of sharePrice measured in QUOTE_ASSET) based fee", "unclaimedFees": "The sum of both managementFee and performanceFee denominated in [base unit of melonAsset]", "feesShareQuantity": "The number of shares to be given as fees to the manager", "nav": "Net asset value denominated in [base unit of melonAsset]", "sharePrice": "Share price denominated in [base unit of melonAsset]" } */ function performCalculations() view returns ( uint gav, uint managementFee, uint performanceFee, uint unclaimedFees, uint feesShareQuantity, uint nav, uint sharePrice ) { gav = calcGav(); // Reflects value independent of fees (managementFee, performanceFee, unclaimedFees) = calcUnclaimedFees(gav); nav = calcNav(gav, unclaimedFees); // The value of unclaimedFees measured in shares of this fund at current value feesShareQuantity = (gav == 0) ? 0 : mul(_totalSupply, unclaimedFees) / gav; // The total share supply including the value of unclaimedFees, measured in shares of this fund uint totalSupplyAccountingForFees = add(_totalSupply, feesShareQuantity); sharePrice = _totalSupply > 0 ? calcValuePerShare(gav, totalSupplyAccountingForFees) : toSmallestShareUnit(1); // Handle potential division through zero by defining a default value } /// @notice Converts unclaimed fees of the manager into fund shares /// @return sharePrice Share price denominated in [base unit of melonAsset] function calcSharePriceAndAllocateFees() public returns (uint) { var ( gav, managementFee, performanceFee, unclaimedFees, feesShareQuantity, nav, sharePrice ) = performCalculations(); createShares(owner, feesShareQuantity); // Updates _totalSupply by creating shares allocated to manager // Update Calculations uint highWaterMark = atLastUnclaimedFeeAllocation.highWaterMark >= sharePrice ? atLastUnclaimedFeeAllocation.highWaterMark : sharePrice; atLastUnclaimedFeeAllocation = Calculations({ gav: gav, managementFee: managementFee, performanceFee: performanceFee, unclaimedFees: unclaimedFees, nav: nav, highWaterMark: highWaterMark, totalSupply: _totalSupply, timestamp: now }); emit FeesConverted(now, feesShareQuantity, unclaimedFees); emit CalculationUpdate(now, managementFee, performanceFee, nav, sharePrice, _totalSupply); return sharePrice; } // PUBLIC : REDEEMING /// @notice Redeems by allocating an ownership percentage only of requestedAssets to the participant /// @dev This works, but with loops, so only up to a certain number of assets (right now the max is 4) /// @dev Independent of running price feed! Note: if requestedAssets != ownedAssets then participant misses out on some owned value /// @param shareQuantity Number of shares owned by the participant, which the participant would like to redeem for a slice of assets /// @param requestedAssets List of addresses that consitute a subset of ownedAssets. /// @return Whether all assets sent to shareholder or not function emergencyRedeem(uint shareQuantity, address[] requestedAssets) public pre_cond(balances[msg.sender] >= shareQuantity) // sender owns enough shares returns (bool) { address ofAsset; uint[] memory ownershipQuantities = new uint[](requestedAssets.length); address[] memory redeemedAssets = new address[](requestedAssets.length); // Check whether enough assets held by fund for (uint i = 0; i < requestedAssets.length; ++i) { ofAsset = requestedAssets[i]; require(isInAssetList[ofAsset]); for (uint j = 0; j < redeemedAssets.length; j++) { if (ofAsset == redeemedAssets[j]) { revert(); } } redeemedAssets[i] = ofAsset; uint assetHoldings = add( uint(AssetInterface(ofAsset).balanceOf(address(this))), quantityHeldInCustodyOfExchange(ofAsset) ); if (assetHoldings == 0) continue; // participant's ownership percentage of asset holdings ownershipQuantities[i] = mul(assetHoldings, shareQuantity) / _totalSupply; // CRITICAL ERR: Not enough fund asset balance for owed ownershipQuantitiy, eg in case of unreturned asset quantity at address(exchanges[i].exchange) address if (uint(AssetInterface(ofAsset).balanceOf(address(this))) < ownershipQuantities[i]) { isShutDown = true; emit ErrorMessage("CRITICAL ERR: Not enough assetHoldings for owed ownershipQuantitiy"); return false; } } // Annihilate shares before external calls to prevent reentrancy annihilateShares(msg.sender, shareQuantity); // Transfer ownershipQuantity of Assets for (uint k = 0; k < requestedAssets.length; ++k) { // Failed to send owed ownershipQuantity from fund to participant ofAsset = requestedAssets[k]; if (ownershipQuantities[k] == 0) { continue; } else if (!AssetInterface(ofAsset).transfer(msg.sender, ownershipQuantities[k])) { revert(); } } emit Redeemed(msg.sender, now, shareQuantity); return true; } // PUBLIC : FEES /// @dev Quantity of asset held in exchange according to associated order id /// @param ofAsset Address of asset /// @return Quantity of input asset held in exchange function quantityHeldInCustodyOfExchange(address ofAsset) returns (uint) { uint totalSellQuantity; // quantity in custody across exchanges uint totalSellQuantityInApprove; // quantity of asset in approve (allowance) but not custody of exchange for (uint i; i < exchanges.length; i++) { if (exchangesToOpenMakeOrders[exchanges[i].exchange][ofAsset].id == 0) { continue; } var (sellAsset, , sellQuantity, ) = GenericExchangeInterface(exchanges[i].exchangeAdapter).getOrder(exchanges[i].exchange, exchangesToOpenMakeOrders[exchanges[i].exchange][ofAsset].id); if (sellQuantity == 0) { // remove id if remaining sell quantity zero (closed) delete exchangesToOpenMakeOrders[exchanges[i].exchange][ofAsset]; } totalSellQuantity = add(totalSellQuantity, sellQuantity); if (!exchanges[i].takesCustody) { totalSellQuantityInApprove += sellQuantity; } } if (totalSellQuantity == 0) { isInOpenMakeOrder[sellAsset] = false; } return sub(totalSellQuantity, totalSellQuantityInApprove); // Since quantity in approve is not actually in custody } // PUBLIC VIEW METHODS /// @notice Calculates sharePrice denominated in [base unit of melonAsset] /// @return sharePrice Share price denominated in [base unit of melonAsset] function calcSharePrice() view returns (uint sharePrice) { (, , , , , sharePrice) = performCalculations(); return sharePrice; } function getModules() view returns (address, address, address) { return ( address(modules.pricefeed), address(modules.compliance), address(modules.riskmgmt) ); } function getLastRequestId() view returns (uint) { return requests.length - 1; } function getLastOrderIndex() view returns (uint) { return orders.length - 1; } function getManager() view returns (address) { return owner; } function getOwnedAssetsLength() view returns (uint) { return ownedAssets.length; } function getExchangeInfo() view returns (address[], address[], bool[]) { address[] memory ofExchanges = new address[](exchanges.length); address[] memory ofAdapters = new address[](exchanges.length); bool[] memory takesCustody = new bool[](exchanges.length); for (uint i = 0; i < exchanges.length; i++) { ofExchanges[i] = exchanges[i].exchange; ofAdapters[i] = exchanges[i].exchangeAdapter; takesCustody[i] = exchanges[i].takesCustody; } return (ofExchanges, ofAdapters, takesCustody); } function orderExpired(address ofExchange, address ofAsset) view returns (bool) { uint expiryTime = exchangesToOpenMakeOrders[ofExchange][ofAsset].expiresAt; require(expiryTime > 0); return block.timestamp >= expiryTime; } function getOpenOrderInfo(address ofExchange, address ofAsset) view returns (uint, uint) { OpenMakeOrder order = exchangesToOpenMakeOrders[ofExchange][ofAsset]; return (order.id, order.expiresAt); } } contract Competition is CompetitionInterface, DSMath, DBC, Owned { // TYPES struct Registrant { address fund; // Address of the Melon fund address registrant; // Manager and registrant of the fund bool hasSigned; // Whether initial requirements passed and Registrant signed Terms and Conditions; uint buyinQuantity; // Quantity of buyinAsset spent uint payoutQuantity; // Quantity of payoutAsset received as prize bool isRewarded; // Is the Registrant rewarded yet } struct RegistrantId { uint id; // Actual Registrant Id bool exists; // Used to check if the mapping exists } // FIELDS // Constant fields // Competition terms and conditions as displayed on https://ipfs.io/ipfs/QmXuUfPi6xeYfuMwpVAughm7GjGUjkbEojhNR8DJqVBBxc // IPFS hash encoded using http://lenschulwitz.com/base58 bytes public constant TERMS_AND_CONDITIONS = hex"12208E21FD34B8B2409972D30326D840C9D747438A118580D6BA8C0735ED53810491"; uint public MELON_BASE_UNIT = 10 ** 18; // Constructor fields address public custodian; // Address of the custodian which holds the funds sent uint public startTime; // Competition start time in seconds (Temporarily Set) uint public endTime; // Competition end time in seconds uint public payoutRate; // Fixed MLN - Ether conversion rate uint public bonusRate; // Bonus multiplier uint public totalMaxBuyin; // Limit amount of deposit to participate in competition (Valued in Ether) uint public currentTotalBuyin; // Total buyin till now uint public maxRegistrants; // Limit number of participate in competition uint public prizeMoneyAsset; // Equivalent to payoutAsset uint public prizeMoneyQuantity; // Total prize money pool address public MELON_ASSET; // Adresss of Melon asset contract ERC20Interface public MELON_CONTRACT; // Melon as ERC20 contract address public COMPETITION_VERSION; // Version contract address // Methods fields Registrant[] public registrants; // List of all registrants, can be externally accessed mapping (address => address) public registeredFundToRegistrants; // For fund address indexed accessing of registrant addresses mapping(address => RegistrantId) public registrantToRegistrantIds; // For registrant address indexed accessing of registrant ids mapping(address => uint) public whitelistantToMaxBuyin; // For registrant address to respective max buyIn cap (Valued in Ether) //EVENTS event Register(uint withId, address fund, address manager); // METHODS // CONSTRUCTOR function Competition( address ofMelonAsset, address ofCompetitionVersion, address ofCustodian, uint ofStartTime, uint ofEndTime, uint ofPayoutRate, uint ofTotalMaxBuyin, uint ofMaxRegistrants ) { MELON_ASSET = ofMelonAsset; MELON_CONTRACT = ERC20Interface(MELON_ASSET); COMPETITION_VERSION = ofCompetitionVersion; custodian = ofCustodian; startTime = ofStartTime; endTime = ofEndTime; payoutRate = ofPayoutRate; totalMaxBuyin = ofTotalMaxBuyin; maxRegistrants = ofMaxRegistrants; } // PRE, POST, INVARIANT CONDITIONS /// @dev Proofs that terms and conditions have been read and understood /// @param byManager Address of the fund manager, as used in the ipfs-frontend /// @param v ellipitc curve parameter v /// @param r ellipitc curve parameter r /// @param s ellipitc curve parameter s /// @return Whether or not terms and conditions have been read and understood function termsAndConditionsAreSigned(address byManager, uint8 v, bytes32 r, bytes32 s) view returns (bool) { return ecrecover( // Parity does prepend \x19Ethereum Signed Message:\n{len(message)} before signing. // Signature order has also been changed in 1.6.7 and upcoming 1.7.x, // it will return rsv (same as geth; where v is [27, 28]). // Note that if you are using ecrecover, v will be either "00" or "01". // As a result, in order to use this value, you will have to parse it to an // integer and then add 27. This will result in either a 27 or a 28. // https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethsign keccak256("\x19Ethereum Signed Message:\n34", TERMS_AND_CONDITIONS), v, r, s ) == byManager; // Has sender signed TERMS_AND_CONDITIONS } /// @dev Whether message sender is KYC verified through CERTIFIER /// @param x Address to be checked for KYC verification function isWhitelisted(address x) view returns (bool) { return whitelistantToMaxBuyin[x] > 0; } /// @dev Whether the competition is on-going function isCompetitionActive() view returns (bool) { return now >= startTime && now < endTime; } // CONSTANT METHODS function getMelonAsset() view returns (address) { return MELON_ASSET; } /// @return Get RegistrantId from registrant address function getRegistrantId(address x) view returns (uint) { return registrantToRegistrantIds[x].id; } /// @return Address of the fund registered by the registrant address function getRegistrantFund(address x) view returns (address) { return registrants[getRegistrantId(x)].fund; } /// @return Get time to end of the competition function getTimeTillEnd() view returns (uint) { if (now > endTime) { return 0; } return sub(endTime, now); } /// @return Get value of MLN amount in Ether function getEtherValue(uint amount) view returns (uint) { address feedAddress = Version(COMPETITION_VERSION).CANONICAL_PRICEFEED(); var (isRecent, price, ) = CanonicalPriceFeed(feedAddress).getPriceInfo(MELON_ASSET); if (!isRecent) { revert(); } return mul(price, amount) / 10 ** 18; } /// @return Calculated payout in MLN with bonus for payin in Ether function calculatePayout(uint payin) view returns (uint payoutQuantity) { payoutQuantity = mul(payin, payoutRate) / 10 ** 18; } /** @notice Returns an array of fund addresses and an associated array of whether competing and whether disqualified @return { "fundAddrs": "Array of addresses of Melon Funds", "fundRegistrants": "Array of addresses of Melon fund managers, as used in the ipfs-frontend", } */ function getCompetitionStatusOfRegistrants() view returns( address[], address[], bool[] ) { address[] memory fundAddrs = new address[](registrants.length); address[] memory fundRegistrants = new address[](registrants.length); bool[] memory isRewarded = new bool[](registrants.length); for (uint i = 0; i < registrants.length; i++) { fundAddrs[i] = registrants[i].fund; fundRegistrants[i] = registrants[i].registrant; isRewarded[i] = registrants[i].isRewarded; } return (fundAddrs, fundRegistrants, isRewarded); } // NON-CONSTANT METHODS /// @notice Register to take part in the competition /// @dev Check if the fund address is actually from the Competition Version /// @param fund Address of the Melon fund /// @param v ellipitc curve parameter v /// @param r ellipitc curve parameter r /// @param s ellipitc curve parameter s function registerForCompetition( address fund, uint8 v, bytes32 r, bytes32 s ) payable pre_cond(isCompetitionActive() && !Version(COMPETITION_VERSION).isShutDown()) pre_cond(termsAndConditionsAreSigned(msg.sender, v, r, s) && isWhitelisted(msg.sender)) { require(registeredFundToRegistrants[fund] == address(0) && registrantToRegistrantIds[msg.sender].exists == false); require(add(currentTotalBuyin, msg.value) <= totalMaxBuyin && registrants.length < maxRegistrants); require(msg.value <= whitelistantToMaxBuyin[msg.sender]); require(Version(COMPETITION_VERSION).getFundByManager(msg.sender) == fund); // Calculate Payout Quantity, invest the quantity in registrant's fund uint payoutQuantity = calculatePayout(msg.value); registeredFundToRegistrants[fund] = msg.sender; registrantToRegistrantIds[msg.sender] = RegistrantId({id: registrants.length, exists: true}); currentTotalBuyin = add(currentTotalBuyin, msg.value); FundInterface fundContract = FundInterface(fund); MELON_CONTRACT.approve(fund, payoutQuantity); // Give payoutRequest MLN in return for msg.value fundContract.requestInvestment(payoutQuantity, getEtherValue(payoutQuantity), MELON_ASSET); fundContract.executeRequest(fundContract.getLastRequestId()); custodian.transfer(msg.value); // Emit Register event emit Register(registrants.length, fund, msg.sender); registrants.push(Registrant({ fund: fund, registrant: msg.sender, hasSigned: true, buyinQuantity: msg.value, payoutQuantity: payoutQuantity, isRewarded: false })); } /// @notice Add batch addresses to whitelist with set maxBuyinQuantity /// @dev Only the owner can call this function /// @param maxBuyinQuantity Quantity of payoutAsset received as prize /// @param whitelistants Performance of Melon fund at competition endTime; Can be changed for any other comparison metric function batchAddToWhitelist( uint maxBuyinQuantity, address[] whitelistants ) pre_cond(isOwner()) pre_cond(now < endTime) { for (uint i = 0; i < whitelistants.length; ++i) { whitelistantToMaxBuyin[whitelistants[i]] = maxBuyinQuantity; } } /// @notice Withdraw MLN /// @dev Only the owner can call this function function withdrawMln(address to, uint amount) pre_cond(isOwner()) { MELON_CONTRACT.transfer(to, amount); } /// @notice Claim Reward function claimReward() pre_cond(getRegistrantFund(msg.sender) != address(0)) { require(block.timestamp >= endTime || Version(COMPETITION_VERSION).isShutDown()); Registrant registrant = registrants[getRegistrantId(msg.sender)]; require(registrant.isRewarded == false); registrant.isRewarded = true; // Is this safe to assume this or should we transfer all the balance instead? uint balance = AssetInterface(registrant.fund).balanceOf(address(this)); require(AssetInterface(registrant.fund).transfer(registrant.registrant, balance)); // Emit ClaimedReward event emit ClaimReward(msg.sender, registrant.fund, balance); } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } contract DSGroup is DSExec, DSNote { address[] public members; uint public quorum; uint public window; uint public actionCount; mapping (uint => Action) public actions; mapping (uint => mapping (address => bool)) public confirmedBy; mapping (address => bool) public isMember; // Legacy events event Proposed (uint id, bytes calldata); event Confirmed (uint id, address member); event Triggered (uint id); struct Action { address target; bytes calldata; uint value; uint confirmations; uint deadline; bool triggered; } function DSGroup( address[] members_, uint quorum_, uint window_ ) { members = members_; quorum = quorum_; window = window_; for (uint i = 0; i < members.length; i++) { isMember[members[i]] = true; } } function memberCount() constant returns (uint) { return members.length; } function target(uint id) constant returns (address) { return actions[id].target; } function calldata(uint id) constant returns (bytes) { return actions[id].calldata; } function value(uint id) constant returns (uint) { return actions[id].value; } function confirmations(uint id) constant returns (uint) { return actions[id].confirmations; } function deadline(uint id) constant returns (uint) { return actions[id].deadline; } function triggered(uint id) constant returns (bool) { return actions[id].triggered; } function confirmed(uint id) constant returns (bool) { return confirmations(id) >= quorum; } function expired(uint id) constant returns (bool) { return now > deadline(id); } function deposit() note payable { } function propose( address target, bytes calldata, uint value ) onlyMembers note returns (uint id) { id = ++actionCount; actions[id].target = target; actions[id].calldata = calldata; actions[id].value = value; actions[id].deadline = now + window; Proposed(id, calldata); } function confirm(uint id) onlyMembers onlyActive(id) note { assert(!confirmedBy[id][msg.sender]); confirmedBy[id][msg.sender] = true; actions[id].confirmations++; Confirmed(id, msg.sender); } function trigger(uint id) onlyMembers onlyActive(id) note { assert(confirmed(id)); actions[id].triggered = true; exec(actions[id].target, actions[id].calldata, actions[id].value); Triggered(id); } modifier onlyMembers { assert(isMember[msg.sender]); _; } modifier onlyActive(uint id) { assert(!expired(id)); assert(!triggered(id)); _; } //------------------------------------------------------------------ // Legacy functions //------------------------------------------------------------------ function getInfo() constant returns ( uint quorum_, uint memberCount, uint window_, uint actionCount_ ) { return (quorum, members.length, window, actionCount); } function getActionStatus(uint id) constant returns ( uint confirmations, uint deadline, bool triggered, address target, uint value ) { return ( actions[id].confirmations, actions[id].deadline, actions[id].triggered, actions[id].target, actions[id].value ); } } contract DSGroupFactory is DSNote { mapping (address => bool) public isGroup; function newGroup( address[] members, uint quorum, uint window ) note returns (DSGroup group) { group = new DSGroup(members, quorum, window); isGroup[group] = true; } } contract DSThing is DSAuth, DSNote, DSMath { function S(string s) internal pure returns (bytes4) { return bytes4(keccak256(s)); } } interface GenericExchangeInterface { // EVENTS event OrderUpdated(uint id); // METHODS // EXTERNAL METHODS function makeOrder( address onExchange, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) external returns (uint); function takeOrder(address onExchange, uint id, uint quantity) external returns (bool); function cancelOrder(address onExchange, uint id) external returns (bool); // PUBLIC METHODS // PUBLIC VIEW METHODS function isApproveOnly() view returns (bool); function getLastOrderId(address onExchange) view returns (uint); function isActive(address onExchange, uint id) view returns (bool); function getOwner(address onExchange, uint id) view returns (address); function getOrder(address onExchange, uint id) view returns (address, address, uint, uint); function getTimestamp(address onExchange, uint id) view returns (uint); } contract CanonicalRegistrar is DSThing, DBC { // TYPES struct Asset { bool exists; // True if asset is registered here bytes32 name; // Human-readable name of the Asset as in ERC223 token standard bytes8 symbol; // Human-readable symbol of the Asset as in ERC223 token standard uint decimals; // Decimal, order of magnitude of precision, of the Asset as in ERC223 token standard string url; // URL for additional information of Asset string ipfsHash; // Same as url but for ipfs address breakIn; // Break in contract on destination chain address breakOut; // Break out contract on this chain; A way to leave uint[] standards; // compliance with standards like ERC20, ERC223, ERC777, etc. (the uint is the standard number) bytes4[] functionSignatures; // Whitelisted function signatures that can be called using `useExternalFunction` in Fund contract. Note: Adhere to a naming convention for `Fund<->Asset` as much as possible. I.e. name same concepts with the same functionSignature. uint price; // Price of asset quoted against `QUOTE_ASSET` * 10 ** decimals uint timestamp; // Timestamp of last price update of this asset } struct Exchange { bool exists; address adapter; // adapter contract for this exchange // One-time note: takesCustody is inverse case of isApproveOnly bool takesCustody; // True in case of exchange implementation which requires are approved when an order is made instead of transfer bytes4[] functionSignatures; // Whitelisted function signatures that can be called using `useExternalFunction` in Fund contract. Note: Adhere to a naming convention for `Fund<->ExchangeAdapter` as much as possible. I.e. name same concepts with the same functionSignature. } // TODO: populate each field here // TODO: add whitelistFunction function // FIELDS // Methods fields mapping (address => Asset) public assetInformation; address[] public registeredAssets; mapping (address => Exchange) public exchangeInformation; address[] public registeredExchanges; // METHODS // PUBLIC METHODS /// @notice Registers an Asset information entry /// @dev Pre: Only registrar owner should be able to register /// @dev Post: Address ofAsset is registered /// @param ofAsset Address of asset to be registered /// @param inputName Human-readable name of the Asset as in ERC223 token standard /// @param inputSymbol Human-readable symbol of the Asset as in ERC223 token standard /// @param inputDecimals Human-readable symbol of the Asset as in ERC223 token standard /// @param inputUrl Url for extended information of the asset /// @param inputIpfsHash Same as url but for ipfs /// @param breakInBreakOut Address of break in and break out contracts on destination chain /// @param inputStandards Integers of EIP standards this asset adheres to /// @param inputFunctionSignatures Function signatures for whitelisted asset functions function registerAsset( address ofAsset, bytes32 inputName, bytes8 inputSymbol, uint inputDecimals, string inputUrl, string inputIpfsHash, address[2] breakInBreakOut, uint[] inputStandards, bytes4[] inputFunctionSignatures ) auth pre_cond(!assetInformation[ofAsset].exists) { assetInformation[ofAsset].exists = true; registeredAssets.push(ofAsset); updateAsset( ofAsset, inputName, inputSymbol, inputDecimals, inputUrl, inputIpfsHash, breakInBreakOut, inputStandards, inputFunctionSignatures ); assert(assetInformation[ofAsset].exists); } /// @notice Register an exchange information entry /// @dev Pre: Only registrar owner should be able to register /// @dev Post: Address ofExchange is registered /// @param ofExchange Address of the exchange /// @param ofExchangeAdapter Address of exchange adapter for this exchange /// @param inputTakesCustody Whether this exchange takes custody of tokens before trading /// @param inputFunctionSignatures Function signatures for whitelisted exchange functions function registerExchange( address ofExchange, address ofExchangeAdapter, bool inputTakesCustody, bytes4[] inputFunctionSignatures ) auth pre_cond(!exchangeInformation[ofExchange].exists) { exchangeInformation[ofExchange].exists = true; registeredExchanges.push(ofExchange); updateExchange( ofExchange, ofExchangeAdapter, inputTakesCustody, inputFunctionSignatures ); assert(exchangeInformation[ofExchange].exists); } /// @notice Updates description information of a registered Asset /// @dev Pre: Owner can change an existing entry /// @dev Post: Changed Name, Symbol, URL and/or IPFSHash /// @param ofAsset Address of the asset to be updated /// @param inputName Human-readable name of the Asset as in ERC223 token standard /// @param inputSymbol Human-readable symbol of the Asset as in ERC223 token standard /// @param inputUrl Url for extended information of the asset /// @param inputIpfsHash Same as url but for ipfs function updateAsset( address ofAsset, bytes32 inputName, bytes8 inputSymbol, uint inputDecimals, string inputUrl, string inputIpfsHash, address[2] ofBreakInBreakOut, uint[] inputStandards, bytes4[] inputFunctionSignatures ) auth pre_cond(assetInformation[ofAsset].exists) { Asset asset = assetInformation[ofAsset]; asset.name = inputName; asset.symbol = inputSymbol; asset.decimals = inputDecimals; asset.url = inputUrl; asset.ipfsHash = inputIpfsHash; asset.breakIn = ofBreakInBreakOut[0]; asset.breakOut = ofBreakInBreakOut[1]; asset.standards = inputStandards; asset.functionSignatures = inputFunctionSignatures; } function updateExchange( address ofExchange, address ofExchangeAdapter, bool inputTakesCustody, bytes4[] inputFunctionSignatures ) auth pre_cond(exchangeInformation[ofExchange].exists) { Exchange exchange = exchangeInformation[ofExchange]; exchange.adapter = ofExchangeAdapter; exchange.takesCustody = inputTakesCustody; exchange.functionSignatures = inputFunctionSignatures; } // TODO: check max size of array before remaking this becomes untenable /// @notice Deletes an existing entry /// @dev Owner can delete an existing entry /// @param ofAsset address for which specific information is requested function removeAsset( address ofAsset, uint assetIndex ) auth pre_cond(assetInformation[ofAsset].exists) { require(registeredAssets[assetIndex] == ofAsset); delete assetInformation[ofAsset]; // Sets exists boolean to false delete registeredAssets[assetIndex]; for (uint i = assetIndex; i < registeredAssets.length-1; i++) { registeredAssets[i] = registeredAssets[i+1]; } registeredAssets.length--; assert(!assetInformation[ofAsset].exists); } /// @notice Deletes an existing entry /// @dev Owner can delete an existing entry /// @param ofExchange address for which specific information is requested /// @param exchangeIndex index of the exchange in array function removeExchange( address ofExchange, uint exchangeIndex ) auth pre_cond(exchangeInformation[ofExchange].exists) { require(registeredExchanges[exchangeIndex] == ofExchange); delete exchangeInformation[ofExchange]; delete registeredExchanges[exchangeIndex]; for (uint i = exchangeIndex; i < registeredExchanges.length-1; i++) { registeredExchanges[i] = registeredExchanges[i+1]; } registeredExchanges.length--; assert(!exchangeInformation[ofExchange].exists); } // PUBLIC VIEW METHODS // get asset specific information function getName(address ofAsset) view returns (bytes32) { return assetInformation[ofAsset].name; } function getSymbol(address ofAsset) view returns (bytes8) { return assetInformation[ofAsset].symbol; } function getDecimals(address ofAsset) view returns (uint) { return assetInformation[ofAsset].decimals; } function assetIsRegistered(address ofAsset) view returns (bool) { return assetInformation[ofAsset].exists; } function getRegisteredAssets() view returns (address[]) { return registeredAssets; } function assetMethodIsAllowed( address ofAsset, bytes4 querySignature ) returns (bool) { bytes4[] memory signatures = assetInformation[ofAsset].functionSignatures; for (uint i = 0; i < signatures.length; i++) { if (signatures[i] == querySignature) { return true; } } return false; } // get exchange-specific information function exchangeIsRegistered(address ofExchange) view returns (bool) { return exchangeInformation[ofExchange].exists; } function getRegisteredExchanges() view returns (address[]) { return registeredExchanges; } function getExchangeInformation(address ofExchange) view returns (address, bool) { Exchange exchange = exchangeInformation[ofExchange]; return ( exchange.adapter, exchange.takesCustody ); } function getExchangeFunctionSignatures(address ofExchange) view returns (bytes4[]) { return exchangeInformation[ofExchange].functionSignatures; } function exchangeMethodIsAllowed( address ofExchange, bytes4 querySignature ) returns (bool) { bytes4[] memory signatures = exchangeInformation[ofExchange].functionSignatures; for (uint i = 0; i < signatures.length; i++) { if (signatures[i] == querySignature) { return true; } } return false; } } interface SimplePriceFeedInterface { // EVENTS event PriceUpdated(bytes32 hash); // PUBLIC METHODS function update(address[] ofAssets, uint[] newPrices) external; // PUBLIC VIEW METHODS // Get price feed operation specific information function getQuoteAsset() view returns (address); function getLastUpdateId() view returns (uint); // Get asset specific information as updated in price feed function getPrice(address ofAsset) view returns (uint price, uint timestamp); function getPrices(address[] ofAssets) view returns (uint[] prices, uint[] timestamps); } contract SimplePriceFeed is SimplePriceFeedInterface, DSThing, DBC { // TYPES struct Data { uint price; uint timestamp; } // FIELDS mapping(address => Data) public assetsToPrices; // Constructor fields address public QUOTE_ASSET; // Asset of a portfolio against which all other assets are priced // Contract-level variables uint public updateId; // Update counter for this pricefeed; used as a check during investment CanonicalRegistrar public registrar; CanonicalPriceFeed public superFeed; // METHODS // CONSTRUCTOR /// @param ofQuoteAsset Address of quote asset /// @param ofRegistrar Address of canonical registrar /// @param ofSuperFeed Address of superfeed function SimplePriceFeed( address ofRegistrar, address ofQuoteAsset, address ofSuperFeed ) { registrar = CanonicalRegistrar(ofRegistrar); QUOTE_ASSET = ofQuoteAsset; superFeed = CanonicalPriceFeed(ofSuperFeed); } // EXTERNAL METHODS /// @dev Only Owner; Same sized input arrays /// @dev Updates price of asset relative to QUOTE_ASSET /** Ex: * Let QUOTE_ASSET == MLN (base units), let asset == EUR-T, * let Value of 1 EUR-T := 1 EUR == 0.080456789 MLN, hence price 0.080456789 MLN / EUR-T * and let EUR-T decimals == 8. * Input would be: information[EUR-T].price = 8045678 [MLN/ (EUR-T * 10**8)] */ /// @param ofAssets list of asset addresses /// @param newPrices list of prices for each of the assets function update(address[] ofAssets, uint[] newPrices) external auth { _updatePrices(ofAssets, newPrices); } // PUBLIC VIEW METHODS // Get pricefeed specific information function getQuoteAsset() view returns (address) { return QUOTE_ASSET; } function getLastUpdateId() view returns (uint) { return updateId; } /** @notice Gets price of an asset multiplied by ten to the power of assetDecimals @dev Asset has been registered @param ofAsset Asset for which price should be returned @return { "price": "Price formatting: mul(exchangePrice, 10 ** decimal), to avoid floating numbers", "timestamp": "When the asset's price was updated" } */ function getPrice(address ofAsset) view returns (uint price, uint timestamp) { Data data = assetsToPrices[ofAsset]; return (data.price, data.timestamp); } /** @notice Price of a registered asset in format (bool areRecent, uint[] prices, uint[] decimals) @dev Convention for price formatting: mul(price, 10 ** decimal), to avoid floating numbers @param ofAssets Assets for which prices should be returned @return { "prices": "Array of prices", "timestamps": "Array of timestamps", } */ function getPrices(address[] ofAssets) view returns (uint[], uint[]) { uint[] memory prices = new uint[](ofAssets.length); uint[] memory timestamps = new uint[](ofAssets.length); for (uint i; i < ofAssets.length; i++) { var (price, timestamp) = getPrice(ofAssets[i]); prices[i] = price; timestamps[i] = timestamp; } return (prices, timestamps); } // INTERNAL METHODS /// @dev Internal so that feeds inheriting this one are not obligated to have an exposed update(...) method, but can still perform updates function _updatePrices(address[] ofAssets, uint[] newPrices) internal pre_cond(ofAssets.length == newPrices.length) { updateId++; for (uint i = 0; i < ofAssets.length; ++i) { require(registrar.assetIsRegistered(ofAssets[i])); require(assetsToPrices[ofAssets[i]].timestamp != now); // prevent two updates in one block assetsToPrices[ofAssets[i]].timestamp = now; assetsToPrices[ofAssets[i]].price = newPrices[i]; } emit PriceUpdated(keccak256(ofAssets, newPrices)); } } contract StakingPriceFeed is SimplePriceFeed { OperatorStaking public stakingContract; AssetInterface public stakingToken; // CONSTRUCTOR /// @param ofQuoteAsset Address of quote asset /// @param ofRegistrar Address of canonical registrar /// @param ofSuperFeed Address of superfeed function StakingPriceFeed( address ofRegistrar, address ofQuoteAsset, address ofSuperFeed ) SimplePriceFeed(ofRegistrar, ofQuoteAsset, ofSuperFeed) { stakingContract = OperatorStaking(ofSuperFeed); // canonical feed *is* staking contract stakingToken = AssetInterface(stakingContract.stakingToken()); } // EXTERNAL METHODS /// @param amount Number of tokens to stake for this feed /// @param data Data may be needed for some future applications (can be empty for now) function depositStake(uint amount, bytes data) external auth { require(stakingToken.transferFrom(msg.sender, address(this), amount)); require(stakingToken.approve(stakingContract, amount)); stakingContract.stake(amount, data); } /// @param amount Number of tokens to unstake for this feed /// @param data Data may be needed for some future applications (can be empty for now) function unstake(uint amount, bytes data) external auth { stakingContract.unstake(amount, data); } function withdrawStake() external auth { uint amountToWithdraw = stakingContract.stakeToWithdraw(address(this)); stakingContract.withdrawStake(); require(stakingToken.transfer(msg.sender, amountToWithdraw)); } } interface RiskMgmtInterface { // METHODS // PUBLIC VIEW METHODS /// @notice Checks if the makeOrder price is reasonable and not manipulative /// @param orderPrice Price of Order /// @param referencePrice Reference price obtained through PriceFeed contract /// @param sellAsset Asset (as registered in Asset registrar) to be sold /// @param buyAsset Asset (as registered in Asset registrar) to be bought /// @param sellQuantity Quantity of sellAsset to be sold /// @param buyQuantity Quantity of buyAsset to be bought /// @return If makeOrder is permitted function isMakePermitted( uint orderPrice, uint referencePrice, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (bool); /// @notice Checks if the takeOrder price is reasonable and not manipulative /// @param orderPrice Price of Order /// @param referencePrice Reference price obtained through PriceFeed contract /// @param sellAsset Asset (as registered in Asset registrar) to be sold /// @param buyAsset Asset (as registered in Asset registrar) to be bought /// @param sellQuantity Quantity of sellAsset to be sold /// @param buyQuantity Quantity of buyAsset to be bought /// @return If takeOrder is permitted function isTakePermitted( uint orderPrice, uint referencePrice, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (bool); } contract OperatorStaking is DBC { // EVENTS event Staked(address indexed user, uint256 amount, uint256 total, bytes data); event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data); event StakeBurned(address indexed user, uint256 amount, bytes data); // TYPES struct StakeData { uint amount; address staker; } // Circular linked list struct Node { StakeData data; uint prev; uint next; } // FIELDS // INTERNAL FIELDS Node[] internal stakeNodes; // Sorted circular linked list nodes containing stake data (Built on top https://programtheblockchain.com/posts/2018/03/30/storage-patterns-doubly-linked-list/) // PUBLIC FIELDS uint public minimumStake; uint public numOperators; uint public withdrawalDelay; mapping (address => bool) public isRanked; mapping (address => uint) public latestUnstakeTime; mapping (address => uint) public stakeToWithdraw; mapping (address => uint) public stakedAmounts; uint public numStakers; // Current number of stakers (Needed because of array holes) AssetInterface public stakingToken; // TODO: consider renaming "operator" depending on how this is implemented // (i.e. is pricefeed staking itself?) function OperatorStaking( AssetInterface _stakingToken, uint _minimumStake, uint _numOperators, uint _withdrawalDelay ) public { require(address(_stakingToken) != address(0)); stakingToken = _stakingToken; minimumStake = _minimumStake; numOperators = _numOperators; withdrawalDelay = _withdrawalDelay; StakeData memory temp = StakeData({ amount: 0, staker: address(0) }); stakeNodes.push(Node(temp, 0, 0)); } // METHODS : STAKING function stake( uint amount, bytes data ) public pre_cond(amount >= minimumStake) { stakedAmounts[msg.sender] += amount; updateStakerRanking(msg.sender); require(stakingToken.transferFrom(msg.sender, address(this), amount)); } function unstake( uint amount, bytes data ) public { uint preStake = stakedAmounts[msg.sender]; uint postStake = preStake - amount; require(postStake >= minimumStake || postStake == 0); require(stakedAmounts[msg.sender] >= amount); latestUnstakeTime[msg.sender] = block.timestamp; stakedAmounts[msg.sender] -= amount; stakeToWithdraw[msg.sender] += amount; updateStakerRanking(msg.sender); emit Unstaked(msg.sender, amount, stakedAmounts[msg.sender], data); } function withdrawStake() public pre_cond(stakeToWithdraw[msg.sender] > 0) pre_cond(block.timestamp >= latestUnstakeTime[msg.sender] + withdrawalDelay) { uint amount = stakeToWithdraw[msg.sender]; stakeToWithdraw[msg.sender] = 0; require(stakingToken.transfer(msg.sender, amount)); } // VIEW FUNCTIONS function isValidNode(uint id) view returns (bool) { // 0 is a sentinel and therefore invalid. // A valid node is the head or has a previous node. return id != 0 && (id == stakeNodes[0].next || stakeNodes[id].prev != 0); } function searchNode(address staker) view returns (uint) { uint current = stakeNodes[0].next; while (isValidNode(current)) { if (staker == stakeNodes[current].data.staker) { return current; } current = stakeNodes[current].next; } return 0; } function isOperator(address user) view returns (bool) { address[] memory operators = getOperators(); for (uint i; i < operators.length; i++) { if (operators[i] == user) { return true; } } return false; } function getOperators() view returns (address[]) { uint arrLength = (numOperators > numStakers) ? numStakers : numOperators; address[] memory operators = new address[](arrLength); uint current = stakeNodes[0].next; for (uint i; i < arrLength; i++) { operators[i] = stakeNodes[current].data.staker; current = stakeNodes[current].next; } return operators; } function getStakersAndAmounts() view returns (address[], uint[]) { address[] memory stakers = new address[](numStakers); uint[] memory amounts = new uint[](numStakers); uint current = stakeNodes[0].next; for (uint i; i < numStakers; i++) { stakers[i] = stakeNodes[current].data.staker; amounts[i] = stakeNodes[current].data.amount; current = stakeNodes[current].next; } return (stakers, amounts); } function totalStakedFor(address user) view returns (uint) { return stakedAmounts[user]; } // INTERNAL METHODS // DOUBLY-LINKED LIST function insertNodeSorted(uint amount, address staker) internal returns (uint) { uint current = stakeNodes[0].next; if (current == 0) return insertNodeAfter(0, amount, staker); while (isValidNode(current)) { if (amount > stakeNodes[current].data.amount) { break; } current = stakeNodes[current].next; } return insertNodeBefore(current, amount, staker); } function insertNodeAfter(uint id, uint amount, address staker) internal returns (uint newID) { // 0 is allowed here to insert at the beginning. require(id == 0 || isValidNode(id)); Node storage node = stakeNodes[id]; stakeNodes.push(Node({ data: StakeData(amount, staker), prev: id, next: node.next })); newID = stakeNodes.length - 1; stakeNodes[node.next].prev = newID; node.next = newID; numStakers++; } function insertNodeBefore(uint id, uint amount, address staker) internal returns (uint) { return insertNodeAfter(stakeNodes[id].prev, amount, staker); } function removeNode(uint id) internal { require(isValidNode(id)); Node storage node = stakeNodes[id]; stakeNodes[node.next].prev = node.prev; stakeNodes[node.prev].next = node.next; delete stakeNodes[id]; numStakers--; } // UPDATING OPERATORS function updateStakerRanking(address _staker) internal { uint newStakedAmount = stakedAmounts[_staker]; if (newStakedAmount == 0) { isRanked[_staker] = false; removeStakerFromArray(_staker); } else if (isRanked[_staker]) { removeStakerFromArray(_staker); insertNodeSorted(newStakedAmount, _staker); } else { isRanked[_staker] = true; insertNodeSorted(newStakedAmount, _staker); } } function removeStakerFromArray(address _staker) internal { uint id = searchNode(_staker); require(id > 0); removeNode(id); } } contract CanonicalPriceFeed is OperatorStaking, SimplePriceFeed, CanonicalRegistrar { // EVENTS event SetupPriceFeed(address ofPriceFeed); struct HistoricalPrices { address[] assets; uint[] prices; uint timestamp; } // FIELDS bool public updatesAreAllowed = true; uint public minimumPriceCount = 1; uint public VALIDITY; uint public INTERVAL; mapping (address => bool) public isStakingFeed; // If the Staking Feed has been created through this contract HistoricalPrices[] public priceHistory; // METHODS // CONSTRUCTOR /// @dev Define and register a quote asset against which all prices are measured/based against /// @param ofStakingAsset Address of staking asset (may or may not be quoteAsset) /// @param ofQuoteAsset Address of quote asset /// @param quoteAssetName Name of quote asset /// @param quoteAssetSymbol Symbol for quote asset /// @param quoteAssetDecimals Decimal places for quote asset /// @param quoteAssetUrl URL related to quote asset /// @param quoteAssetIpfsHash IPFS hash associated with quote asset /// @param quoteAssetBreakInBreakOut Break-in/break-out for quote asset on destination chain /// @param quoteAssetStandards EIP standards quote asset adheres to /// @param quoteAssetFunctionSignatures Whitelisted functions of quote asset contract // /// @param interval Number of seconds between pricefeed updates (this interval is not enforced on-chain, but should be followed by the datafeed maintainer) // /// @param validity Number of seconds that datafeed update information is valid for /// @param ofGovernance Address of contract governing the Canonical PriceFeed function CanonicalPriceFeed( address ofStakingAsset, address ofQuoteAsset, // Inital entry in asset registrar contract is Melon (QUOTE_ASSET) bytes32 quoteAssetName, bytes8 quoteAssetSymbol, uint quoteAssetDecimals, string quoteAssetUrl, string quoteAssetIpfsHash, address[2] quoteAssetBreakInBreakOut, uint[] quoteAssetStandards, bytes4[] quoteAssetFunctionSignatures, uint[2] updateInfo, // interval, validity uint[3] stakingInfo, // minStake, numOperators, unstakeDelay address ofGovernance ) OperatorStaking( AssetInterface(ofStakingAsset), stakingInfo[0], stakingInfo[1], stakingInfo[2] ) SimplePriceFeed(address(this), ofQuoteAsset, address(0)) { registerAsset( ofQuoteAsset, quoteAssetName, quoteAssetSymbol, quoteAssetDecimals, quoteAssetUrl, quoteAssetIpfsHash, quoteAssetBreakInBreakOut, quoteAssetStandards, quoteAssetFunctionSignatures ); INTERVAL = updateInfo[0]; VALIDITY = updateInfo[1]; setOwner(ofGovernance); } // EXTERNAL METHODS /// @notice Create a new StakingPriceFeed function setupStakingPriceFeed() external { address ofStakingPriceFeed = new StakingPriceFeed( address(this), stakingToken, address(this) ); isStakingFeed[ofStakingPriceFeed] = true; StakingPriceFeed(ofStakingPriceFeed).setOwner(msg.sender); emit SetupPriceFeed(ofStakingPriceFeed); } /// @dev override inherited update function to prevent manual update from authority function update(address[] ofAssets, uint[] newPrices) external { revert(); } /// @dev Burn state for a pricefeed operator /// @param user Address of pricefeed operator to burn the stake from function burnStake(address user) external auth { uint totalToBurn = add(stakedAmounts[user], stakeToWithdraw[user]); stakedAmounts[user] = 0; stakeToWithdraw[user] = 0; updateStakerRanking(user); emit StakeBurned(user, totalToBurn, ""); } // PUBLIC METHODS // STAKING function stake( uint amount, bytes data ) public pre_cond(isStakingFeed[msg.sender]) { OperatorStaking.stake(amount, data); } // function stakeFor( // address user, // uint amount, // bytes data // ) // public // pre_cond(isStakingFeed[user]) // { // OperatorStaking.stakeFor(user, amount, data); // } // AGGREGATION /// @dev Only Owner; Same sized input arrays /// @dev Updates price of asset relative to QUOTE_ASSET /** Ex: * Let QUOTE_ASSET == MLN (base units), let asset == EUR-T, * let Value of 1 EUR-T := 1 EUR == 0.080456789 MLN, hence price 0.080456789 MLN / EUR-T * and let EUR-T decimals == 8. * Input would be: information[EUR-T].price = 8045678 [MLN/ (EUR-T * 10**8)] */ /// @param ofAssets list of asset addresses function collectAndUpdate(address[] ofAssets) public auth pre_cond(updatesAreAllowed) { uint[] memory newPrices = pricesToCommit(ofAssets); priceHistory.push( HistoricalPrices({assets: ofAssets, prices: newPrices, timestamp: block.timestamp}) ); _updatePrices(ofAssets, newPrices); } function pricesToCommit(address[] ofAssets) view returns (uint[]) { address[] memory operators = getOperators(); uint[] memory newPrices = new uint[](ofAssets.length); for (uint i = 0; i < ofAssets.length; i++) { uint[] memory assetPrices = new uint[](operators.length); for (uint j = 0; j < operators.length; j++) { SimplePriceFeed feed = SimplePriceFeed(operators[j]); var (price, timestamp) = feed.assetsToPrices(ofAssets[i]); if (now > add(timestamp, VALIDITY)) { continue; // leaves a zero in the array (dealt with later) } assetPrices[j] = price; } newPrices[i] = medianize(assetPrices); } return newPrices; } /// @dev from MakerDao medianizer contract function medianize(uint[] unsorted) view returns (uint) { uint numValidEntries; for (uint i = 0; i < unsorted.length; i++) { if (unsorted[i] != 0) { numValidEntries++; } } if (numValidEntries < minimumPriceCount) { revert(); } uint counter; uint[] memory out = new uint[](numValidEntries); for (uint j = 0; j < unsorted.length; j++) { uint item = unsorted[j]; if (item != 0) { // skip zero (invalid) entries if (counter == 0 || item >= out[counter - 1]) { out[counter] = item; // item is larger than last in array (we are home) } else { uint k = 0; while (item >= out[k]) { k++; // get to where element belongs (between smaller and larger items) } for (uint m = counter; m > k; m--) { out[m] = out[m - 1]; // bump larger elements rightward to leave slot } out[k] = item; } counter++; } } uint value; if (counter % 2 == 0) { uint value1 = uint(out[(counter / 2) - 1]); uint value2 = uint(out[(counter / 2)]); value = add(value1, value2) / 2; } else { value = out[(counter - 1) / 2]; } return value; } function setMinimumPriceCount(uint newCount) auth { minimumPriceCount = newCount; } function enableUpdates() auth { updatesAreAllowed = true; } function disableUpdates() auth { updatesAreAllowed = false; } // PUBLIC VIEW METHODS // FEED INFORMATION function getQuoteAsset() view returns (address) { return QUOTE_ASSET; } function getInterval() view returns (uint) { return INTERVAL; } function getValidity() view returns (uint) { return VALIDITY; } function getLastUpdateId() view returns (uint) { return updateId; } // PRICES /// @notice Whether price of asset has been updated less than VALIDITY seconds ago /// @param ofAsset Asset in registrar /// @return isRecent Price information ofAsset is recent function hasRecentPrice(address ofAsset) view pre_cond(assetIsRegistered(ofAsset)) returns (bool isRecent) { var ( , timestamp) = getPrice(ofAsset); return (sub(now, timestamp) <= VALIDITY); } /// @notice Whether prices of assets have been updated less than VALIDITY seconds ago /// @param ofAssets All assets in registrar /// @return isRecent Price information ofAssets array is recent function hasRecentPrices(address[] ofAssets) view returns (bool areRecent) { for (uint i; i < ofAssets.length; i++) { if (!hasRecentPrice(ofAssets[i])) { return false; } } return true; } function getPriceInfo(address ofAsset) view returns (bool isRecent, uint price, uint assetDecimals) { isRecent = hasRecentPrice(ofAsset); (price, ) = getPrice(ofAsset); assetDecimals = getDecimals(ofAsset); } /** @notice Gets inverted price of an asset @dev Asset has been initialised and its price is non-zero @dev Existing price ofAssets quoted in QUOTE_ASSET (convention) @param ofAsset Asset for which inverted price should be return @return { "isRecent": "Whether the price is fresh, given VALIDITY interval", "invertedPrice": "Price based (instead of quoted) against QUOTE_ASSET", "assetDecimals": "Decimal places for this asset" } */ function getInvertedPriceInfo(address ofAsset) view returns (bool isRecent, uint invertedPrice, uint assetDecimals) { uint inputPrice; // inputPrice quoted in QUOTE_ASSET and multiplied by 10 ** assetDecimal (isRecent, inputPrice, assetDecimals) = getPriceInfo(ofAsset); // outputPrice based in QUOTE_ASSET and multiplied by 10 ** quoteDecimal uint quoteDecimals = getDecimals(QUOTE_ASSET); return ( isRecent, mul(10 ** uint(quoteDecimals), 10 ** uint(assetDecimals)) / inputPrice, quoteDecimals // TODO: check on this; shouldn't it be assetDecimals? ); } /** @notice Gets reference price of an asset pair @dev One of the address is equal to quote asset @dev either ofBase == QUOTE_ASSET or ofQuote == QUOTE_ASSET @param ofBase Address of base asset @param ofQuote Address of quote asset @return { "isRecent": "Whether the price is fresh, given VALIDITY interval", "referencePrice": "Reference price", "decimal": "Decimal places for this asset" } */ function getReferencePriceInfo(address ofBase, address ofQuote) view returns (bool isRecent, uint referencePrice, uint decimal) { if (getQuoteAsset() == ofQuote) { (isRecent, referencePrice, decimal) = getPriceInfo(ofBase); } else if (getQuoteAsset() == ofBase) { (isRecent, referencePrice, decimal) = getInvertedPriceInfo(ofQuote); } else { revert(); // no suitable reference price available } } /// @notice Gets price of Order /// @param sellAsset Address of the asset to be sold /// @param buyAsset Address of the asset to be bought /// @param sellQuantity Quantity in base units being sold of sellAsset /// @param buyQuantity Quantity in base units being bought of buyAsset /// @return orderPrice Price as determined by an order function getOrderPriceInfo( address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (uint orderPrice) { return mul(buyQuantity, 10 ** uint(getDecimals(sellAsset))) / sellQuantity; } /// @notice Checks whether data exists for a given asset pair /// @dev Prices are only upated against QUOTE_ASSET /// @param sellAsset Asset for which check to be done if data exists /// @param buyAsset Asset for which check to be done if data exists /// @return Whether assets exist for given asset pair function existsPriceOnAssetPair(address sellAsset, address buyAsset) view returns (bool isExistent) { return hasRecentPrice(sellAsset) && // Is tradable asset (TODO cleaner) and datafeed delivering data hasRecentPrice(buyAsset) && // Is tradable asset (TODO cleaner) and datafeed delivering data (buyAsset == QUOTE_ASSET || sellAsset == QUOTE_ASSET) && // One asset must be QUOTE_ASSET (buyAsset != QUOTE_ASSET || sellAsset != QUOTE_ASSET); // Pair must consists of diffrent assets } /// @return Sparse array of addresses of owned pricefeeds function getPriceFeedsByOwner(address _owner) view returns(address[]) { address[] memory ofPriceFeeds = new address[](numStakers); if (numStakers == 0) return ofPriceFeeds; uint current = stakeNodes[0].next; for (uint i; i < numStakers; i++) { StakingPriceFeed stakingFeed = StakingPriceFeed(stakeNodes[current].data.staker); if (stakingFeed.owner() == _owner) { ofPriceFeeds[i] = address(stakingFeed); } current = stakeNodes[current].next; } return ofPriceFeeds; } function getHistoryLength() returns (uint) { return priceHistory.length; } function getHistoryAt(uint id) returns (address[], uint[], uint) { address[] memory assets = priceHistory[id].assets; uint[] memory prices = priceHistory[id].prices; uint timestamp = priceHistory[id].timestamp; return (assets, prices, timestamp); } } interface VersionInterface { // EVENTS event FundUpdated(uint id); // PUBLIC METHODS function shutDown() external; function setupFund( bytes32 ofFundName, address ofQuoteAsset, uint ofManagementFee, uint ofPerformanceFee, address ofCompliance, address ofRiskMgmt, address[] ofExchanges, address[] ofDefaultAssets, uint8 v, bytes32 r, bytes32 s ); function shutDownFund(address ofFund); // PUBLIC VIEW METHODS function getNativeAsset() view returns (address); function getFundById(uint withId) view returns (address); function getLastFundId() view returns (uint); function getFundByManager(address ofManager) view returns (address); function termsAndConditionsAreSigned(uint8 v, bytes32 r, bytes32 s) view returns (bool signed); } contract Version is DBC, Owned, VersionInterface { // FIELDS bytes32 public constant TERMS_AND_CONDITIONS = 0xAA9C907B0D6B4890E7225C09CBC16A01CB97288840201AA7CDCB27F4ED7BF159; // Hashed terms and conditions as displayed on IPFS, decoded from base 58 // Constructor fields string public VERSION_NUMBER; // SemVer of Melon protocol version address public MELON_ASSET; // Address of Melon asset contract address public NATIVE_ASSET; // Address of Fixed quote asset address public GOVERNANCE; // Address of Melon protocol governance contract address public CANONICAL_PRICEFEED; // Address of the canonical pricefeed // Methods fields bool public isShutDown; // Governance feature, if yes than setupFund gets blocked and shutDownFund gets opened address public COMPLIANCE; // restrict to Competition compliance module for this version address[] public listOfFunds; // A complete list of fund addresses created using this version mapping (address => address) public managerToFunds; // Links manager address to fund address created using this version // EVENTS event FundUpdated(address ofFund); // METHODS // CONSTRUCTOR /// @param versionNumber SemVer of Melon protocol version /// @param ofGovernance Address of Melon governance contract /// @param ofMelonAsset Address of Melon asset contract function Version( string versionNumber, address ofGovernance, address ofMelonAsset, address ofNativeAsset, address ofCanonicalPriceFeed, address ofCompetitionCompliance ) { VERSION_NUMBER = versionNumber; GOVERNANCE = ofGovernance; MELON_ASSET = ofMelonAsset; NATIVE_ASSET = ofNativeAsset; CANONICAL_PRICEFEED = ofCanonicalPriceFeed; COMPLIANCE = ofCompetitionCompliance; } // EXTERNAL METHODS function shutDown() external pre_cond(msg.sender == GOVERNANCE) { isShutDown = true; } // PUBLIC METHODS /// @param ofFundName human-readable descriptive name (not necessarily unique) /// @param ofQuoteAsset Asset against which performance fee is measured against /// @param ofManagementFee A time based fee, given in a number which is divided by 10 ** 15 /// @param ofPerformanceFee A time performance based fee, performance relative to ofQuoteAsset, given in a number which is divided by 10 ** 15 /// @param ofCompliance Address of participation module /// @param ofRiskMgmt Address of risk management module /// @param ofExchanges Addresses of exchange on which this fund can trade /// @param ofDefaultAssets Enable invest/redeem with these assets (quote asset already enabled) /// @param v ellipitc curve parameter v /// @param r ellipitc curve parameter r /// @param s ellipitc curve parameter s function setupFund( bytes32 ofFundName, address ofQuoteAsset, uint ofManagementFee, uint ofPerformanceFee, address ofCompliance, address ofRiskMgmt, address[] ofExchanges, address[] ofDefaultAssets, uint8 v, bytes32 r, bytes32 s ) { require(!isShutDown); require(termsAndConditionsAreSigned(v, r, s)); require(CompetitionCompliance(COMPLIANCE).isCompetitionAllowed(msg.sender)); require(managerToFunds[msg.sender] == address(0)); // Add limitation for simpler migration process of shutting down and setting up fund address[] memory melonAsDefaultAsset = new address[](1); melonAsDefaultAsset[0] = MELON_ASSET; // Melon asset should be in default assets address ofFund = new Fund( msg.sender, ofFundName, NATIVE_ASSET, 0, 0, COMPLIANCE, ofRiskMgmt, CANONICAL_PRICEFEED, ofExchanges, melonAsDefaultAsset ); listOfFunds.push(ofFund); managerToFunds[msg.sender] = ofFund; emit FundUpdated(ofFund); } /// @dev Dereference Fund and shut it down /// @param ofFund Address of the fund to be shut down function shutDownFund(address ofFund) pre_cond(isShutDown || managerToFunds[msg.sender] == ofFund) { Fund fund = Fund(ofFund); delete managerToFunds[msg.sender]; fund.shutDown(); emit FundUpdated(ofFund); } // PUBLIC VIEW METHODS /// @dev Proof that terms and conditions have been read and understood /// @param v ellipitc curve parameter v /// @param r ellipitc curve parameter r /// @param s ellipitc curve parameter s /// @return signed Whether or not terms and conditions have been read and understood function termsAndConditionsAreSigned(uint8 v, bytes32 r, bytes32 s) view returns (bool signed) { return ecrecover( // Parity does prepend \x19Ethereum Signed Message:\n{len(message)} before signing. // Signature order has also been changed in 1.6.7 and upcoming 1.7.x, // it will return rsv (same as geth; where v is [27, 28]). // Note that if you are using ecrecover, v will be either "00" or "01". // As a result, in order to use this value, you will have to parse it to an // integer and then add 27. This will result in either a 27 or a 28. // https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethsign keccak256("\x19Ethereum Signed Message:\n32", TERMS_AND_CONDITIONS), v, r, s ) == msg.sender; // Has sender signed TERMS_AND_CONDITIONS } function getNativeAsset() view returns (address) { return NATIVE_ASSET; } function getFundById(uint withId) view returns (address) { return listOfFunds[withId]; } function getLastFundId() view returns (uint) { return listOfFunds.length - 1; } function getFundByManager(address ofManager) view returns (address) { return managerToFunds[ofManager]; } }
If the Staking Feed has been created through this contract
mapping (address => bool) public isStakingFeed;
196,344
[ 1, 2047, 326, 934, 6159, 14013, 711, 2118, 2522, 3059, 333, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 353, 510, 6159, 8141, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x78a486306D15E7111cca541F2f1307a1cFCaF5C4/sources/contracts/IPeronioSupport.sol
--- USDC ---------------------------------------------------------------------------------------------------------------------------------------------------
function add(UsdcQuantity left, UsdcQuantity right) pure returns (UsdcQuantity) { return UsdcQuantity.wrap(UsdcQuantity.unwrap(left) + UsdcQuantity.unwrap(right)); import {Math} from "@openzeppelin/contracts_latest/utils/math/Math.sol"; }
4,798,475
[ 1, 6062, 11836, 5528, 8879, 28253, 413, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 915, 527, 12, 3477, 7201, 12035, 2002, 16, 587, 6427, 71, 12035, 2145, 13, 16618, 1135, 261, 3477, 7201, 12035, 13, 288, 203, 565, 327, 587, 6427, 71, 12035, 18, 4113, 12, 3477, 7201, 12035, 18, 318, 4113, 12, 4482, 13, 397, 587, 6427, 71, 12035, 18, 318, 4113, 12, 4083, 10019, 203, 203, 5666, 288, 10477, 97, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 67, 13550, 19, 5471, 19, 15949, 19, 10477, 18, 18281, 14432, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/8453/0xa794a8B344601e8aDe9CB359C904776809ECaa9E/sources/contracts/protocol/extensions/adapters/AUniswap.sol
@inheritdoc IAUniswap we swap the tokens
function exactInput(ISwapRouter02.ExactInputParams calldata params) external override returns (uint256 amountOut) { (address tokenIn, address tokenOut) = _decodePathTokens(params.path); address uniswapRouter = _preSwap(tokenIn, tokenOut); amountOut = ISwapRouter02(uniswapRouter).exactInput( IV3SwapRouter.ExactInputParams({ path: params.path, amountIn: params.amountIn, amountOutMinimum: params.amountOutMinimum }) ); }
11,548,121
[ 1, 36, 10093, 467, 37, 984, 291, 91, 438, 732, 7720, 326, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5565, 1210, 12, 5127, 91, 438, 8259, 3103, 18, 14332, 1210, 1370, 745, 892, 859, 13, 3903, 3849, 1135, 261, 11890, 5034, 3844, 1182, 13, 288, 203, 3639, 261, 2867, 1147, 382, 16, 1758, 1147, 1182, 13, 273, 389, 3922, 743, 5157, 12, 2010, 18, 803, 1769, 203, 3639, 1758, 640, 291, 91, 438, 8259, 273, 389, 1484, 12521, 12, 2316, 382, 16, 1147, 1182, 1769, 203, 203, 3639, 3844, 1182, 273, 4437, 91, 438, 8259, 3103, 12, 318, 291, 91, 438, 8259, 2934, 17165, 1210, 12, 203, 5411, 21602, 23, 12521, 8259, 18, 14332, 1210, 1370, 12590, 203, 7734, 589, 30, 859, 18, 803, 16, 203, 7734, 3844, 382, 30, 859, 18, 8949, 382, 16, 203, 7734, 3844, 1182, 13042, 30, 859, 18, 8949, 1182, 13042, 203, 5411, 289, 13, 203, 3639, 11272, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0-only /* AdminEscrow.sol - SKALE Allocator Copyright (C) 2020-Present SKALE Labs @author Artem Payvin SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Escrow.sol"; contract AdminEscrow is Escrow { address public constant ADMIN = address(0x4165CCb2ab09AC00Bb40C66FB296baCa183F899f); modifier onlyBeneficiary() override { require(_msgSender() == _beneficiary || _msgSender() == ADMIN, "Message sender is not a plan beneficiary"); _; } modifier onlyActiveBeneficiaryOrVestingManager() override { Allocator allocator = Allocator(contractManager.getContract("Allocator")); if (allocator.isVestingActive(_beneficiary)) { require(_msgSender() == _beneficiary || _msgSender() == ADMIN, "Message sender is not beneficiary"); } else { require( allocator.hasRole(allocator.VESTING_MANAGER_ROLE(), _msgSender()), "Message sender is not authorized" ); } _; } } // SPDX-License-Identifier: AGPL-3.0-only /* Escrow.sol - SKALE Allocator Copyright (C) 2020-Present SKALE Labs @author Artem Payvin SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Sender.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "./interfaces/delegation/IDelegationController.sol"; import "./interfaces/delegation/IDistributor.sol"; import "./interfaces/delegation/ITokenState.sol"; import "./Allocator.sol"; import "./Permissions.sol"; /** * @title Escrow * @dev This contract manages funds locked by the Allocator contract. */ contract Escrow is IERC777Recipient, IERC777Sender, Permissions { address internal _beneficiary; uint256 private _availableAmountAfterTermination; IERC1820Registry private _erc1820; modifier onlyBeneficiary() virtual { require(_msgSender() == _beneficiary, "Message sender is not a plan beneficiary"); _; } modifier onlyVestingManager() { Allocator allocator = Allocator(contractManager.getContract("Allocator")); require( allocator.hasRole(allocator.VESTING_MANAGER_ROLE(), _msgSender()), "Message sender is not a vesting manager" ); _; } modifier onlyActiveBeneficiaryOrVestingManager() virtual { Allocator allocator = Allocator(contractManager.getContract("Allocator")); if (allocator.isVestingActive(_beneficiary)) { require(_msgSender() == _beneficiary, "Message sender is not beneficiary"); } else { require( allocator.hasRole(allocator.VESTING_MANAGER_ROLE(), _msgSender()), "Message sender is not authorized" ); } _; } function initialize(address contractManagerAddress, address beneficiary) external initializer { require(beneficiary != address(0), "Beneficiary address is not set"); Permissions.initialize(contractManagerAddress); _beneficiary = beneficiary; _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensSender"), address(this)); } function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleToken") // solhint-disable-next-line no-empty-blocks { } function tokensToSend( address, address, address to, uint256, bytes calldata, bytes calldata ) external override allow("SkaleToken") // solhint-disable-next-line no-empty-blocks { } /** * @dev Allows Beneficiary to retrieve vested tokens from the Escrow contract. * * IMPORTANT: Slashed tokens are non-transferable. */ function retrieve() external onlyBeneficiary { Allocator allocator = Allocator(contractManager.getContract("Allocator")); ITokenState tokenState = ITokenState(contractManager.getContract("TokenState")); uint256 vestedAmount = 0; if (allocator.isVestingActive(_beneficiary)) { vestedAmount = allocator.calculateVestedAmount(_beneficiary); } else { vestedAmount = _availableAmountAfterTermination; } uint256 escrowBalance = IERC20(contractManager.getContract("SkaleToken")).balanceOf(address(this)); uint256 locked = Math.max( allocator.getFullAmount(_beneficiary).sub(vestedAmount), tokenState.getAndUpdateForbiddenForDelegationAmount(address(this)) ); if (escrowBalance > locked) { require( IERC20(contractManager.getContract("SkaleToken")).transfer( _beneficiary, escrowBalance.sub(locked) ), "Error of token send" ); } } /** * @dev Allows Vesting Manager to retrieve remaining transferrable escrow balance * after beneficiary's termination. * * IMPORTANT: Slashed tokens are non-transferable. * * Requirements: * * - Allocator must be active. */ function retrieveAfterTermination(address destination) external onlyVestingManager { Allocator allocator = Allocator(contractManager.getContract("Allocator")); ITokenState tokenState = ITokenState(contractManager.getContract("TokenState")); require(destination != address(0), "Destination address is not set"); require(!allocator.isVestingActive(_beneficiary), "Vesting is active"); uint256 escrowBalance = IERC20(contractManager.getContract("SkaleToken")).balanceOf(address(this)); uint256 forbiddenToSend = tokenState.getAndUpdateLockedAmount(address(this)); if (escrowBalance > forbiddenToSend) { require( IERC20(contractManager.getContract("SkaleToken")).transfer( destination, escrowBalance.sub(forbiddenToSend) ), "Error of token send" ); } } /** * @dev Allows Beneficiary to propose a delegation to a validator. * * Requirements: * * - Beneficiary must be active. * - Beneficiary must have sufficient delegatable tokens. * - If trusted list is enabled, validator must be a member of the trusted * list. */ function delegate( uint256 validatorId, uint256 amount, uint256 delegationPeriod, string calldata info ) external onlyBeneficiary { Allocator allocator = Allocator(contractManager.getContract("Allocator")); require(allocator.isDelegationAllowed(_beneficiary), "Delegation is not allowed"); require(allocator.isVestingActive(_beneficiary), "Beneficiary is not Active"); IDelegationController delegationController = IDelegationController( contractManager.getContract("DelegationController") ); delegationController.delegate(validatorId, amount, delegationPeriod, info); } /** * @dev Allows Beneficiary and Vesting manager to request undelegation. Only * Vesting manager can request undelegation after beneficiary is deactivated * (after beneficiary termination). * * Requirements: * * - Beneficiary and Vesting manager must be `msg.sender`. */ function requestUndelegation(uint256 delegationId) external onlyActiveBeneficiaryOrVestingManager { IDelegationController delegationController = IDelegationController( contractManager.getContract("DelegationController") ); delegationController.requestUndelegation(delegationId); } /** * @dev Allows Beneficiary and Vesting manager to cancel a delegation proposal. Only * Vesting manager can request undelegation after beneficiary is deactivated * (after beneficiary termination). * * Requirements: * * - Beneficiary and Vesting manager must be `msg.sender`. */ function cancelPendingDelegation(uint delegationId) external onlyActiveBeneficiaryOrVestingManager { IDelegationController delegationController = IDelegationController( contractManager.getContract("DelegationController") ); delegationController.cancelPendingDelegation(delegationId); } /** * @dev Allows Beneficiary and Vesting manager to withdraw earned bounty. Only * Vesting manager can withdraw bounty to Allocator contract after beneficiary * is deactivated. * * IMPORTANT: Withdraws are only possible after 90 day initial network lock. * * Requirements: * * - Beneficiary or Vesting manager must be `msg.sender`. * - Beneficiary must be active when Beneficiary is `msg.sender`. */ function withdrawBounty(uint256 validatorId, address to) external onlyActiveBeneficiaryOrVestingManager { IDistributor distributor = IDistributor(contractManager.getContract("Distributor")); distributor.withdrawBounty(validatorId, to); } /** * @dev Allows Allocator contract to cancel vesting of a Beneficiary. Cancel * vesting is performed upon termination. */ function cancelVesting(uint256 vestedAmount) external allow("Allocator") { _availableAmountAfterTermination = vestedAmount; } } pragma solidity ^0.6.0; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: AGPL-3.0-only /* IDelegationController.sol - SKALE Allocator Copyright (C) 2019-Present SKALE Labs @author Artem Payvin SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of Delegatable Token operations. */ interface IDelegationController { function delegate( uint256 validatorId, uint256 amount, uint256 delegationPeriod, string calldata info ) external; function requestUndelegation(uint256 delegationId) external; function cancelPendingDelegation(uint delegationId) external; } // SPDX-License-Identifier: AGPL-3.0-only /* IDistributor.sol - SKALE Allocator Copyright (C) 2019-Present SKALE Labs @author Artem Payvin SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of Distributor contract. */ interface IDistributor { function withdrawBounty(uint256 validatorId, address to) external; } // SPDX-License-Identifier: AGPL-3.0-only /* ITokenState.sol - SKALE Allocator Copyright (C) 2019-Present SKALE Labs @author Artem Payvin SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of Token State contract. */ interface ITokenState { function getAndUpdateLockedAmount(address holder) external returns (uint); function getAndUpdateForbiddenForDelegationAmount(address holder) external returns (uint); } // SPDX-License-Identifier: AGPL-3.0-only /* Allocator.sol - SKALE Allocator Copyright (C) 2020-Present SKALE Labs @author Artem Payvin SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "./interfaces/openzeppelin/IProxyFactory.sol"; import "./interfaces/openzeppelin/IProxyAdmin.sol"; import "./interfaces/ITimeHelpers.sol"; import "./Escrow.sol"; import "./Permissions.sol"; /** * @title Allocator */ contract Allocator is Permissions, IERC777Recipient { uint256 constant private _SECONDS_PER_DAY = 24 * 60 * 60; uint256 constant private _MONTHS_PER_YEAR = 12; enum TimeUnit { DAY, MONTH, YEAR } enum BeneficiaryStatus { UNKNOWN, CONFIRMED, ACTIVE, TERMINATED } struct Plan { uint256 totalVestingDuration; // months uint256 vestingCliff; // months TimeUnit vestingIntervalTimeUnit; uint256 vestingInterval; // amount of days/months/years bool isDelegationAllowed; bool isTerminatable; } struct Beneficiary { BeneficiaryStatus status; uint256 planId; uint256 startMonth; uint256 fullAmount; uint256 amountAfterLockup; } event PlanCreated( uint256 id ); IERC1820Registry private _erc1820; // array of Plan configs Plan[] private _plans; bytes32 public constant VESTING_MANAGER_ROLE = keccak256("VESTING_MANAGER_ROLE"); // beneficiary => beneficiary plan params mapping (address => Beneficiary) private _beneficiaries; // beneficiary => Escrow mapping (address => Escrow) private _beneficiaryToEscrow; modifier onlyVestingManager() { require( hasRole(VESTING_MANAGER_ROLE, _msgSender()), "Message sender is not a vesting manager" ); _; } function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleToken") // solhint-disable-next-line no-empty-blocks { } /** * @dev Allows Vesting manager to activate a vesting and transfer locked * tokens from the Allocator contract to the associated Escrow address. * * Requirements: * * - Beneficiary address must be already confirmed. */ function startVesting(address beneficiary) external onlyVestingManager { require( _beneficiaries[beneficiary].status == BeneficiaryStatus.CONFIRMED, "Beneficiary has inappropriate status" ); _beneficiaries[beneficiary].status = BeneficiaryStatus.ACTIVE; require( IERC20(contractManager.getContract("SkaleToken")).transfer( address(_beneficiaryToEscrow[beneficiary]), _beneficiaries[beneficiary].fullAmount ), "Error of token sending" ); } /** * @dev Allows Vesting manager to define and add a Plan. * * Requirements: * * - Vesting cliff period must be less than or equal to the full period. * - Vesting step time unit must be in days, months, or years. * - Total vesting duration must equal vesting cliff plus entire vesting schedule. */ function addPlan( uint256 vestingCliff, // months uint256 totalVestingDuration, // months TimeUnit vestingIntervalTimeUnit, // 0 - day 1 - month 2 - year uint256 vestingInterval, // months or days or years bool canDelegate, // can beneficiary delegate all un-vested tokens bool isTerminatable ) external onlyVestingManager { require(totalVestingDuration > 0, "Vesting duration can't be zero"); require(vestingInterval > 0, "Vesting interval can't be zero"); require(totalVestingDuration >= vestingCliff, "Cliff period exceeds total vesting duration"); // can't check if vesting interval in days is correct because it depends on startMonth // This check is in connectBeneficiaryToPlan if (vestingIntervalTimeUnit == TimeUnit.MONTH) { uint256 vestingDurationAfterCliff = totalVestingDuration - vestingCliff; require( vestingDurationAfterCliff.mod(vestingInterval) == 0, "Vesting duration can't be divided into equal intervals" ); } else if (vestingIntervalTimeUnit == TimeUnit.YEAR) { uint256 vestingDurationAfterCliff = totalVestingDuration - vestingCliff; require( vestingDurationAfterCliff.mod(vestingInterval.mul(_MONTHS_PER_YEAR)) == 0, "Vesting duration can't be divided into equal intervals" ); } _plans.push(Plan({ totalVestingDuration: totalVestingDuration, vestingCliff: vestingCliff, vestingIntervalTimeUnit: vestingIntervalTimeUnit, vestingInterval: vestingInterval, isDelegationAllowed: canDelegate, isTerminatable: isTerminatable })); emit PlanCreated(_plans.length); } /** * @dev Allows Vesting manager to register a beneficiary to a Plan. * * Requirements: * * - Plan must already exist. * - The vesting amount must be less than or equal to the full allocation. * - The beneficiary address must not already be included in the any other Plan. */ function connectBeneficiaryToPlan( address beneficiary, uint256 planId, uint256 startMonth, uint256 fullAmount, uint256 lockupAmount ) external onlyVestingManager { require(_plans.length >= planId && planId > 0, "Plan does not exist"); require(fullAmount >= lockupAmount, "Incorrect amounts"); require(_beneficiaries[beneficiary].status == BeneficiaryStatus.UNKNOWN, "Beneficiary is already added"); if (_plans[planId - 1].vestingIntervalTimeUnit == TimeUnit.DAY) { uint256 vestingDurationInDays = _daysBetweenMonths( startMonth.add(_plans[planId - 1].vestingCliff), startMonth.add(_plans[planId - 1].totalVestingDuration) ); require( vestingDurationInDays.mod(_plans[planId - 1].vestingInterval) == 0, "Vesting duration can't be divided into equal intervals" ); } _beneficiaries[beneficiary] = Beneficiary({ status: BeneficiaryStatus.CONFIRMED, planId: planId, startMonth: startMonth, fullAmount: fullAmount, amountAfterLockup: lockupAmount }); _beneficiaryToEscrow[beneficiary] = _deployEscrow(beneficiary); } /** * @dev Allows Vesting manager to terminate vesting of a Escrow. Performed when * a beneficiary is terminated. * * Requirements: * * - Vesting must be active. */ function stopVesting(address beneficiary) external onlyVestingManager { require( _beneficiaries[beneficiary].status == BeneficiaryStatus.ACTIVE, "Cannot stop vesting for a non active beneficiary" ); require( _plans[_beneficiaries[beneficiary].planId - 1].isTerminatable, "Can't stop vesting for beneficiary with this plan" ); _beneficiaries[beneficiary].status = BeneficiaryStatus.TERMINATED; Escrow(_beneficiaryToEscrow[beneficiary]).cancelVesting(calculateVestedAmount(beneficiary)); } /** * @dev Returns vesting start month of the beneficiary's Plan. */ function getStartMonth(address beneficiary) external view returns (uint) { return _beneficiaries[beneficiary].startMonth; } /** * @dev Returns the final vesting date of the beneficiary's Plan. */ function getFinishVestingTime(address beneficiary) external view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); Beneficiary memory beneficiaryPlan = _beneficiaries[beneficiary]; Plan memory planParams = _plans[beneficiaryPlan.planId - 1]; return timeHelpers.monthToTimestamp(beneficiaryPlan.startMonth.add(planParams.totalVestingDuration)); } /** * @dev Returns the vesting cliff period in months. */ function getVestingCliffInMonth(address beneficiary) external view returns (uint) { return _plans[_beneficiaries[beneficiary].planId - 1].vestingCliff; } /** * @dev Confirms whether the beneficiary is active in the Plan. */ function isVestingActive(address beneficiary) external view returns (bool) { return _beneficiaries[beneficiary].status == BeneficiaryStatus.ACTIVE; } /** * @dev Confirms whether the beneficiary is registered in a Plan. */ function isBeneficiaryRegistered(address beneficiary) external view returns (bool) { return _beneficiaries[beneficiary].status != BeneficiaryStatus.UNKNOWN; } /** * @dev Confirms whether the beneficiary's Plan allows all un-vested tokens to be * delegated. */ function isDelegationAllowed(address beneficiary) external view returns (bool) { return _plans[_beneficiaries[beneficiary].planId - 1].isDelegationAllowed; } /** * @dev Returns the locked and unlocked (full) amount of tokens allocated to * the beneficiary address in Plan. */ function getFullAmount(address beneficiary) external view returns (uint) { return _beneficiaries[beneficiary].fullAmount; } /** * @dev Returns the Escrow contract by beneficiary. */ function getEscrowAddress(address beneficiary) external view returns (address) { return address(_beneficiaryToEscrow[beneficiary]); } /** * @dev Returns the timestamp when vesting cliff ends and periodic vesting * begins. */ function getLockupPeriodEndTimestamp(address beneficiary) external view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); Beneficiary memory beneficiaryPlan = _beneficiaries[beneficiary]; Plan memory planParams = _plans[beneficiaryPlan.planId - 1]; return timeHelpers.monthToTimestamp(beneficiaryPlan.startMonth.add(planParams.vestingCliff)); } /** * @dev Returns the time of the next vesting event. */ function getTimeOfNextVest(address beneficiary) external view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); Beneficiary memory beneficiaryPlan = _beneficiaries[beneficiary]; Plan memory planParams = _plans[beneficiaryPlan.planId - 1]; uint256 firstVestingMonth = beneficiaryPlan.startMonth.add(planParams.vestingCliff); uint256 lockupEndTimestamp = timeHelpers.monthToTimestamp(firstVestingMonth); if (now < lockupEndTimestamp) { return lockupEndTimestamp; } require( now < timeHelpers.monthToTimestamp(beneficiaryPlan.startMonth.add(planParams.totalVestingDuration)), "Vesting is over" ); require(beneficiaryPlan.status != BeneficiaryStatus.TERMINATED, "Vesting was stopped"); uint256 currentMonth = timeHelpers.getCurrentMonth(); if (planParams.vestingIntervalTimeUnit == TimeUnit.DAY) { // TODO: it may be simplified if TimeHelpers contract in skale-manager is updated uint daysPassedBeforeCurrentMonth = _daysBetweenMonths(firstVestingMonth, currentMonth); uint256 currentMonthBeginningTimestamp = timeHelpers.monthToTimestamp(currentMonth); uint256 daysPassedInCurrentMonth = now.sub(currentMonthBeginningTimestamp).div(_SECONDS_PER_DAY); uint256 daysPassedBeforeNextVest = _calculateNextVestingStep( daysPassedBeforeCurrentMonth.add(daysPassedInCurrentMonth), planParams.vestingInterval ); return currentMonthBeginningTimestamp.add( daysPassedBeforeNextVest .sub(daysPassedBeforeCurrentMonth) .mul(_SECONDS_PER_DAY) ); } else if (planParams.vestingIntervalTimeUnit == TimeUnit.MONTH) { return timeHelpers.monthToTimestamp( firstVestingMonth.add( _calculateNextVestingStep(currentMonth.sub(firstVestingMonth), planParams.vestingInterval) ) ); } else if (planParams.vestingIntervalTimeUnit == TimeUnit.YEAR) { return timeHelpers.monthToTimestamp( firstVestingMonth.add( _calculateNextVestingStep( currentMonth.sub(firstVestingMonth), planParams.vestingInterval.mul(_MONTHS_PER_YEAR) ) ) ); } else { revert("Vesting interval timeunit is incorrect"); } } /** * @dev Returns the Plan parameters. * * Requirements: * * - Plan must already exist. */ function getPlan(uint256 planId) external view returns (Plan memory) { require(planId > 0 && planId <= _plans.length, "Plan Round does not exist"); return _plans[planId - 1]; } /** * @dev Returns the Plan parameters for a beneficiary address. * * Requirements: * * - Beneficiary address must be registered to an Plan. */ function getBeneficiaryPlanParams(address beneficiary) external view returns (Beneficiary memory) { require(_beneficiaries[beneficiary].status != BeneficiaryStatus.UNKNOWN, "Plan beneficiary is not registered"); return _beneficiaries[beneficiary]; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } /** * @dev Calculates and returns the vested token amount. */ function calculateVestedAmount(address wallet) public view returns (uint256 vestedAmount) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); Beneficiary memory beneficiaryPlan = _beneficiaries[wallet]; Plan memory planParams = _plans[beneficiaryPlan.planId - 1]; vestedAmount = 0; uint256 currentMonth = timeHelpers.getCurrentMonth(); if (currentMonth >= beneficiaryPlan.startMonth.add(planParams.vestingCliff)) { vestedAmount = beneficiaryPlan.amountAfterLockup; if (currentMonth >= beneficiaryPlan.startMonth.add(planParams.totalVestingDuration)) { vestedAmount = beneficiaryPlan.fullAmount; } else { uint256 payment = _getSinglePaymentSize( wallet, beneficiaryPlan.fullAmount, beneficiaryPlan.amountAfterLockup ); vestedAmount = vestedAmount.add(payment.mul(_getNumberOfCompletedVestingEvents(wallet))); } } } /** * @dev Returns the number of vesting events that have completed. */ function _getNumberOfCompletedVestingEvents(address wallet) internal view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); Beneficiary memory beneficiaryPlan = _beneficiaries[wallet]; Plan memory planParams = _plans[beneficiaryPlan.planId - 1]; uint256 firstVestingMonth = beneficiaryPlan.startMonth.add(planParams.vestingCliff); if (now < timeHelpers.monthToTimestamp(firstVestingMonth)) { return 0; } else { uint256 currentMonth = timeHelpers.getCurrentMonth(); if (planParams.vestingIntervalTimeUnit == TimeUnit.DAY) { return _daysBetweenMonths(firstVestingMonth, currentMonth) .add( now .sub(timeHelpers.monthToTimestamp(currentMonth)) .div(_SECONDS_PER_DAY) ) .div(planParams.vestingInterval); } else if (planParams.vestingIntervalTimeUnit == TimeUnit.MONTH) { return currentMonth .sub(firstVestingMonth) .div(planParams.vestingInterval); } else if (planParams.vestingIntervalTimeUnit == TimeUnit.YEAR) { return currentMonth .sub(firstVestingMonth) .div(_MONTHS_PER_YEAR) .div(planParams.vestingInterval); } else { revert("Unknown time unit"); } } } /** * @dev Returns the number of total vesting events. */ function _getNumberOfAllVestingEvents(address wallet) internal view returns (uint) { Beneficiary memory beneficiaryPlan = _beneficiaries[wallet]; Plan memory planParams = _plans[beneficiaryPlan.planId - 1]; if (planParams.vestingIntervalTimeUnit == TimeUnit.DAY) { return _daysBetweenMonths( beneficiaryPlan.startMonth.add(planParams.vestingCliff), beneficiaryPlan.startMonth.add(planParams.totalVestingDuration) ).div(planParams.vestingInterval); } else if (planParams.vestingIntervalTimeUnit == TimeUnit.MONTH) { return planParams.totalVestingDuration .sub(planParams.vestingCliff) .div(planParams.vestingInterval); } else if (planParams.vestingIntervalTimeUnit == TimeUnit.YEAR) { return planParams.totalVestingDuration .sub(planParams.vestingCliff) .div(_MONTHS_PER_YEAR) .div(planParams.vestingInterval); } else { revert("Unknown time unit"); } } /** * @dev Returns the amount of tokens that are unlocked in each vesting * period. */ function _getSinglePaymentSize( address wallet, uint256 fullAmount, uint256 afterLockupPeriodAmount ) internal view returns(uint) { return fullAmount.sub(afterLockupPeriodAmount).div(_getNumberOfAllVestingEvents(wallet)); } function _deployEscrow(address beneficiary) private returns (Escrow) { // TODO: replace with ProxyFactory when @openzeppelin/upgrades will be compatible with solidity 0.6 IProxyFactory proxyFactory = IProxyFactory(contractManager.getContract("ProxyFactory")); Escrow escrow = Escrow(contractManager.getContract("Escrow")); // TODO: replace with ProxyAdmin when @openzeppelin/upgrades will be compatible with solidity 0.6 IProxyAdmin proxyAdmin = IProxyAdmin(contractManager.getContract("ProxyAdmin")); return Escrow( proxyFactory.deploy( uint256(bytes32(bytes20(beneficiary))), proxyAdmin.getProxyImplementation(address(escrow)), address(proxyAdmin), abi.encodeWithSelector( Escrow.initialize.selector, address(contractManager), beneficiary ) ) ); } function _daysBetweenMonths(uint256 beginMonth, uint256 endMonth) private view returns (uint256) { assert(beginMonth <= endMonth); ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); uint256 beginTimestamp = timeHelpers.monthToTimestamp(beginMonth); uint256 endTimestamp = timeHelpers.monthToTimestamp(endMonth); uint256 secondsPassed = endTimestamp.sub(beginTimestamp); require(secondsPassed.mod(_SECONDS_PER_DAY) == 0, "Internal error in calendar"); return secondsPassed.div(_SECONDS_PER_DAY); } /** * @dev returns time of next vest in abstract time units named "step" * Examples: * if current step is 5 and vesting interval is 7 function returns 7. * if current step is 17 and vesting interval is 7 function returns 21. */ function _calculateNextVestingStep(uint256 currentStep, uint256 vestingInterval) private pure returns (uint256) { return currentStep .add(vestingInterval) .sub( currentStep.mod(vestingInterval) ); } } // SPDX-License-Identifier: AGPL-3.0-only /* IProxyFactory.sol - SKALE Allocator Copyright (C) 2020-Present SKALE Labs @author Artem Payvin SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; // TODO: Remove it when @openzeppelin/upgrades will be compatible with solidity 0.6 interface IProxyFactory { function deploy(uint256 _salt, address _logic, address _admin, bytes memory _data) external returns (address); } // SPDX-License-Identifier: AGPL-3.0-only /* IProxyAdmin.sol - SKALE Allocator Copyright (C) 2020-Present SKALE Labs @author Dmytro Stebaiev SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; // TODO: Remove it when @openzeppelin/upgrades will be compatible with solidity 0.6 interface IProxyAdmin { function getProxyImplementation(address proxy) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only /* ITimeHelpers.sol - SKALE Allocator Copyright (C) 2020-Present SKALE Labs @author Artem Payvin SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @title Time Helpers Interface * @dev Interface of Time Helper functions of the Time Helpers SKALE Allocator * contract. */ interface ITimeHelpers { function getCurrentMonth() external view returns (uint); function monthToTimestamp(uint month) external view returns (uint timestamp); } // SPDX-License-Identifier: AGPL-3.0-only /* Permissions.sol - SKALE Allocator Copyright (C) 2020-Present SKALE Labs @author Artem Payvin SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "./interfaces/IContractManager.sol"; /** * @title Permissions - connected module for Upgradeable approach, knows ContractManager * @author Artem Payvin */ contract Permissions is AccessControlUpgradeSafe { using SafeMath for uint; using Address for address; IContractManager public contractManager; /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } /** * @dev allow - throws if called by any account and contract other than the owner * or `contractName` contract */ modifier allow(string memory contractName) { require( contractManager.getContract(contractName) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual initializer { AccessControlUpgradeSafe.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = IContractManager(contractManagerAddress); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; import "../Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: AGPL-3.0-only /* IContractManager.sol - SKALE Allocator Copyright (C) 2020-Present SKALE Labs @author Dmytro Stebaiev SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @title Contract Manager * @dev This contract is the main contract for upgradeable approach. This * contract contains the current mapping from contract IDs (in the form of * human-readable strings) to addresses. */ interface IContractManager { /** * @dev Returns the contract address of a given contract name. * * Requirements: * * - Contract mapping must exist. */ function getContract(string calldata name) external view returns (address contractAddress); } // SPDX-License-Identifier: AGPL-3.0-only /* ConstantsHolderMock.sol - SKALE Allocator Copyright (C) 2019-Present SKALE Labs @author Artem Payvin SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; // import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "../Permissions.sol"; /** * @dev Interface of Delegatable Token operations. */ contract ConstantsHolderMock is Permissions { uint256 public launchTimestamp; function setLaunchTimestamp(uint256 timestamp) external onlyOwner { require(now < launchTimestamp, "Can't set network launch timestamp because network is already launched"); launchTimestamp = timestamp; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* ContractManager.sol - SKALE Allocator Copyright (C) 2020-Present SKALE Labs @author Artem Payvin SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; import "./utils/StringUtils.sol"; /** * @title Contract Manager * @dev This contract is the main contract for upgradeable approach. This * contract contains the current mapping from contract IDs (in the form of * human-readable strings) to addresses. */ contract ContractManager is OwnableUpgradeSafe { using StringUtils for string; using Address for address; // mapping of actual smart contracts addresses mapping (bytes32 => address) public contracts; event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * @dev Allows Owner to add contract to mapping of actual contract addresses * * Emits a {ContractUpgraded} event. * * Requirements: * * - Contract address is non-zero. * - Contract address is not already added. * - Contract contains code. */ function setContractsAddress(string calldata contractsName, address newContractsAddress) external onlyOwner { // check newContractsAddress is not equal to zero require(newContractsAddress != address(0), "New address is equal zero"); // create hash of contractsName bytes32 contractId = keccak256(abi.encodePacked(contractsName)); // check newContractsAddress is not equal the previous contract's address require(contracts[contractId] != newContractsAddress, "Contract is already added"); require(newContractsAddress.isContract(), "Given contracts address does not contain code"); // add newContractsAddress to mapping of actual contract addresses contracts[contractId] = newContractsAddress; emit ContractUpgraded(contractsName, newContractsAddress); } /** * @dev Returns the contract address of a given contract name. * * Requirements: * * - Contract mapping must exist. */ function getContract(string calldata name) external view returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; require(contractAddress != address(0), name.strConcat(" contract has not been found")); } } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: AGPL-3.0-only /* StringUtils.sol - SKALE Allocator Copyright (C) 2020-Present SKALE Labs @author Vadim Yavorsky SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library StringUtils { using SafeMath for uint; function strConcat(string memory a, string memory b) internal pure returns (string memory) { bytes memory _ba = bytes(a); bytes memory _bb = bytes(b); string memory ab = new string(_ba.length.add(_bb.length)); bytes memory strBytes = bytes(ab); uint256 k = 0; uint256 i = 0; for (i = 0; i < _ba.length; i++) { strBytes[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { strBytes[k++] = _bb[i]; } return string(strBytes); } } // SPDX-License-Identifier: AGPL-3.0-only /* DelegationControllerTester.sol - SKALE Allocator Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; import "../interfaces/delegation/IDelegationController.sol"; import "./interfaces/ILocker.sol"; import "./TokenStateTester.sol"; import "./SkaleTokenTester.sol"; contract DelegationControllerTester is Permissions, IDelegationController, ILocker { struct Delegation { address holder; uint256 amount; } mapping (address => uint) private _locked; Delegation[] private _delegations; function delegate( uint256 , uint256 amount, uint256 , string calldata ) external override { SkaleTokenTester skaleToken = SkaleTokenTester(contractManager.getContract("SkaleToken")); TokenStateTester tokenState = TokenStateTester(contractManager.getContract("TokenState")); _delegations.push(Delegation({ holder: msg.sender, amount: amount })); _locked[msg.sender] += amount; uint256 holderBalance = skaleToken.balanceOf(msg.sender); uint256 forbiddenForDelegation = tokenState.getAndUpdateForbiddenForDelegationAmount(msg.sender); require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate"); } function requestUndelegation(uint256 delegationId) external override { address holder = _delegations[delegationId].holder; _locked[holder] -= _delegations[delegationId].amount; } function cancelPendingDelegation(uint delegationId) external override { address holder = _delegations[delegationId].holder; _locked[holder] -= _delegations[delegationId].amount; } /** * @dev See ILocker. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See ILocker. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } function _getAndUpdateLockedAmount(address wallet) private view returns (uint) { return _locked[wallet]; } } // SPDX-License-Identifier: AGPL-3.0-only /* ILocker.sol - SKALE Allocator Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of Locker functions of the {TokenState} contract. * * The SKALE Network has three types of locked tokens: * * - Tokens that are transferrable but are currently locked into delegation with * a validator. See {DelegationController}; * * - Tokens that are not transferable from one address to another, but may be * delegated to a validator {getAndUpdateLockedAmount}. This lock enforces * Proof-of-Use requirements. See {TokenLaunchLocker}; and, * * - Tokens that are neither transferable nor delegatable * {getAndUpdateForbiddenForDelegationAmount}. This lock enforces slashing. * See {Punisher}. */ interface ILocker { /** * @dev Returns the locked amount of untransferable tokens of a given `wallet` */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns the locked amount of untransferable and un-delegatable tokens of a given `wallet`. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleTokenInternalTester.sol - SKALE Allocator Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; import "../interfaces/delegation/ITokenState.sol"; import "./interfaces/ILocker.sol"; contract TokenStateTester is Permissions, ITokenState { string[] private _lockers; function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint) { uint256 forbidden = 0; for (uint256 i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder)); } return forbidden; } function getAndUpdateLockedAmount(address holder) external override returns (uint) { uint256 locked = 0; for (uint256 i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); locked = locked.add(locker.getAndUpdateLockedAmount(holder)); } return locked; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); addLocker("DelegationController"); } /** * @dev Allows the Owner to add a contract to the Locker. * * Emits a LockerWasAdded event. * * @param locker string name of contract to add to locker */ function addLocker(string memory locker) public onlyOwner { _lockers.push(locker); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleTokenInternalTester.sol - SKALE Allocator Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/ERC777.sol"; import "../Permissions.sol"; import "../interfaces/delegation/ITokenState.sol"; contract SkaleTokenTester is ERC777UpgradeSafe, Permissions { uint256 public constant CAP = 7 * 1e9 * (10 ** 18); // the maximum amount of tokens that can ever be created constructor( address contractManagerAddress, string memory name, string memory symbol, address[] memory defOp ) public { ERC777UpgradeSafe.__ERC777_init(name, symbol, defOp); Permissions.initialize(contractManagerAddress); } function mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) external onlyOwner returns (bool) { require(amount <= CAP.sub(totalSupply()), "Amount is too big"); _mint( account, amount, userData, operatorData ); return true; } function getAndUpdateDelegatedAmount(address) pure external returns (uint) { return 0; } function getAndUpdateSlashedAmount(address) pure external returns (uint) { return 0; } function getAndUpdateLockedAmount(address wallet) public returns (uint) { ITokenState tokenState = ITokenState(contractManager.getContract("TokenState")); return tokenState.getAndUpdateLockedAmount(wallet); } function _beforeTokenTransfer( address, // operator address from, address, // to uint256 tokenId) internal override { uint256 locked = getAndUpdateLockedAmount(from); if (locked > 0) { require(balanceOf(from) >= locked.add(tokenId), "Token should be unlocked for transferring"); } } } pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC777.sol"; import "./IERC777Recipient.sol"; import "./IERC777Sender.sol"; import "../../token/ERC20/IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../introspection/IERC1820Registry.sol"; import "../../Initializable.sol"; /** * @dev Implementation of the {IERC777} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. */ contract ERC777UpgradeSafe is Initializable, ContextUpgradeSafe, IERC777, IERC20 { using SafeMath for uint256; using Address for address; IERC1820Registry constant internal _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) private _allowances; /** * @dev `defaultOperators` may be an empty array. */ function __ERC777_init( string memory name, string memory symbol, address[] memory defaultOperators ) internal initializer { __Context_init_unchained(); __ERC777_init_unchained(name, symbol, defaultOperators); } function __ERC777_init_unchained( string memory name, string memory symbol, address[] memory defaultOperators ) internal initializer { _name = name; _symbol = symbol; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {ERC20-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view override returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view override(IERC20, IERC777) returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view override(IERC20, IERC777) returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes memory data) public override { _send(_msgSender(), recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes memory data) public override { _burn(_msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view override returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) public override { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) public override { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view override returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {IERC20-Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public override { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); _send(sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {IERC20-Transfer} events. */ function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public override { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); _burn(account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view override returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) public override returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = _msgSender(); _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal virtual { require(account != address(0), "ERC777: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, amount); // Update state variables _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send( address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } /** * @dev Burn tokens * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal virtual { require(from != address(0), "ERC777: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), amount); _callTokensToSend(operator, from, address(0), amount, data, operatorData); // Update state variables _balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _beforeTokenTransfer(operator, from, to, amount); _balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance"); _balances[to] = _balances[to].add(amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } function _approve(address holder, address spender, uint256 value) internal { // TODO: restore this require statement if this function becomes internal, or is called at a new callsite. It is // currently unnecessary. //require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to the zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } /** * @dev Hook that is called before any token transfer. This includes * calls to {send}, {transfer}, {operatorSend}, minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - when `from` is zero, `tokenId` will be minted for `to`. * - when `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address operator, address from, address to, uint256 tokenId) internal virtual { } uint256[41] private __gap; } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } // SPDX-License-Identifier: AGPL-3.0-only /* DistributorMock.sol - SKALE Allocator Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "../interfaces/delegation/IDistributor.sol"; contract DistributorMock is IDistributor, IERC777Recipient { IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); IERC20 public skaleToken; // wallet => validatorId => tokens mapping (address => mapping (uint256 => uint)) public approved; constructor (address skaleTokenAddress) public { skaleToken = IERC20(skaleTokenAddress); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } function withdrawBounty(uint256 validatorId, address to) external override { uint256 bounty = approved[msg.sender][validatorId]; delete approved[msg.sender][validatorId]; require(skaleToken.transfer(to, bounty), "Failed to transfer tokens"); } function tokensReceived( address, address, address to, uint256 amount, bytes calldata userData, bytes calldata ) external override { require(to == address(this), "Receiver is incorrect"); require(userData.length == 32 * 2, "Data length is incorrect"); (uint256 validatorId, address wallet) = abi.decode(userData, (uint, address)); _payBounty(wallet, validatorId, amount); } // private function _payBounty(address wallet, uint256 validatorId, uint256 amount) private { approved[wallet][validatorId] += amount; } } // SPDX-License-Identifier: AGPL-3.0-only /* LockerMock.sol - SKALE Allocator Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./interfaces/ILocker.sol"; contract LockerMock is ILocker { function getAndUpdateLockedAmount(address) external override returns (uint) { return 13; } function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) { return 13; } } // SPDX-License-Identifier: AGPL-3.0-only /* ProxyFactoryMock.sol - SKALE Allocator Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../interfaces/openzeppelin/IProxyFactory.sol"; import "../interfaces/openzeppelin/IProxyAdmin.sol"; contract ProxyMock { bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; constructor(address implementation, bytes memory _data) public { _setImplementation(implementation); if(_data.length > 0) { // solhint-disable-next-line avoid-low-level-calls (bool success,) = implementation.delegatecall(_data); require(success); } } fallback () payable external { _delegate(_implementation()); } function _delegate(address implementation) internal { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } function _implementation() internal view returns (address impl) { bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { impl := sload(slot) } } function _setImplementation(address newImplementation) internal { bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newImplementation) } } } contract ProxyFactoryMock is IProxyFactory, IProxyAdmin { address public implementation; function deploy(uint256, address _logic, address, bytes memory _data) external override returns (address) { return address(new ProxyMock(_logic, _data)); } function setImplementation(address _implementation) external { implementation = _implementation; } function getProxyImplementation(address) external view override returns (address) { return implementation; } } pragma solidity ^0.6.0; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint256 constant SECONDS_PER_DAY = 24 * 60 * 60; uint256 constant SECONDS_PER_HOUR = 60 * 60; uint256 constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint256 constant DOW_MON = 1; uint256 constant DOW_TUE = 2; uint256 constant DOW_WED = 3; uint256 constant DOW_THU = 4; uint256 constant DOW_FRI = 5; uint256 constant DOW_SAT = 6; uint256 constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint256 year, uint256 month, uint256 day) internal pure returns (uint256 _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint256 _days) internal pure returns (uint256 year, uint256 month, uint256 day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint256 year, uint256 month, uint256 day) internal pure returns (uint256 timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second) internal pure returns (uint256 timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint256 timestamp) internal pure returns (uint256 year, uint256 month, uint256 day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint256 timestamp) internal pure returns (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint256 year, uint256 month, uint256 day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint256 daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint256 year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint256 year, uint256 month) internal pure returns (uint256 daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) { uint256 _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint256 timestamp) internal pure returns (uint256 year) { uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint256 timestamp) internal pure returns (uint256 month) { uint256 year; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint256 timestamp) internal pure returns (uint256 day) { uint256 year; uint256 month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint256 timestamp) internal pure returns (uint256 hour) { uint256 secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint256 timestamp) internal pure returns (uint256 minute) { uint256 secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint256 timestamp) internal pure returns (uint256 second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) { require(fromTimestamp <= toTimestamp); uint256 fromYear; uint256 fromMonth; uint256 fromDay; uint256 toYear; uint256 toMonth; uint256 toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) { require(fromTimestamp <= toTimestamp); uint256 fromYear; uint256 fromMonth; uint256 fromDay; uint256 toYear; uint256 toMonth; uint256 toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.21 <0.7.0; contract Migrations { address public owner; uint256 public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint256 completed) public restricted { last_completed_migration = completed; } } // SPDX-License-Identifier: AGPL-3.0-only /* TimeHelpers.sol - SKALE Allocator Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./thirdparty/BokkyPooBahsDateTimeLibrary.sol"; import "../interfaces/ITimeHelpers.sol"; /** * @title TimeHelpers * @dev The contract performs time operations. * * These functions are used to calculate monthly and Proof of Use epochs. */ contract TimeHelpersTester is ITimeHelpers { using SafeMath for uint; uint256 constant private _ZERO_YEAR = 2020; function getCurrentMonth() external view override returns (uint) { return timestampToMonth(now); } function timestampToMonth(uint256 timestamp) public pure returns (uint) { uint256 year; uint256 month; (year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12)); require(month > 0, "Timestamp is too far in the past"); return month; } function monthToTimestamp(uint256 month) public view override returns (uint256 timestamp) { uint256 year = _ZERO_YEAR; uint256 _month = month; year = year.add(_month.div(12)); _month = _month.mod(12); _month = _month.add(1); return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1); } } // SPDX-License-Identifier: AGPL-3.0-only /* ITokenLaunchManager.sol - SKALE Allocator Copyright (C) 2019-Present SKALE Labs @author Artem Payvin SKALE Allocator is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Allocator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; // import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "../Permissions.sol"; /** * @dev Interface of Delegatable Token operations. */ contract TokenLaunchManagerTester is Permissions { bytes32 public constant SELLER_ROLE = keccak256("SELLER_ROLE"); function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } }
* @dev Allows the Owner to add a contract to the Locker. Emits a LockerWasAdded event. @param locker string name of contract to add to locker/
function addLocker(string memory locker) public onlyOwner { _lockers.push(locker); }
19,776
[ 1, 19132, 326, 16837, 358, 527, 279, 6835, 358, 326, 3488, 264, 18, 7377, 1282, 279, 3488, 264, 14992, 8602, 871, 18, 225, 28152, 533, 508, 434, 6835, 358, 527, 358, 28152, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 2531, 264, 12, 1080, 3778, 28152, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 739, 414, 18, 6206, 12, 739, 264, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.8; /** * @title SafeMath * * @dev SafeMath Library - General Math Utility Library for safe Math operations * with safety checks that throws error */ library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } } /** * @title Owned * * @dev Owned contract - Implements a simple ownership model with 2-phase transfer.It sets * the owner and the ownership control. Also, it can transfer the ownership to a new owner, * a proposedOwner, to be able to have authorization and control functions, this simplifies * the implementation of "user permissions". */ contract Owned { address public owner; address public proposedOwner; event OwnershipTransferInitiated(address indexed _proposedOwner); event OwnershipTransferCompleted(address indexed _newOwner); event OwnershipTransferCanceled(); /** * @dev The Owned constructor sets the original `owner` of the contract to the * creator's account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(msg.sender) == true); _; } function isOwner(address _address) public view returns (bool) { return (_address == owner); } /** * @dev Allows the owner to initiate and Ownership control of the contract to a newOwner. * * @param _proposedOwner - The address to initiateOwnershipTransfer to. */ function initiateOwnershipTransfer(address _proposedOwner) public onlyOwner returns (bool) { require(_proposedOwner != address(0)); require(_proposedOwner != address(this)); require(_proposedOwner != owner); proposedOwner = _proposedOwner; emit OwnershipTransferInitiated(proposedOwner); return true; } /** * @dev Allows for the cancellation of the OwnershipTransfer */ function cancelOwnershipTransfer() public onlyOwner returns (bool) { if (proposedOwner == address(0)) { return true; } proposedOwner = address(0); emit OwnershipTransferCanceled(); return true; } /** * @dev Allows for the finalization of the initiated Ownership Transfer */ function completeOwnershipTransfer() public returns (bool) { require(msg.sender == proposedOwner); owner = msg.sender; proposedOwner = address(0); emit OwnershipTransferCompleted(owner); return true; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Owned { 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() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } /** * @title ERC20Interface - Standard ERC20 Interface Definition based on the final specification at: * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md * * @dev Also, you can see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Interface { event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); // function name() public view returns (string memory); // function symbol() public view returns (string memory); // function decimals() public view returns (uint8); uint256 public _totalSupply; function totalSupply() public view returns (uint256); function balanceOf(address _owner) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256 remaining); // function balanceOf(address who) public view returns (uint256); // function transfer(address to, uint256 value) public; function transfer(address _to, uint256 _value) public; function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); } /** * @title ERC20Token - Standard ERC20 Implementation */ contract ERC20Token is Owned, ERC20Interface { using SafeMath for uint256; uint256 public basisPointsRate = 0; uint256 public maximumFee = 0; mapping(address => uint256) internal balances; modifier onlyPayloadSize(uint256 size) { require(!(msg.data.length < size + 4)); _; } // function balanceOf(address _owner) public view returns (uint256 balance); // function transfer(address _to, uint256 _value) public returns (bool success); function transfer(address _to, uint256 _value) public onlyPayloadSize(2 * 32) { uint256 fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } uint256 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 view returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20Token { mapping(address => mapping(address => uint256)) public allowed; uint256 public constant MAX_UINT = 2**256 - 1; function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3 * 32) returns (bool sucess) { uint256 _allowance = allowed[_from][msg.sender]; uint256 fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } if (_allowance < MAX_UINT) { allowed[_from][msg.sender] = _allowance.sub(_value); } uint256 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); return true; } function approve(address _spender, uint256 _value) public onlyPayloadSize(2 * 32) returns (bool sucess) { require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract BlackList is Owned, ERC20Token { mapping(address => bool) public isBlackListed; event AddedBlackList(address _user); event RemovedBlackList(address _user); event DestroyedBlackFunds(address _blackListedUser, uint256 _balance); // Getters to allow the same blacklist to be used also by other contracts function getBlackListStatus(address _maker) external view returns (bool) { return isBlackListed[_maker]; } function getOwner() external view returns (address) { return owner; } function addBlackList(address _evilUser) public onlyOwner { isBlackListed[_evilUser] = true; emit AddedBlackList(_evilUser); } function removeBlackList(address _clearedUser) public onlyOwner { isBlackListed[_clearedUser] = false; emit RemovedBlackList(_clearedUser); } function destroyBlackFunds(address _blackListedUser) public onlyOwner { require(isBlackListed[_blackListedUser]); uint256 dirtyFunds = balanceOf(_blackListedUser); balances[_blackListedUser] = 0; _totalSupply -= dirtyFunds; emit DestroyedBlackFunds(_blackListedUser, dirtyFunds); } } /** * These methods are called by the legacy contract * and they must ensure msg.sender to be the contract address */ contract UpgradedERC20Token is ERC20Token { function transferByLegacy(address from, address to, uint256 value) public; function transferFromByLegacy( address sender, address from, address spender, uint256 value ) public; function approveByLegacy(address from, address spender, uint256 value) public; } /** * ERC20 Compatible Stable Coin * The token is a standard ERC20 Stable with the addition of a few * concepts such as: */ contract PHStableCoin is Pausable, StandardToken, BlackList { string internal tokenName; string internal tokenSymbol; uint8 internal tokenDecimals; uint256 internal tokenTotalSupply; uint256 internal decimalsfactor = 10**uint256(tokenDecimals); bool public deprecated; address public upgradedAddress; event Issue(uint256 amount); event Redeem(uint256 amount); event Deprecate(address newAddress); event Params(uint256 feeBasisPoints, uint256 maxFee); constructor(uint256 _initialSupply) public { tokenName = "PharmHedge Stablecoin"; tokenSymbol = "PHSC"; tokenDecimals = 18; tokenTotalSupply = _initialSupply; balances[owner] = _initialSupply; deprecated = false; } function name() public view returns (string memory) { return tokenName; } function symbol() public view returns (string memory) { return tokenSymbol; } function decimals() public view returns (uint8) { return tokenDecimals; } // Forward ERC20 methods to upgraded contract if this one is deprecated function transfer(address _to, uint256 _value) public whenNotPaused { require(!isBlackListed[msg.sender]); if (deprecated) { UpgradedERC20Token(upgradedAddress).transferByLegacy( msg.sender, _to, _value ); } else { super.transfer(_to, _value); } } // Forward ERC20 methods to upgraded contract if this one is deprecated function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool sucess) { require(!isBlackListed[_from]); if (deprecated) { UpgradedERC20Token(upgradedAddress).transferFromByLegacy( msg.sender, _from, _to, _value ); } else { super.transferFrom(_from, _to, _value); } return true; } // Forward ERC20 methods to upgraded contract if this one is deprecated function balanceOf(address who) public view returns (uint256) { if (deprecated) { return UpgradedERC20Token(upgradedAddress).balanceOf(who); } else { return super.balanceOf(who); } } // Forward ERC20 methods to upgraded contract if this one is deprecated function approve(address _spender, uint256 _value) public returns (bool sucess) { if (deprecated) { UpgradedERC20Token(upgradedAddress).approveByLegacy( msg.sender, _spender, _value ); } else { super.approve(_spender, _value); } return true; } // Forward ERC20 methods to upgraded contract if this one is deprecated function allowance(address _owner, address _spender) public view returns (uint256 remaining) { if (deprecated) { return ERC20Token(upgradedAddress).allowance(_owner, _spender); } else { return super.allowance(_owner, _spender); } } // deprecate current contract in favour of a new one function deprecate(address _upgradedAddress) public onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; emit Deprecate(_upgradedAddress); } // deprecate current contract if favour of a new one function totalSupply() public view returns (uint256) { if (deprecated) { return ERC20Token(upgradedAddress).totalSupply(); } else { return tokenTotalSupply; } } // Issue a new amount of tokens // these tokens are deposited into the owner address // // @param _amount Number of tokens to be issued function issue(uint256 amount) public onlyOwner { require(tokenTotalSupply + amount > tokenTotalSupply); require(balances[owner] + amount > balances[owner]); balances[owner] += amount; tokenTotalSupply += amount; emit Issue(amount); } // Redeem tokens. // These tokens are withdrawn from the owner address // if the balance must be enough to cover the redeem // or the call will fail. // @param _amount Number of tokens to be issued function redeem(uint256 amount) public onlyOwner { require(tokenTotalSupply >= amount); require(balances[owner] >= amount); tokenTotalSupply -= amount; balances[owner] -= amount; emit Redeem(amount); } function setParams(uint256 newBasisPoints, uint256 newMaxFee) public onlyOwner { // Ensure transparency by hardcoding limit beyond which fees can never be added require(newBasisPoints < 20); require(newMaxFee < 50); basisPointsRate = newBasisPoints; maximumFee = newMaxFee.mul(decimalsfactor); emit Params(basisPointsRate, maximumFee); } }
* @title Owned @dev Owned contract - Implements a simple ownership model with 2-phase transfer.It sets the owner and the ownership control. Also, it can transfer the ownership to a new owner, a proposedOwner, to be able to have authorization and control functions, this simplifies the implementation of "user permissions"./
contract Owned { address public owner; address public proposedOwner; event OwnershipTransferInitiated(address indexed _proposedOwner); event OwnershipTransferCompleted(address indexed _newOwner); event OwnershipTransferCanceled(); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(isOwner(msg.sender) == true); _; } function isOwner(address _address) public view returns (bool) { return (_address == owner); } function initiateOwnershipTransfer(address _proposedOwner) public onlyOwner returns (bool) { require(_proposedOwner != address(0)); require(_proposedOwner != address(this)); require(_proposedOwner != owner); proposedOwner = _proposedOwner; emit OwnershipTransferInitiated(proposedOwner); return true; } function cancelOwnershipTransfer() public onlyOwner returns (bool) { if (proposedOwner == address(0)) { return true; } proposedOwner = address(0); emit OwnershipTransferCanceled(); return true; } function cancelOwnershipTransfer() public onlyOwner returns (bool) { if (proposedOwner == address(0)) { return true; } proposedOwner = address(0); emit OwnershipTransferCanceled(); return true; } function completeOwnershipTransfer() public returns (bool) { require(msg.sender == proposedOwner); owner = msg.sender; proposedOwner = address(0); emit OwnershipTransferCompleted(owner); return true; } }
12,586,133
[ 1, 5460, 329, 225, 14223, 11748, 6835, 300, 29704, 279, 4143, 23178, 938, 598, 576, 17, 13961, 7412, 18, 7193, 1678, 326, 3410, 471, 326, 23178, 3325, 18, 8080, 16, 518, 848, 7412, 326, 23178, 358, 279, 394, 3410, 16, 279, 20084, 5541, 16, 358, 506, 7752, 358, 1240, 6093, 471, 3325, 4186, 16, 333, 9330, 5032, 326, 4471, 434, 315, 1355, 4371, 9654, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 14223, 11748, 288, 203, 565, 1758, 1071, 3410, 31, 203, 565, 1758, 1071, 20084, 5541, 31, 203, 203, 565, 871, 14223, 9646, 5310, 5912, 2570, 10206, 12, 2867, 8808, 389, 685, 7423, 5541, 1769, 203, 565, 871, 14223, 9646, 5310, 5912, 9556, 12, 2867, 8808, 389, 2704, 5541, 1769, 203, 565, 871, 14223, 9646, 5310, 5912, 23163, 5621, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 291, 5541, 12, 3576, 18, 15330, 13, 422, 638, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 353, 5541, 12, 2867, 389, 2867, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 261, 67, 2867, 422, 3410, 1769, 203, 565, 289, 203, 203, 565, 445, 18711, 5460, 12565, 5912, 12, 2867, 389, 685, 7423, 5541, 13, 203, 3639, 1071, 203, 3639, 1338, 5541, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2583, 24899, 685, 7423, 5541, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 24899, 685, 7423, 5541, 480, 1758, 12, 2211, 10019, 203, 3639, 2583, 24899, 685, 7423, 5541, 480, 3410, 1769, 203, 203, 3639, 20084, 5541, 273, 389, 685, 7423, 5541, 31, 203, 203, 3639, 3626, 14223, 9646, 5310, 5912, 2570, 10206, 12, 685, 7423, 5541, 1769, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 3755, 5460, 12565, 5912, 1435, 1071, 1338, 5541, 1135, 261, 6430, 13, 288, 203, 2 ]
/** *Submitted for verification at Etherscan.io on 2020-01-13 */ // File: contracts/loopring/impl/BrokerData.sol pragma solidity 0.5.7; library BrokerData { struct BrokerOrder { address owner; bytes32 orderHash; uint fillAmountB; uint requestedAmountS; uint requestedFeeAmount; address tokenRecipient; bytes extraData; } struct BrokerApprovalRequest { BrokerOrder[] orders; address tokenS; address tokenB; address feeToken; uint totalFillAmountB; uint totalRequestedAmountS; uint totalRequestedFeeAmount; } struct BrokerInterceptorReport { address owner; address broker; bytes32 orderHash; address tokenB; address tokenS; address feeToken; uint fillAmountB; uint spentAmountS; uint spentFeeAmount; address tokenRecipient; bytes extraData; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on 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); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { //require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: contracts/market-making/sources/ERC20.sol contract ERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); uint256 internal _totalSupply; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } // File: contracts/market-making/sources/uniswap/UniswapExchange.sol pragma solidity ^0.5.0; interface IUniswapFactory { event NewExchange(address indexed token, address indexed exchange); function initializeFactory(address template) external; function createExchange(address token) external returns (address payable); function getExchange(address token) external view returns (address payable); function getToken(address token) external view returns (address); function getTokenWihId(uint256 token_id) external view returns (address); } interface IUniswapExchange { event TokenPurchase(address indexed buyer, uint256 indexed eth_sold, uint256 indexed tokens_bought); event EthPurchase(address indexed buyer, uint256 indexed tokens_sold, uint256 indexed eth_bought); event AddLiquidity(address indexed provider, uint256 indexed eth_amount, uint256 indexed token_amount); event RemoveLiquidity(address indexed provider, uint256 indexed eth_amount, uint256 indexed token_amount); function () external payable; function getInputPrice(uint256 input_amount, uint256 input_reserve, uint256 output_reserve) external view returns (uint256); function getOutputPrice(uint256 output_amount, uint256 input_reserve, uint256 output_reserve) external view returns (uint256); function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) external payable returns (uint256); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external payable returns(uint256); function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) external payable returns(uint256); function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256); function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline) external returns (uint256); function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient) external returns (uint256); function tokenToEthSwapOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline) external returns (uint256); function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256); function tokenToTokenSwapInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) external returns (uint256); function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) external returns (uint256); function tokenToTokenSwapOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) external returns (uint256); function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) external returns (uint256); function tokenToExchangeSwapInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address exchange_addr) external returns (uint256); function tokenToExchangeTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address exchange_addr) external returns (uint256); function tokenToExchangeSwapOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address exchange_addr) external returns (uint256); function tokenToExchangeTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address exchange_addr) external returns (uint256); function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256); function getEthToTokenOutputPrice(uint256 tokens_bought) external view returns (uint256); function getTokenToEthInputPrice(uint256 tokens_sold) external view returns (uint256); function getTokenToEthOutputPrice(uint256 eth_bought) external view returns (uint256); function tokenAddress() external view returns (address); function factoryAddress() external view returns (address); function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256); function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256); } contract UniswapExchange is ERC20 { /***********************************| | Variables && Events | |__________________________________*/ // Variables bytes32 public name; // Uniswap V1 bytes32 public symbol; // UNI-V1 uint256 public decimals; // 18 ERC20 token; // address of the ERC20 token traded on this contract IUniswapFactory factory; // interface for the factory that created this contract // Events event TokenPurchase(address indexed buyer, uint256 indexed eth_sold, uint256 indexed tokens_bought); event EthPurchase(address indexed buyer, uint256 indexed tokens_sold, uint256 indexed eth_bought); event AddLiquidity(address indexed provider, uint256 indexed eth_amount, uint256 indexed token_amount); event RemoveLiquidity(address indexed provider, uint256 indexed eth_amount, uint256 indexed token_amount); /***********************************| | Constsructor | |__________________________________*/ /** * @dev This function acts as a contract constructor which is not currently supported in contracts deployed * using create_with_code_of(). It is called once by the factory during contract creation. */ function setup(address token_addr) public { require( address(factory) == address(0) && address(token) == address(0) && token_addr != address(0), "INVALID_ADDRESS" ); factory = IUniswapFactory(msg.sender); token = ERC20(token_addr); name = 0x556e697377617020563100000000000000000000000000000000000000000000; symbol = 0x554e492d56310000000000000000000000000000000000000000000000000000; decimals = 18; } /***********************************| | Exchange Functions | |__________________________________*/ /** * @notice Convert ETH to Tokens. * @dev User specifies exact input (msg.value). * @dev User cannot specify minimum output or deadline. */ function () external payable { ethToTokenInput(msg.value, 1, block.timestamp, msg.sender, msg.sender); } /** * @dev Pricing function for converting between ETH && Tokens. * @param input_amount Amount of ETH or Tokens being sold. * @param input_reserve Amount of ETH or Tokens (input type) in exchange reserves. * @param output_reserve Amount of ETH or Tokens (output type) in exchange reserves. * @return Amount of ETH or Tokens bought. */ function getInputPrice(uint256 input_amount, uint256 input_reserve, uint256 output_reserve) public view returns (uint256) { require(input_reserve > 0 && output_reserve > 0, "INVALID_VALUE"); uint256 input_amount_with_fee = input_amount.mul(997); uint256 numerator = input_amount_with_fee.mul(output_reserve); uint256 denominator = input_reserve.mul(1000).add(input_amount_with_fee); return numerator / denominator; } /** * @dev Pricing function for converting between ETH && Tokens. * @param output_amount Amount of ETH or Tokens being bought. * @param input_reserve Amount of ETH or Tokens (input type) in exchange reserves. * @param output_reserve Amount of ETH or Tokens (output type) in exchange reserves. * @return Amount of ETH or Tokens sold. */ function getOutputPrice(uint256 output_amount, uint256 input_reserve, uint256 output_reserve) public view returns (uint256) { require(input_reserve > 0 && output_reserve > 0); uint256 numerator = input_reserve.mul(output_amount).mul(1000); uint256 denominator = (output_reserve.sub(output_amount)).mul(997); return (numerator / denominator).add(1); } function ethToTokenInput(uint256 eth_sold, uint256 min_tokens, uint256 deadline, address buyer, address recipient) private returns (uint256) { require(deadline >= block.timestamp && eth_sold > 0 && min_tokens > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 tokens_bought = getInputPrice(eth_sold, address(this).balance.sub(eth_sold), token_reserve); require(tokens_bought >= min_tokens); require(token.transfer(recipient, tokens_bought)); emit TokenPurchase(buyer, eth_sold, tokens_bought); return tokens_bought; } /** * @notice Convert ETH to Tokens. * @dev User specifies exact input (msg.value) && minimum output. * @param min_tokens Minimum Tokens bought. * @param deadline Time after which this transaction can no longer be executed. * @return Amount of Tokens bought. */ function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) public payable returns (uint256) { return ethToTokenInput(msg.value, min_tokens, deadline, msg.sender, msg.sender); } /** * @notice Convert ETH to Tokens && transfers Tokens to recipient. * @dev User specifies exact input (msg.value) && minimum output * @param min_tokens Minimum Tokens bought. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output Tokens. * @return Amount of Tokens bought. */ function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) public payable returns(uint256) { require(recipient != address(this) && recipient != address(0)); return ethToTokenInput(msg.value, min_tokens, deadline, msg.sender, recipient); } function ethToTokenOutput(uint256 tokens_bought, uint256 max_eth, uint256 deadline, address payable buyer, address recipient) private returns (uint256) { require(deadline >= block.timestamp && tokens_bought > 0 && max_eth > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_sold = getOutputPrice(tokens_bought, address(this).balance.sub(max_eth), token_reserve); // Throws if eth_sold > max_eth uint256 eth_refund = max_eth.sub(eth_sold); if (eth_refund > 0) { buyer.transfer(eth_refund); } require(token.transfer(recipient, tokens_bought)); emit TokenPurchase(buyer, eth_sold, tokens_bought); return eth_sold; } /** * @notice Convert ETH to Tokens. * @dev User specifies maximum input (msg.value) && exact output. * @param tokens_bought Amount of tokens bought. * @param deadline Time after which this transaction can no longer be executed. * @return Amount of ETH sold. */ function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) public payable returns(uint256) { return ethToTokenOutput(tokens_bought, msg.value, deadline, msg.sender, msg.sender); } /** * @notice Convert ETH to Tokens && transfers Tokens to recipient. * @dev User specifies maximum input (msg.value) && exact output. * @param tokens_bought Amount of tokens bought. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output Tokens. * @return Amount of ETH sold. */ function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) public payable returns (uint256) { require(recipient != address(this) && recipient != address(0)); return ethToTokenOutput(tokens_bought, msg.value, deadline, msg.sender, recipient); } function tokenToEthInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address buyer, address payable recipient) private returns (uint256) { require(deadline >= block.timestamp && tokens_sold > 0 && min_eth > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_bought = getInputPrice(tokens_sold, token_reserve, address(this).balance); uint256 wei_bought = eth_bought; require(wei_bought >= min_eth); recipient.transfer(wei_bought); require(token.transferFrom(buyer, address(this), tokens_sold)); emit EthPurchase(buyer, tokens_sold, wei_bought); return wei_bought; } /** * @notice Convert Tokens to ETH. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_eth Minimum ETH purchased. * @param deadline Time after which this transaction can no longer be executed. * @return Amount of ETH bought. */ function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline) public returns (uint256) { return tokenToEthInput(tokens_sold, min_eth, deadline, msg.sender, msg.sender); } /** * @notice Convert Tokens to ETH && transfers ETH to recipient. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_eth Minimum ETH purchased. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @return Amount of ETH bought. */ function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address payable recipient) public returns (uint256) { require(recipient != address(this) && recipient != address(0)); return tokenToEthInput(tokens_sold, min_eth, deadline, msg.sender, recipient); } function tokenToEthOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address buyer, address payable recipient) private returns (uint256) { require(deadline >= block.timestamp && eth_bought > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 tokens_sold = getOutputPrice(eth_bought, token_reserve, address(this).balance); // tokens sold is always > 0 require(max_tokens >= tokens_sold); recipient.transfer(eth_bought); require(token.transferFrom(buyer, address(this), tokens_sold)); emit EthPurchase(buyer, tokens_sold, eth_bought); return tokens_sold; } /** * @notice Convert Tokens to ETH. * @dev User specifies maximum input && exact output. * @param eth_bought Amount of ETH purchased. * @param max_tokens Maximum Tokens sold. * @param deadline Time after which this transaction can no longer be executed. * @return Amount of Tokens sold. */ function tokenToEthSwapOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline) public returns (uint256) { return tokenToEthOutput(eth_bought, max_tokens, deadline, msg.sender, msg.sender); } /** * @notice Convert Tokens to ETH && transfers ETH to recipient. * @dev User specifies maximum input && exact output. * @param eth_bought Amount of ETH purchased. * @param max_tokens Maximum Tokens sold. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @return Amount of Tokens sold. */ function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address payable recipient) public returns (uint256) { require(recipient != address(this) && recipient != address(0)); return tokenToEthOutput(eth_bought, max_tokens, deadline, msg.sender, recipient); } function tokenToTokenInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address buyer, address recipient, address payable exchange_addr) private returns (uint256) { require(deadline >= block.timestamp && tokens_sold > 0 && min_tokens_bought > 0 && min_eth_bought > 0); require(exchange_addr != address(this) && exchange_addr != address(0)); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_bought = getInputPrice(tokens_sold, token_reserve, address(this).balance); uint256 wei_bought = eth_bought; require(wei_bought >= min_eth_bought); require(token.transferFrom(buyer, address(this), tokens_sold)); uint256 tokens_bought = IUniswapExchange(exchange_addr).ethToTokenTransferInput.value(wei_bought)(min_tokens_bought, deadline, recipient); emit EthPurchase(buyer, tokens_sold, wei_bought); return tokens_bought; } /** * @notice Convert Tokens (token) to Tokens (token_addr). * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_tokens_bought Minimum Tokens (token_addr) purchased. * @param min_eth_bought Minimum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param token_addr The address of the token being purchased. * @return Amount of Tokens (token_addr) bought. */ function tokenToTokenSwapInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) public returns (uint256) { address payable exchange_addr = factory.getExchange(token_addr); return tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, msg.sender, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (token_addr) && transfers * Tokens (token_addr) to recipient. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_tokens_bought Minimum Tokens (token_addr) purchased. * @param min_eth_bought Minimum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @param token_addr The address of the token being purchased. * @return Amount of Tokens (token_addr) bought. */ function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) public returns (uint256) { address payable exchange_addr = factory.getExchange(token_addr); return tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, recipient, exchange_addr); } function tokenToTokenOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address buyer, address recipient, address payable exchange_addr) private returns (uint256) { require(deadline >= block.timestamp && (tokens_bought > 0 && max_eth_sold > 0)); require(exchange_addr != address(this) && exchange_addr != address(0)); uint256 eth_bought = IUniswapExchange(exchange_addr).getEthToTokenOutputPrice(tokens_bought); uint256 token_reserve = token.balanceOf(address(this)); uint256 tokens_sold = getOutputPrice(eth_bought, token_reserve, address(this).balance); // tokens sold is always > 0 require(max_tokens_sold >= tokens_sold && max_eth_sold >= eth_bought); require(token.transferFrom(buyer, address(this), tokens_sold)); uint256 eth_sold = IUniswapExchange(exchange_addr).ethToTokenTransferOutput.value(eth_bought)(tokens_bought, deadline, recipient); emit EthPurchase(buyer, tokens_sold, eth_bought); return tokens_sold; } /** * @notice Convert Tokens (token) to Tokens (token_addr). * @dev User specifies maximum input && exact output. * @param tokens_bought Amount of Tokens (token_addr) bought. * @param max_tokens_sold Maximum Tokens (token) sold. * @param max_eth_sold Maximum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param token_addr The address of the token being purchased. * @return Amount of Tokens (token) sold. */ function tokenToTokenSwapOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) public returns (uint256) { address payable exchange_addr = factory.getExchange(token_addr); return tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, msg.sender, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (token_addr) && transfers * Tokens (token_addr) to recipient. * @dev User specifies maximum input && exact output. * @param tokens_bought Amount of Tokens (token_addr) bought. * @param max_tokens_sold Maximum Tokens (token) sold. * @param max_eth_sold Maximum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @param token_addr The address of the token being purchased. * @return Amount of Tokens (token) sold. */ function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) public returns (uint256) { address payable exchange_addr = factory.getExchange(token_addr); return tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, recipient, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (exchange_addr.token). * @dev Allows trades through contracts that were not deployed from the same factory. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_tokens_bought Minimum Tokens (token_addr) purchased. * @param min_eth_bought Minimum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param exchange_addr The address of the exchange for the token being purchased. * @return Amount of Tokens (exchange_addr.token) bought. */ function tokenToExchangeSwapInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address payable exchange_addr) public returns (uint256) { return tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, msg.sender, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (exchange_addr.token) && transfers * Tokens (exchange_addr.token) to recipient. * @dev Allows trades through contracts that were not deployed from the same factory. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_tokens_bought Minimum Tokens (token_addr) purchased. * @param min_eth_bought Minimum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @param exchange_addr The address of the exchange for the token being purchased. * @return Amount of Tokens (exchange_addr.token) bought. */ function tokenToExchangeTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address payable exchange_addr) public returns (uint256) { require(recipient != address(this)); return tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, recipient, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (exchange_addr.token). * @dev Allows trades through contracts that were not deployed from the same factory. * @dev User specifies maximum input && exact output. * @param tokens_bought Amount of Tokens (token_addr) bought. * @param max_tokens_sold Maximum Tokens (token) sold. * @param max_eth_sold Maximum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param exchange_addr The address of the exchange for the token being purchased. * @return Amount of Tokens (token) sold. */ function tokenToExchangeSwapOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address payable exchange_addr) public returns (uint256) { return tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, msg.sender, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (exchange_addr.token) && transfers * Tokens (exchange_addr.token) to recipient. * @dev Allows trades through contracts that were not deployed from the same factory. * @dev User specifies maximum input && exact output. * @param tokens_bought Amount of Tokens (token_addr) bought. * @param max_tokens_sold Maximum Tokens (token) sold. * @param max_eth_sold Maximum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @param exchange_addr The address of the exchange for the token being purchased. * @return Amount of Tokens (token) sold. */ function tokenToExchangeTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address payable exchange_addr) public returns (uint256) { require(recipient != address(this)); return tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, recipient, exchange_addr); } /***********************************| | Getter Functions | |__________________________________*/ /** * @notice Public price function for ETH to Token trades with an exact input. * @param eth_sold Amount of ETH sold. * @return Amount of Tokens that can be bought with input ETH. */ function getEthToTokenInputPrice(uint256 eth_sold) public view returns (uint256) { require(eth_sold > 0); uint256 token_reserve = token.balanceOf(address(this)); return getInputPrice(eth_sold, address(this).balance, token_reserve); } /** * @notice Public price function for ETH to Token trades with an exact output. * @param tokens_bought Amount of Tokens bought. * @return Amount of ETH needed to buy output Tokens. */ function getEthToTokenOutputPrice(uint256 tokens_bought) public view returns (uint256) { require(tokens_bought > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_sold = getOutputPrice(tokens_bought, address(this).balance, token_reserve); return eth_sold; } /** * @notice Public price function for Token to ETH trades with an exact input. * @param tokens_sold Amount of Tokens sold. * @return Amount of ETH that can be bought with input Tokens. */ function getTokenToEthInputPrice(uint256 tokens_sold) public view returns (uint256) { require(tokens_sold > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_bought = getInputPrice(tokens_sold, token_reserve, address(this).balance); return eth_bought; } /** * @notice Public price function for Token to ETH trades with an exact output. * @param eth_bought Amount of output ETH. * @return Amount of Tokens needed to buy output ETH. */ function getTokenToEthOutputPrice(uint256 eth_bought) public view returns (uint256) { require(eth_bought > 0); uint256 token_reserve = token.balanceOf(address(this)); return getOutputPrice(eth_bought, token_reserve, address(this).balance); } /** * @return Address of Token that is sold on this exchange. */ function tokenAddress() public view returns (address) { return address(token); } /** * @return Address of factory that created this exchange. */ function factoryAddress() public view returns (address) { return address(factory); } /***********************************| | Liquidity Functions | |__________________________________*/ /** * @notice Deposit ETH && Tokens (token) at current ratio to mint UNI tokens. * @dev min_liquidity does nothing when total UNI supply is 0. * @param min_liquidity Minimum number of UNI sender will mint if total UNI supply is greater than 0. * @param max_tokens Maximum number of tokens deposited. Deposits max amount if total UNI supply is 0. * @param deadline Time after which this transaction can no longer be executed. * @return The amount of UNI minted. */ function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) public payable returns (uint256) { require(deadline > block.timestamp && max_tokens > 0 && msg.value > 0, 'UniswapExchange#addLiquidity: INVALID_ARGUMENT'); uint256 total_liquidity = _totalSupply; if (total_liquidity > 0) { require(min_liquidity > 0); uint256 eth_reserve = address(this).balance.sub(msg.value); uint256 token_reserve = token.balanceOf(address(this)); uint256 token_amount = (msg.value.mul(token_reserve) / eth_reserve).add(1); uint256 liquidity_minted = msg.value.mul(total_liquidity) / eth_reserve; require(max_tokens >= token_amount && liquidity_minted >= min_liquidity); _balances[msg.sender] = _balances[msg.sender].add(liquidity_minted); _totalSupply = total_liquidity.add(liquidity_minted); require(token.transferFrom(msg.sender, address(this), token_amount)); emit AddLiquidity(msg.sender, msg.value, token_amount); emit Transfer(address(0), msg.sender, liquidity_minted); return liquidity_minted; } else { require(address(factory) != address(0) && address(token) != address(0) && msg.value >= 1000000000, "INVALID_VALUE"); require(factory.getExchange(address(token)) == address(this)); uint256 token_amount = max_tokens; uint256 initial_liquidity = address(this).balance; _totalSupply = initial_liquidity; _balances[msg.sender] = initial_liquidity; require(token.transferFrom(msg.sender, address(this), token_amount)); emit AddLiquidity(msg.sender, msg.value, token_amount); emit Transfer(address(0), msg.sender, initial_liquidity); return initial_liquidity; } } /** * @dev Burn UNI tokens to withdraw ETH && Tokens at current ratio. * @param amount Amount of UNI burned. * @param min_eth Minimum ETH withdrawn. * @param min_tokens Minimum Tokens withdrawn. * @param deadline Time after which this transaction can no longer be executed. * @return The amount of ETH && Tokens withdrawn. */ function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) public returns (uint256, uint256) { require(amount > 0 && deadline > block.timestamp && min_eth > 0 && min_tokens > 0); uint256 total_liquidity = _totalSupply; require(total_liquidity > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_amount = amount.mul(address(this).balance) / total_liquidity; uint256 token_amount = amount.mul(token_reserve) / total_liquidity; require(eth_amount >= min_eth && token_amount >= min_tokens); _balances[msg.sender] = _balances[msg.sender].sub(amount); //injected INTEGER OVERFLOW OR UNDERFLOW _totalSupply = total_liquidity.sub(amount); //injected INTEGER OVERFLOW OR UNDERFLOW msg.sender.transfer(eth_amount); require(token.transfer(msg.sender, token_amount)); emit RemoveLiquidity(msg.sender, eth_amount, token_amount); emit Transfer(msg.sender, address(0), amount); return (eth_amount, token_amount); } } // File: contracts/market-making/sources/WETH.sol /* * Copyright 2019 Dolomite * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity 0.5.7; contract WETH { event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); function totalSupply() public view returns (uint); function balanceOf(address guy) public view returns (uint); function allowance(address src, address guy) public view returns (uint); function approve(address guy, uint wad) public returns (bool); function transfer(address dst, uint wad) public returns (bool); function transferFrom(address src, address dst, uint wad) public returns (bool); function deposit() public payable; function withdraw(uint wad) public; } // File: contracts/loopring/iface/IBrokerDelegate.sol /* * Copyright 2019 Dolomite * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity 0.5.7; pragma experimental ABIEncoderV2; /** * @title IBrokerDelegate * @author Zack Rubenstein */ interface IBrokerDelegate { /* * Loopring requests an allowance be set on a given token for a specified amount. Order details * are provided (tokenS, totalAmountS, tokenB, totalAmountB, orderTokenRecipient, extraOrderData) * to aid in any calculations or on-chain exchange of assets that may be required. The last 4 * parameters concern the actual token approval being requested of the broker. * * @returns Whether or not onOrderFillReport should be called for orders using this broker */ function brokerRequestAllowance(BrokerData.BrokerApprovalRequest calldata request) external returns (bool); /* * After Loopring performs all of the transfers necessary to complete all the submitted * rings it will call this function for every order's brokerInterceptor (if set) passing * along the final fill counts for tokenB, tokenS and feeToken. This allows actions to be * performed on a per-order basis after all tokenS/feeToken funds have left the order owner's * possession and the tokenB funds have been transferred to the order owner's intended recipient */ function onOrderFillReport(BrokerData.BrokerInterceptorReport calldata fillReport) external; /* * Get the available token balance controlled by the broker on behalf of an address (owner) */ function brokerBalanceOf(address owner, address token) external view returns (uint); } // File: contracts/dolomite-direct/DolomiteDirectV1.sol /* * Copyright 2019 Dolomite * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity 0.5.7;interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external; function transferFrom(address from, address to, uint256 value) external; function approve(address spender, uint256 value) external; } library Types { struct RequestFee { address feeRecipient; address feeToken; uint feeAmount; } struct RequestSignature { uint8 v; bytes32 r; bytes32 s; } enum RequestType { Update, Transfer, Approve, Perform } struct Request { address owner; address target; RequestType requestType; bytes payload; uint nonce; RequestFee fee; RequestSignature signature; } struct TransferRequest { address token; address recipient; uint amount; bool unwrap; } } interface IDolomiteMarginTradingBroker { function brokerMarginRequestApproval(address owner, address token, uint amount) external; function brokerMarginGetTrader(address owner, bytes calldata orderData) external view returns (address); } interface IVersionable { /* * Is called by IDepositContractRegistry when this version * is being upgraded to. Will call `versionEndUsage` on the * old contract before calling this one */ function versionBeginUsage( address owner, address payable depositAddress, address oldVersion, bytes calldata additionalData ) external; /* * Is called by IDepositContractRegistry when this version is * being upgraded from. IDepositContractRegistry will then call * `versionBeginUsage` on the new contract */ function versionEndUsage( address owner, address payable depositAddress, address newVersion, bytes calldata additionalData ) external; } interface IDepositContract { function perform( address addr, string calldata signature, bytes calldata encodedParams, uint value ) external returns (bytes memory); } interface IDepositContractRegistry { function depositAddressOf(address owner) external view returns (address payable); function operatorOf(address owner, address operator) external returns (bool); } library DepositContractHelper { function wrapAndTransferToken(IDepositContract self, address token, address recipient, uint amount, address wethAddress) internal { if (token == wethAddress) { uint etherBalance = address(self).balance; if (etherBalance > 0) wrapEth(self, token, etherBalance); } transferToken(self, token, recipient, amount); } function transferToken(IDepositContract self, address token, address recipient, uint amount) internal { self.perform(token, "transfer(address,uint256)", abi.encode(recipient, amount), 0); } function transferEth(IDepositContract self, address recipient, uint amount) internal { self.perform(recipient, "", abi.encode(), amount); } function approveToken(IDepositContract self, address token, address broker, uint amount) internal { self.perform(token, "approve(address,uint256)", abi.encode(broker, amount), 0); } function wrapEth(IDepositContract self, address wethToken, uint amount) internal { self.perform(wethToken, "deposit()", abi.encode(), amount); } function unwrapWeth(IDepositContract self, address wethToken, uint amount) internal { self.perform(wethToken, "withdraw(uint256)", abi.encode(amount), 0); } function setDydxOperator(IDepositContract self, address dydxContract, address operator) internal { bytes memory encodedParams = abi.encode( bytes32(0x0000000000000000000000000000000000000000000000000000000000000020), bytes32(0x0000000000000000000000000000000000000000000000000000000000000001), operator, bytes32(0x0000000000000000000000000000000000000000000000000000000000000001) ); self.perform(dydxContract, "setOperators((address,bool)[])", encodedParams, 0); } } library RequestHelper { bytes constant personalPrefix = "\x19Ethereum Signed Message:\n32"; function getSigner(Types.Request memory self) internal pure returns (address) { bytes32 messageHash = keccak256(abi.encode( self.owner, self.target, self.requestType, self.payload, self.nonce, abi.encode(self.fee.feeRecipient, self.fee.feeToken, self.fee.feeAmount) )); bytes32 prefixedHash = keccak256(abi.encodePacked(personalPrefix, messageHash)); return ecrecover(prefixedHash, self.signature.v, self.signature.r, self.signature.s); } function decodeTransferRequest(Types.Request memory self) internal pure returns (Types.TransferRequest memory transferRequest) { require(self.requestType == Types.RequestType.Transfer, "INVALID_REQUEST_TYPE"); ( transferRequest.token, transferRequest.recipient, transferRequest.amount, transferRequest.unwrap ) = abi.decode(self.payload, (address, address, uint, bool)); } } contract Requestable { using RequestHelper for Types.Request; mapping(address => uint) nonces; function validateRequest(Types.Request memory request) internal { require(request.target == address(this), "INVALID_TARGET"); require(request.getSigner() == request.owner, "INVALID_SIGNATURE"); require(nonces[request.owner] + 1 == request.nonce, "INVALID_NONCE"); if (request.fee.feeAmount > 0) { require(balanceOf(request.owner, request.fee.feeToken) >= request.fee.feeAmount, "INSUFFICIENT_FEE_BALANCE"); } nonces[request.owner] += 1; } function completeRequest(Types.Request memory request) internal { if (request.fee.feeAmount > 0) { _payRequestFee(request.owner, request.fee.feeToken, request.fee.feeRecipient, request.fee.feeAmount); } } function nonceOf(address owner) public view returns (uint) { return nonces[owner]; } // Abtract functions function balanceOf(address owner, address token) public view returns (uint); function _payRequestFee(address owner, address feeToken, address feeRecipient, uint feeAmount) internal; } /** * @title DolomiteDirectV1 * @author Zack Rubenstein * * Interfaces with the IDepositContractRegistry and individual * IDepositContracts to enable smart-wallet functionality as well * as spot and margin trading on Dolomite (through Loopring & dYdX) */ contract DolomiteDirectV1 is Requestable, IVersionable, IDolomiteMarginTradingBroker { using DepositContractHelper for IDepositContract; using SafeMath for uint; IDepositContractRegistry public registry; address public loopringDelegate; address public dolomiteMarginProtocolAddress; address public dydxProtocolAddress; address public wethTokenAddress; constructor( address _depositContractRegistry, address _loopringDelegate, address _dolomiteMarginProtocol, address _dydxProtocolAddress, address _wethTokenAddress ) public { registry = IDepositContractRegistry(_depositContractRegistry); loopringDelegate = _loopringDelegate; dolomiteMarginProtocolAddress = _dolomiteMarginProtocol; dydxProtocolAddress = _dydxProtocolAddress; wethTokenAddress = _wethTokenAddress; } /* * Returns the available balance for an owner that this contract manages. * If the token is WETH, it returns the sum of the ETH and WETH balance, * as ETH is automatically wrapped upon transfers (unless the unwrap option is * set to true in the transfer request) */ function balanceOf(address owner, address token) public view returns (uint) { address depositAddress = registry.depositAddressOf(owner); uint tokenBalance = IERC20(token).balanceOf(depositAddress); if (token == wethTokenAddress) tokenBalance = tokenBalance.add(depositAddress.balance); return tokenBalance; } /* * Send up a signed transfer request and the given amount tokens * is transfered to the specified recipient. */ function transfer(Types.Request memory request) public { validateRequest(request); Types.TransferRequest memory transferRequest = request.decodeTransferRequest(); address payable depositAddress = registry.depositAddressOf(request.owner); _transfer( transferRequest.token, depositAddress, transferRequest.recipient, transferRequest.amount, transferRequest.unwrap ); completeRequest(request); } // ============================= function _transfer(address token, address payable depositAddress, address recipient, uint amount, bool unwrap) internal { IDepositContract depositContract = IDepositContract(depositAddress); if (token == wethTokenAddress && unwrap) { if (depositAddress.balance < amount) { depositContract.unwrapWeth(wethTokenAddress, amount.sub(depositAddress.balance)); } depositContract.transferEth(recipient, amount); return; } depositContract.wrapAndTransferToken(token, recipient, amount, wethTokenAddress); } // ----------------------------- // Loopring Broker Delegate function brokerRequestAllowance(BrokerData.BrokerApprovalRequest memory request) public returns (bool) { require(msg.sender == loopringDelegate); BrokerData.BrokerOrder[] memory mergedOrders = new BrokerData.BrokerOrder[](request.orders.length); uint numMergedOrders = 1; mergedOrders[0] = request.orders[0]; if (request.orders.length > 1) { for (uint i = 1; i < request.orders.length; i++) { bool isDuplicate = false; for (uint b = 0; b < numMergedOrders; b++) { if (request.orders[i].owner == mergedOrders[b].owner) { mergedOrders[b].requestedAmountS += request.orders[i].requestedAmountS; mergedOrders[b].requestedFeeAmount += request.orders[i].requestedFeeAmount; isDuplicate = true; break; } } if (!isDuplicate) { mergedOrders[numMergedOrders] = request.orders[i]; numMergedOrders += 1; } } } for (uint j = 0; j < numMergedOrders; j++) { BrokerData.BrokerOrder memory order = mergedOrders[j]; address payable depositAddress = registry.depositAddressOf(order.owner); _transfer(request.tokenS, depositAddress, address(this), order.requestedAmountS, false); if (order.requestedFeeAmount > 0) _transfer(request.feeToken, depositAddress, address(this), order.requestedFeeAmount, false); } return false; // Does not use onOrderFillReport } function onOrderFillReport(BrokerData.BrokerInterceptorReport memory fillReport) public { // Do nothing } function brokerBalanceOf(address owner, address tokenAddress) public view returns (uint) { return balanceOf(owner, tokenAddress); } // ---------------------------- // Dolomite Margin Trading Broker function brokerMarginRequestApproval(address owner, address token, uint amount) public { require(msg.sender == dolomiteMarginProtocolAddress); address payable depositAddress = registry.depositAddressOf(owner); _transfer(token, depositAddress, address(this), amount, false); } function brokerMarginGetTrader(address owner, bytes memory orderData) public view returns (address) { return registry.depositAddressOf(owner); } // ----------------------------- // Requestable function _payRequestFee(address owner, address feeToken, address feeRecipient, uint feeAmount) internal { _transfer(feeToken, registry.depositAddressOf(owner), feeRecipient, feeAmount, false); } // ----------------------------- // Versionable function versionBeginUsage( address owner, address payable depositAddress, address oldVersion, bytes calldata additionalData ) external { // Approve the DolomiteMarginProtocol as an operator for the deposit contract's dYdX account IDepositContract(depositAddress).setDydxOperator(dydxProtocolAddress, dolomiteMarginProtocolAddress); } function versionEndUsage( address owner, address payable depositAddress, address newVersion, bytes calldata additionalData ) external { /* do nothing */ } // ============================= // Administrative /* * Tokens are held in individual deposit contracts, the only time a trader's * funds are held by this contract is when Loopring or dYdX requests a trader's * tokens, and immediately upon this contract moving funds into itself, Loopring * or dYdX will move the funds out and into themselves. Thus, we can open this * function up for anyone to call to set or reset the approval for Loopring and * dYdX for a given token. The reason these approvals are set globally and not * on an as-needed (per fill) basis is to reduce gas costs. */ function enableTrading(address token) external { IERC20(token).approve(loopringDelegate, 10**70); IERC20(token).approve(dolomiteMarginProtocolAddress, 10**70); } } // File: contracts/market-making/helper/MakerBrokerBase.sol pragma solidity 0.5.7; contract MakerBrokerBase { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, "NOT_OWNER"); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0x0), "ZERO_ADDRESS"); owner = newOwner; } function withdrawDust(address token) external { require(msg.sender == owner, "UNAUTHORIZED"); ERC20(token).transfer(msg.sender, ERC20(token).balanceOf(address(this))); } function withdrawEthDust() external { require(msg.sender == owner, "UNAUTHORIZED"); msg.sender.transfer(address(this).balance); } } // File: contracts/market-making/UniswapMakerBroker.sol /* * Copyright 2019 Dolomite * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity 0.5.7; library UniswapFactoryHelper { function exchangeOf(IUniswapFactory self, address token) internal returns (IUniswapExchange) { return IUniswapExchange(self.getExchange(token)); } } /* * Inherits Loopring's IBrokerDelegate and sources liquidity from Uniswap * when the Loopring protocol requests a token approval. Because the Loopring * protocol expects the taker order to precede maker orders, and non-brokered * transfers occur before before brokered transfers, it is guaranteed that this * broker contract will receive the necessary tokens to trade, right before it * sets the approval and the Loopring protocol transfers the tokens out. Thus, * liquidity can be sourced on-chain with no money down! */ contract UniswapMakerBroker is MakerBrokerBase { using UniswapFactoryHelper for IUniswapFactory; address public wethTokenAddress; address public loopringProtocol; IUniswapFactory public uniswapFactory; mapping(address => address) public tokenToExchange; mapping(address => bool) public tokenToIsSetup; constructor(address _loopringProtocol, address _uniswapFactory, address _wethTokenAddress) public { loopringProtocol = _loopringProtocol; wethTokenAddress = _wethTokenAddress; uniswapFactory = IUniswapFactory(_uniswapFactory); } function setupToken(address token, bool setupExchange) public { if (setupExchange) { IUniswapExchange exchange = uniswapFactory.exchangeOf(token); ERC20(token).approve(address(exchange), 10 ** 70); tokenToExchange[token] = address(exchange); } ERC20(token).approve(loopringProtocol, 10 ** 70); tokenToIsSetup[token] = true; } function () external payable { // No op, but accepts ETH being sent to this contract. } // -------------------------------- // Loopring Broker Delegate function brokerRequestAllowance(BrokerData.BrokerApprovalRequest memory request) public returns (bool) { require(msg.sender == loopringProtocol, "Uniswap MakerBroker: Unauthorized caller"); require(tokenToIsSetup[request.tokenS], "Uniswap MakerBroker: tokenS is not setup yet"); for (uint i = 0; i < request.orders.length; i++) { require(request.orders[i].tokenRecipient == address(this), "Uniswap MakerBroker: Order tokenRecipient must be this broker"); require(request.orders[i].owner == owner, "Uniswap MakerBroker: Order owner must be the owner of this contract"); } if (request.tokenB == wethTokenAddress) { // We need to convert WETH to ETH to 1) avoid double fee payment on Uniswap and 2) get the best price on Uniswap WETH(wethTokenAddress).withdraw(request.totalFillAmountB); } // perform exchange bool isTokenBExchangeWrapper = abi.decode(request.orders[0].extraData, (bool)); IUniswapExchange exchange; if (isTokenBExchangeWrapper) { exchange = IUniswapExchange(address(uint160(tokenToExchange[request.tokenB]))); } else { exchange = IUniswapExchange(address(uint160(tokenToExchange[request.tokenS]))); } uint deadline = block.timestamp + 1; uint exchangeAmount; if (request.tokenS == wethTokenAddress) { exchangeAmount = exchange.tokenToEthSwapInput(request.totalFillAmountB, request.totalRequestedAmountS, deadline); } else if (request.tokenB == wethTokenAddress) { exchangeAmount = exchange.ethToTokenSwapInput.value(request.totalFillAmountB)(request.totalRequestedAmountS, deadline); } else { // Pure token to token address tokenToBuy; if (isTokenBExchangeWrapper) { request.tokenS; } else { request.tokenB; } exchangeAmount = exchange.tokenToTokenSwapInput( request.totalFillAmountB, request.totalRequestedAmountS, /* minEthBoughtInWei */ 1, // We don't care about the token <-> ETH exchange rate as long as we get enough tokenB deadline, tokenToBuy); } if (request.tokenS == wethTokenAddress) { // Orders on Dolomite require we use WETH instead of ETH, so we must convert it back WETH(wethTokenAddress).deposit.value(exchangeAmount)(); } return false; } function onOrderFillReport(BrokerData.BrokerInterceptorReport memory fillReport) public { // No op } /* * Balance is unknown as it is entirely dependent on the offer in Uniswap being filled. * Thus we send down a very large number to ensure the relay/matching engine believes * orders from this broker have enough of a balance for trades to be filled. */ function brokerBalanceOf(address owner, address tokenAddress) public view returns (uint) { return 10 ** 70; } }
* @notice Convert Tokens (token) to Tokens (token_addr) && transfers Tokens (token_addr) to recipient. @dev User specifies exact input && minimum output. @param tokens_sold Amount of Tokens sold. @param min_tokens_bought Minimum Tokens (token_addr) purchased. @param min_eth_bought Minimum ETH purchased as intermediary. @param deadline Time after which this transaction can no longer be executed. @param recipient The address that receives output ETH. @param token_addr The address of the token being purchased. @return Amount of Tokens (token_addr) bought./
function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) public returns (uint256) { address payable exchange_addr = factory.getExchange(token_addr); return tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, recipient, exchange_addr); }
5,385,837
[ 1, 2723, 13899, 261, 2316, 13, 358, 13899, 261, 2316, 67, 4793, 13, 597, 29375, 540, 13899, 261, 2316, 67, 4793, 13, 358, 8027, 18, 225, 2177, 11470, 5565, 810, 597, 5224, 876, 18, 225, 2430, 67, 87, 1673, 16811, 434, 13899, 272, 1673, 18, 225, 1131, 67, 7860, 67, 1075, 9540, 23456, 13899, 261, 2316, 67, 4793, 13, 5405, 343, 8905, 18, 225, 1131, 67, 546, 67, 1075, 9540, 23456, 512, 2455, 5405, 343, 8905, 487, 1554, 5660, 814, 18, 225, 14096, 2647, 1839, 1492, 333, 2492, 848, 1158, 7144, 506, 7120, 18, 225, 8027, 1021, 1758, 716, 17024, 876, 512, 2455, 18, 225, 1147, 67, 4793, 1021, 1758, 434, 326, 1147, 3832, 5405, 343, 8905, 18, 327, 16811, 434, 13899, 261, 2316, 67, 4793, 13, 800, 9540, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1147, 774, 1345, 5912, 1210, 12, 203, 565, 2254, 5034, 2430, 67, 87, 1673, 16, 7010, 565, 2254, 5034, 1131, 67, 7860, 67, 1075, 9540, 16, 7010, 565, 2254, 5034, 1131, 67, 546, 67, 1075, 9540, 16, 7010, 565, 2254, 5034, 14096, 16, 7010, 565, 1758, 8027, 16, 7010, 565, 1758, 1147, 67, 4793, 13, 7010, 565, 1071, 1135, 261, 11890, 5034, 13, 7010, 225, 288, 203, 565, 1758, 8843, 429, 7829, 67, 4793, 273, 3272, 18, 588, 11688, 12, 2316, 67, 4793, 1769, 203, 565, 327, 1147, 774, 1345, 1210, 12, 7860, 67, 87, 1673, 16, 1131, 67, 7860, 67, 1075, 9540, 16, 1131, 67, 546, 67, 1075, 9540, 16, 14096, 16, 1234, 18, 15330, 16, 8027, 16, 7829, 67, 4793, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; 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); } contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } contract Conserve is StandardToken { // CHANGE THIS. Update the contract name. /* 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? // This is a constructor function // which means the following function name has to match the contract name declared above function Conserve() { balances[msg.sender] = 500000000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS) totalSupply = 500000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS) name = "Conserve"; // Set the name for display purposes (CHANGE THIS) decimals = 18; // Amount of decimals for display purposes (CHANGE THIS) symbol = "UBI"; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuy = 250000000; // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH } function() public 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; } }
CHANGE THIS. Update the contract name.
contract Conserve is StandardToken {
13,864,357
[ 1, 14473, 20676, 18, 2315, 326, 6835, 508, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 735, 30104, 353, 8263, 1345, 288, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; /** * @title SafeMathInt * @dev Math operations for int256 with overflow safety checks. */ library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } } pragma solidity 0.4.24; /** * @title Various utilities useful for uint256. */ library UInt256Lib { uint256 private constant MAX_INT256 = ~(uint256(1) << 255); /** * @dev Safely converts a uint256 to an int256. */ function toInt256Safe(uint256 a) internal pure returns (int256) { require(a <= MAX_INT256); return int256(a); } } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { bool private initialized; bool private initializing; modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract already initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _ ; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable is Initializable { address private _owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function initialize(address sender) public initializer { _owner = sender; } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(_owner); _owner = address(0); } /** * @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 { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting '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; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } // function mod(uint256 a, uint256 b) internal pure returns (uint256) { // return mod(a, b); // } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } pragma solidity ^0.4.24; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is Initializable, IERC20 { string private _name; string private _symbol; uint8 private _decimals; function initialize(string name, string symbol, uint8 decimals) public initializer { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns(string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns(string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns(uint8) { return _decimals; } uint256[50] private ______gap; } interface ISync { function sync() external; } /** * @title OracleBase ERC20 token * @dev This is part of an implementation of the OracleBase Ideal Money protocol. * OracleBase is a normal ERC20 token, but its supply can be adjusted by splitting and * combining tokens proportionally across all wallets. * * OracleBase balances are internally represented with a hidden denomination, 'gons'. * We support splitting the currency in expansion and combining the currency on contraction by * changing the exchange rate between the hidden 'gons' and the public 'fragments'. */ contract OracleBase is ERC20Detailed, Ownable { // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH // Anytime there is division, there is a risk of numerical instability from rounding errors. In // order to minimize this risk, we adhere to the following guidelines: // 1) The conversion rate adopted is the number of gons that equals 1 fragment. // The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is // always the denominator. (i.e. If you want to convert gons to fragments instead of // multiplying by the inverse rate, you should divide by the normal rate) // 2) Gon balances converted into Fragments are always rounded down (truncated). // // We make the following guarantees: // - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will // be decreased by precisely x Fragments, and B's external balance will be precisely // increased by x Fragments. // // We do not guarantee that the sum of all balances equals the result of calling totalSupply(). // This is because, for any conversion function 'f()' that has non-zero rounding error, // f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); event LogMonetaryPolicyUpdated(address monetaryPolicy); event LogOBEthPairAdded(address OBEthUniswapPair); bool private rebasePausedDeprecated; bool private tokenPausedDeprecated; modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } uint256 private constant DECIMALS = 9; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 965 * 10**3 * 10**DECIMALS; // Initial Supply 596_000 // TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer. // Use the highest value that fits in a uint256 for max granularity. uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY); // MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2 uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 private _gonsPerFragment; //Uniswap pair contract address public _OBEthUniswapPair; mapping(address => uint256) private _gonBalances; // This is denominated in Fragments, because the gons-fragments conversion might change before // it's fully paid. mapping (address => mapping (address => uint256)) private _allowedFragments; /** * @param OBEthUniswapPair_ The address of the uniswap pair(OracleBase~eth) contract to sync liquiity. */ function setOBEthPairAddress(address OBEthUniswapPair_) external onlyOwner { _OBEthUniswapPair = OBEthUniswapPair_; emit LogOBEthPairAdded(_OBEthUniswapPair); } /** * @dev Notifies Fragments contract about a new rebase cycle. * @param supplyDelta The number of new fragment tokens to add into circulation via expansion. * @return The total number of fragments after the supply adjustment. */ function rebase(uint256 epoch, int256 supplyDelta) internal returns (uint256) { if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); } else { _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _gonsPerFragment = TOTAL_GONS.div(_totalSupply); // From this point forward, _gonsPerFragment is taken as the source of truth. // We recalculate a new _totalSupply to be in agreement with the _gonsPerFragment // conversion rate. // This means our applied supplyDelta can deviate from the requested supplyDelta, // but this deviation is guaranteed to be < (_totalSupply^2)/(TOTAL_GONS - _totalSupply). // // In the case of _totalSupply <= MAX_UINT128 (our current supply cap), this // deviation is guaranteed to be < 1, so we can omit this step. If the supply cap is // ever increased, it must be re-included. // _totalSupply = TOTAL_GONS.div(_gonsPerFragment) emit LogRebase(epoch, _totalSupply); // ISync(_OBEthUniswapPair).sync(); // Uniswap ETH-OB Pair return _totalSupply; } function tokenInitialize(address owner_) internal { ERC20Detailed.initialize("ORACLEBASE", "OB", uint8(DECIMALS)); Ownable.initialize(owner_); rebasePausedDeprecated = false; tokenPausedDeprecated = false; _totalSupply = INITIAL_FRAGMENTS_SUPPLY; _gonBalances[owner_] = TOTAL_GONS; _gonsPerFragment = TOTAL_GONS.div(_totalSupply); emit Transfer(address(0x0), owner_, _totalSupply); } /** * @return The total number of fragments. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view returns (uint256) { return _gonBalances[who].div(_gonsPerFragment); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) external validRecipient(to) returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[msg.sender] = _gonBalances[msg.sender].sub(gonValue); _gonBalances[to] = _gonBalances[to].add(gonValue); emit Transfer(msg.sender, to, value); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public view returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) external validRecipient(to) returns (bool) { _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[from] = _gonBalances[from].sub(gonValue); _gonBalances[to] = _gonBalances[to].add(gonValue); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) external returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } } pragma solidity ^0.4.24; /** * @title Median Oracle * * @notice Provides a value onchain that's aggregated from a whitelisted set of * providers. */ contract TargetPriceOracle is Ownable { uint256 public currentMarketPrice; /** * @notice Pushes a targetPrice * @param currentMarketPrice_ is expected to be 18 decimal fixed point number in WEI */ function pushTargetReport(uint256 currentMarketPrice_) external onlyOwner { // currentMarketPrice = currentMarketPrice_; } /** * @return AggregatedValue: return the reported values. * valid: Boolean indicating an aggregated value was computed successfully. */ function getData() public view returns (uint256, bool) { return (currentMarketPrice, true); } } pragma solidity ^0.4.24; /** * @title Median Oracle * * @notice Provides a value onchain that's aggregated from a whitelisted set of * providers. */ contract MarketPriceOracle is Ownable { uint256 public currentMarketPrice; /** * @notice Pushes a targetPrice * @param currentMarketPrice_ is expected to be 18 decimal fixed point number in WEI */ function pushMarketReport(uint256 currentMarketPrice_) external onlyOwner { // currentMarketPrice = currentMarketPrice_; } /** * @return AggregatedValue: return the reported values. * valid: Boolean indicating an aggregated value was computed successfully. */ function getData() public view returns (uint256, bool) { return (currentMarketPrice, true); } } /** * @title uFragments Monetary Supply Policy * @dev This is an implementation of the uFragments Ideal Money protocol. * uFragments operates symmetrically on expansion and contraction. It will both split and * combine coins to maintain a stable unit price. * * This component regulates the token supply of the uFragments ERC20 token in response to * market oracles. */ contract UFragmentsPolicy is Ownable, TargetPriceOracle, MarketPriceOracle, OracleBase { using SafeMath for uint256; using SafeMathInt for int256; using UInt256Lib for uint256; event LogRebase( uint256 indexed epoch, uint256 exchangeRate, uint256 cpi, int256 requestedSupplyAdjustment, uint256 timestampSec ); // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. // DECIMALS Fixed point number. uint256 public deviationThreshold; // The rebase lag parameter, used to dampen the applied supply adjustment by 1 / rebaseLag // Check setRebaseLag comments for more details. // Natural number, no decimal places. uint256 public rebaseLag; // More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec; // Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; // The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec; // The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec; // The number of rebase cycles since inception uint256 public epoch; uint256 private constant DECIMALS = 18; // Due to the expression in computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256. // Both are 18 decimals fixed point numbers. uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS; // MAX_SUPPLY = MAX_INT256 / MAX_RATE uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE; /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is TargetPriceOracleRate / baseCpi */ // uint256 public supplyDelta; // uint256 public exchangeRate; // int256 public targetRate ; uint256 public priceChange ; int256 public supplyDeltaNew; function policyRebase() internal { require(inRebaseWindow()); // This comparison also ensures there is no reentrancy. require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now); // Snap the rebase time to the start of this window. lastRebaseTimestampSec = now.sub( now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec); epoch = epoch.add(1); uint256 targetRate; bool targetRateValid; (targetRate, targetRateValid) = TargetPriceOracle.getData(); require(targetRateValid); uint256 exchangeRate; bool rateValid; (exchangeRate, rateValid) = MarketPriceOracle.getData(); // fetch exchange rate in ETH require(rateValid); if (exchangeRate > MAX_RATE) { exchangeRate = MAX_RATE; } // int256 supplyDelta = computeSupplyDelta(exchangeRate, targetRate); // Apply the Dampening factor. supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe()); if (supplyDelta > 0 && OracleBase.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(OracleBase.totalSupply())).toInt256Safe(); } uint256 supplyAfterRebase = OracleBase.rebase(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); emit LogRebase(epoch, exchangeRate, targetRate, supplyDelta, now); } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetRate, then no supply * modifications are made. DECIMALS fixed point number. * @param deviationThreshold_ The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 deviationThreshold_) external onlyOwner { deviationThreshold = deviationThreshold_; } /** * @notice Sets the rebase lag parameter. It is used to dampen the applied supply adjustment by 1 / rebaseLag If the rebase lag R, equals 1, the smallest value for R, then the full supply correction is applied on each rebase cycle. If it is greater than 1, then a correction of 1/R of is applied on each rebase. * @param rebaseLag_ The new rebase lag parameter. */ function setRebaseLag(uint256 rebaseLag_) external onlyOwner { require(rebaseLag_ > 0); rebaseLag = rebaseLag_; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase * operations, in seconds. * @param rebaseWindowOffsetSec_ The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param rebaseWindowLengthSec_ The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 minRebaseTimeIntervalSec_, uint256 rebaseWindowOffsetSec_, uint256 rebaseWindowLengthSec_) external onlyOwner { require(minRebaseTimeIntervalSec_ > 0); require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_); minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; rebaseWindowOffsetSec = rebaseWindowOffsetSec_; rebaseWindowLengthSec = rebaseWindowLengthSec_; } /** * @dev ZOS upgradable contract initialization method. * It is called at the time of contract creation to invoke parent class initializers and * initialize the contract's state variables. */ function policyInitialize(address _owner) internal { // deviationThreshold = 0.05e18 = 5e16 deviationThreshold = 25 * 10 ** (DECIMALS-3); // 50000000000000000 rebaseLag = 10; minRebaseTimeIntervalSec = 1 days; rebaseWindowOffsetSec = 72000; // 8PM UTC rebaseWindowLengthSec = 15 minutes; lastRebaseTimestampSec = 0; epoch = 0; OracleBase.tokenInitialize(_owner); } /** * @return If the latest block timestamp is within the rebase time window it, returns true. * Otherwise, returns false. */ function inRebaseWindow() public view returns (bool) { return ( now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec && now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)) ); } /** * @return Computes the total supply adjustment in response to the exchange rate * and the targetRate. */ function computeSupplyDelta(uint256 rate, uint256 targetRate) private view returns (int256) { if (withinDeviationThreshold(rate, targetRate)) { return 0; } // supplyDelta = totalSupply * (rate - targetRate) / targetRate int256 targetRateSigned = targetRate.toInt256Safe(); return OracleBase.totalSupply().toInt256Safe() .mul(rate.toInt256Safe().sub(targetRateSigned)) .div(targetRateSigned); } /** * @param rate The current exchange rate, an 18 decimal fixed point number. * @param targetRate The target exchange rate, an 18 decimal fixed point number. * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 rate, uint256 targetRate) private view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** DECIMALS); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } } /** * @title Orchestrator * @notice The orchestrator is the main entry point for rebase operations. It coordinates the policy * actions with external consumers. */ contract Orchestrator is Ownable, UFragmentsPolicy { struct Transaction { bool enabled; address destination; bytes data; } event TransactionFailed(address indexed destination, uint index, bytes data); // Stable ordering is not guaranteed. Transaction[] public transactions; constructor() public { Ownable.initialize(msg.sender); UFragmentsPolicy.policyInitialize(msg.sender); } /** * @notice Main entry point to initiate a rebase operation. * The Orchestrator calls rebase on the policy and notifies downstream applications. * Contracts are guarded from calling, to avoid flash loan attacks on liquidity * providers. * If a transaction in the transaction list reverts, it is swallowed and the remaining * transactions are executed. */ function rebase() external { require(msg.sender == tx.origin); // solhint-disable-line avoid-tx-origin UFragmentsPolicy.policyRebase(); for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } } /** * @notice Adds a transaction that gets called for a downstream receiver of rebases * @param destination Address of contract destination * @param data Transaction data payload */ function addTransaction(address destination, bytes data) external onlyOwner { transactions.push(Transaction({ enabled: true, destination: destination, data: data })); } /** * @param index Index of transaction to remove. * Transaction ordering may have changed since adding. */ function removeTransaction(uint index) external onlyOwner { require(index < transactions.length, "index out of bounds"); if (index < transactions.length - 1) { transactions[index] = transactions[transactions.length - 1]; } transactions.length--; } /** * @param index Index of transaction. Transaction ordering may have changed since adding. * @param enabled True for enabled, false for disabled. */ function setTransactionEnabled(uint index, bool enabled) external onlyOwner { require(index < transactions.length, "index must be in range of stored tx list"); transactions[index].enabled = enabled; } /** * @return Number of transactions, both enabled and disabled, in transactions list. */ function transactionsSize() external view returns (uint256) { return transactions.length; } /** * @dev wrapper to call the encoded transactions on downstream consumers. * @param destination Address of destination contract. * @param data The encoded data payload. * @return True on success */ function externalCall(address destination, bytes data) internal returns (bool) { bool result; assembly { // solhint-disable-line no-inline-assembly // "Allocate" memory for output // (0x40 is where "free memory" pointer is stored by convention) let outputAddress := mload(0x40) // First 32 bytes are the padded length of data, so exclude that let dataAddress := add(data, 32) result := call( // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) // + callValueTransferGas (9000) + callNewAccountGas // (25000, in case the destination address does not exist and needs creating) sub(gas, 34710), destination, 0, // transfer value in wei dataAddress, mload(data), // Size of the input, in bytes. Stored in position 0 of the array. outputAddress, 0 // Output is ignored, therefore the output size is zero ) } return result; } }
* @title SafeMathInt @dev Math operations for int256 with overflow safety checks./
library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } function div(int256 a, int256 b) internal pure returns (int256) { require(b != -1 || a != MIN_INT256); return a / b; } function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } }
6,944,647
[ 1, 9890, 10477, 1702, 225, 2361, 5295, 364, 509, 5034, 598, 9391, 24179, 4271, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 14060, 10477, 1702, 288, 203, 565, 509, 5034, 3238, 5381, 6989, 67, 3217, 5034, 273, 509, 5034, 12, 21, 13, 2296, 4561, 31, 203, 565, 509, 5034, 3238, 5381, 4552, 67, 3217, 5034, 273, 4871, 12, 474, 5034, 12, 21, 13, 2296, 4561, 1769, 203, 203, 565, 445, 14064, 12, 474, 5034, 279, 16, 509, 5034, 324, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 474, 5034, 13, 203, 565, 288, 203, 3639, 509, 5034, 276, 273, 279, 380, 324, 31, 203, 203, 3639, 2583, 12, 71, 480, 6989, 67, 3217, 5034, 747, 261, 69, 473, 6989, 67, 3217, 5034, 13, 480, 261, 70, 473, 6989, 67, 3217, 5034, 10019, 203, 3639, 2583, 12443, 70, 422, 374, 13, 747, 261, 71, 342, 324, 422, 279, 10019, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 3739, 12, 474, 5034, 279, 16, 509, 5034, 324, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 474, 5034, 13, 203, 540, 203, 565, 288, 203, 3639, 2583, 12, 70, 480, 300, 21, 747, 279, 480, 6989, 67, 3217, 5034, 1769, 203, 203, 3639, 327, 279, 342, 324, 31, 203, 565, 289, 203, 203, 565, 445, 720, 12, 474, 5034, 279, 16, 509, 5034, 324, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 474, 5034, 13, 203, 565, 288, 203, 3639, 509, 5034, 276, 273, 279, 300, 324, 31, 203, 3639, 2583, 12443, 70, 1545, 374, 597, 276, 1648, 279, 13, 747, 261, 70, 411, 374, 2 ]
./full_match/4/0x83c6bd824A24321DebF10aD6112C9a587EB1080b/sources/HowlTest.sol
once set to true can never be set false againmaximum purchase amount for initial launch exlcude from fees and max transaction amount addresses that can make transfers before presale is over store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount store the amount sold for each account every day to add extra tax the last time an address transferred used to detect if an account can be reinvest inactive funds to the vault
contract Howl is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private swapping; bool private reinvesting; bool public maxPurchaseEnabled = true; HowlDividendTracker public dividendTracker; address public immutable deadAddress = 0x000000000000000000000000000000000000dEaD; uint256 public maxDailySellAmount = 10000 * (10**18); uint256 public swapTokensAtAmount = 1000 * (10**18); mapping(address => bool) private _isBot; address[] private _confirmedBots; bool public aidiBuybackEnabled = true; uint256 public buybackFee = 2; uint256 public redistributeFee = 5; uint256 public devMarketingAndCharityFee = 3; uint256 public totalFee = 10; bool public tradingOpen = false; uint256 public launchTime; uint256 minimumTokenBalanceForDividends = 50 * (10**18); uint256 maxPurchaseAmount = 25000 * (10**18); mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public canTransferBeforeTradingIsEnabled; mapping (address => bool) public automatedMarketMakerPairs; mapping (uint256 => mapping(address => uint256)) public dailySell; mapping (address => uint256) public lastTransfer; mapping (address => bool) public isExcludedFromDailyLimit; event UpdateDividendTracker(address indexed newAddress, address indexed oldAddress); event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event SendDividends(uint256 amount); event DividendClaimed(uint256 ethAmount, uint256 tokenAmount, address account); constructor() public ERC20("Howl", "HOWL") { dividendTracker = new HowlDividendTracker(); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); dividendTracker.excludeFromDividends(address(dividendTracker)); dividendTracker.excludeFromDividends(address(this)); dividendTracker.excludeFromDividends(owner()); dividendTracker.excludeFromDividends(address(_uniswapV2Router)); excludeFromFees(address(this), true); excludeFromFees(owner(), true); canTransferBeforeTradingIsEnabled[owner()] = true; isExcludedFromDailyLimit[address(this)] = true; isExcludedFromDailyLimit[owner()] = true; _mint(owner(), 5000000 * (10**18)); } receive() external payable { } function updateDividendTracker(address newAddress) public onlyOwner { require(newAddress != address(dividendTracker), "Howl: The dividend tracker already has that address"); HowlDividendTracker newDividendTracker = HowlDividendTracker(payable(newAddress)); require(newDividendTracker.owner() == address(this), "Howl: The new dividend tracker must be owned by the Howl token contract"); newDividendTracker.excludeFromDividends(address(newDividendTracker)); newDividendTracker.excludeFromDividends(address(this)); newDividendTracker.excludeFromDividends(owner()); newDividendTracker.excludeFromDividends(address(uniswapV2Router)); emit UpdateDividendTracker(newAddress, address(dividendTracker)); dividendTracker = newDividendTracker; } function updateUniswapV2Router(address newAddress) public onlyOwner { require(newAddress != address(uniswapV2Router), "Howl: The router already has that address"); emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router)); uniswapV2Router = IUniswapV2Router02(newAddress); dividendTracker.excludeFromDividends(address(uniswapV2Router)); } function excludeFromFees(address account, bool excluded) public onlyOwner { require(_isExcludedFromFees[account] != excluded, "Howl: Account is already the value of 'excluded'"); _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFees[accounts[i]] = excluded; } emit ExcludeMultipleAccountsFromFees(accounts, excluded); } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFees[accounts[i]] = excluded; } emit ExcludeMultipleAccountsFromFees(accounts, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "Howl: The UniSwap pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "Howl: Automated market maker pair is already set to that value"); automatedMarketMakerPairs[pair] = value; if(value) { dividendTracker.excludeFromDividends(pair); } emit SetAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "Howl: Automated market maker pair is already set to that value"); automatedMarketMakerPairs[pair] = value; if(value) { dividendTracker.excludeFromDividends(pair); } emit SetAutomatedMarketMakerPair(pair, value); } function excludeFromDailyLimit(address account, bool excluded) public onlyOwner { require(isExcludedFromDailyLimit[account] != excluded, "Howl: Daily limit exclusion is already the value of 'excluded'"); isExcludedFromDailyLimit[account] = excluded; } function allowPreTrading(address account, bool allowed) public onlyOwner { require(canTransferBeforeTradingIsEnabled[account] != allowed, "Howl: Pre trading is already the value of 'excluded'"); canTransferBeforeTradingIsEnabled[account] = allowed; } function setMaxPurchaseEnabled(bool enabled) public onlyOwner { require(maxPurchaseEnabled != enabled, "Howl: Max purchase enabled is already the value of 'enabled'"); maxPurchaseEnabled = enabled; } function setAidiBuybackEnabled(bool enabled) public onlyOwner { aidiBuybackEnabled = enabled; } function setMaxPurchaseAmount(uint256 newAmount) public onlyOwner { maxPurchaseAmount = newAmount; } function updateDevMarketingAndCharityAddress(address payable newAddress) public onlyOwner { devMarketingAndCharityAddress = newAddress; } function getTotalDividendsDistributed() external view returns (uint256) { return dividendTracker.totalDividendsDistributed(); } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function withdrawableDividendOf(address account) public view returns(uint256) { return dividendTracker.withdrawableDividendOf(account); } function dividendTokenBalanceOf(address account) public view returns (uint256) { return dividendTracker.balanceOf(account); } function reinvestInactive(address payable account) public onlyOwner { uint256 tokenBalance = dividendTracker.balanceOf(account); require(tokenBalance <= minimumTokenBalanceForDividends, "Howl: Account balance must be less then minimum token balance for dividends"); uint256 _lastTransfer = lastTransfer[account]; require(block.timestamp.sub(_lastTransfer) > 12 weeks, "Howl: Account must have been inactive for at least 12 weeks"); dividendTracker.processAccount(account, address(this)); uint256 dividends = address(this).balance; if(success) { emit SendDividends(dividends); } } (bool success,) = address(dividendTracker).call{value: dividends}(""); function reinvestInactive(address payable account) public onlyOwner { uint256 tokenBalance = dividendTracker.balanceOf(account); require(tokenBalance <= minimumTokenBalanceForDividends, "Howl: Account balance must be less then minimum token balance for dividends"); uint256 _lastTransfer = lastTransfer[account]; require(block.timestamp.sub(_lastTransfer) > 12 weeks, "Howl: Account must have been inactive for at least 12 weeks"); dividendTracker.processAccount(account, address(this)); uint256 dividends = address(this).balance; if(success) { emit SendDividends(dividends); } } try dividendTracker.setBalance(account, 0) {} catch {} function claim(bool reinvest, uint256 minTokens) external { _claim(msg.sender, reinvest, minTokens); } function _claim(address payable account, bool reinvest, uint256 minTokens) private { uint256 withdrawableAmount = dividendTracker.withdrawableDividendOf(account); require(withdrawableAmount > 0, "Howl: Claimer has no withdrawable dividend"); if (!reinvest) { uint256 ethAmount = dividendTracker.processAccount(account, account); if (ethAmount > 0) { emit DividendClaimed(ethAmount, 0, account); } return; } uint256 ethAmount = dividendTracker.processAccount(account, address(this)); if (ethAmount > 0) { reinvesting = true; uint256 tokenAmount = swapEthForTokens(ethAmount, minTokens, account); reinvesting = false; emit DividendClaimed(ethAmount, tokenAmount, account); } } function _claim(address payable account, bool reinvest, uint256 minTokens) private { uint256 withdrawableAmount = dividendTracker.withdrawableDividendOf(account); require(withdrawableAmount > 0, "Howl: Claimer has no withdrawable dividend"); if (!reinvest) { uint256 ethAmount = dividendTracker.processAccount(account, account); if (ethAmount > 0) { emit DividendClaimed(ethAmount, 0, account); } return; } uint256 ethAmount = dividendTracker.processAccount(account, address(this)); if (ethAmount > 0) { reinvesting = true; uint256 tokenAmount = swapEthForTokens(ethAmount, minTokens, account); reinvesting = false; emit DividendClaimed(ethAmount, tokenAmount, account); } } function _claim(address payable account, bool reinvest, uint256 minTokens) private { uint256 withdrawableAmount = dividendTracker.withdrawableDividendOf(account); require(withdrawableAmount > 0, "Howl: Claimer has no withdrawable dividend"); if (!reinvest) { uint256 ethAmount = dividendTracker.processAccount(account, account); if (ethAmount > 0) { emit DividendClaimed(ethAmount, 0, account); } return; } uint256 ethAmount = dividendTracker.processAccount(account, address(this)); if (ethAmount > 0) { reinvesting = true; uint256 tokenAmount = swapEthForTokens(ethAmount, minTokens, account); reinvesting = false; emit DividendClaimed(ethAmount, tokenAmount, account); } } function _claim(address payable account, bool reinvest, uint256 minTokens) private { uint256 withdrawableAmount = dividendTracker.withdrawableDividendOf(account); require(withdrawableAmount > 0, "Howl: Claimer has no withdrawable dividend"); if (!reinvest) { uint256 ethAmount = dividendTracker.processAccount(account, account); if (ethAmount > 0) { emit DividendClaimed(ethAmount, 0, account); } return; } uint256 ethAmount = dividendTracker.processAccount(account, address(this)); if (ethAmount > 0) { reinvesting = true; uint256 tokenAmount = swapEthForTokens(ethAmount, minTokens, account); reinvesting = false; emit DividendClaimed(ethAmount, tokenAmount, account); } } function getNumberOfDividendTokenHolders() external view returns(uint256) { return dividendTracker.getNumberOfTokenHolders(); } function getAccount(address _account) public view returns ( uint256 withdrawableDividends, uint256 withdrawnDividends, uint256 balance ) { (withdrawableDividends, withdrawnDividends) = dividendTracker.getAccount(_account); return (withdrawableDividends, withdrawnDividends, balanceOf(_account)); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } to != address(uniswapV2Router) && !_isExcludedFromFees[to]) { require(tradingOpen, 'Trading not yet enabled.'); if (block.timestamp == launchTime) { _isBot[to] = true; _confirmedBots.push(to); } } if (maxPurchaseEnabled && !isExcludedFromDailyLimit[to] && automatedMarketMakerPairs[from]) { require(amount <= maxPurchaseAmount, "Howl: Exceeds max purchase amount"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(aidiBuybackEnabled) { buybackFee = 2; buybackFee = 0; } redistributeFee = 5; devMarketingAndCharityFee = 3; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; { if (!isExcludedFromDailyLimit[from] && !automatedMarketMakerPairs[from] && (dailySell[getDay()][from].add(amount) > maxDailySellAmount)) { if(aidiBuybackEnabled) { buybackFee = 4; buybackFee = 0; } redistributeFee = 10; devMarketingAndCharityFee = 6; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; } dailySell[getDay()][from] = dailySell[getDay()][from].add(amount); } if( canSwap && !swapping && !reinvesting && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapAndDistribute(); swapping = false; } bool takeFee = !swapping && !reinvesting; if((_isExcludedFromFees[from] || _isExcludedFromFees[to]) || (!automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to])) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFee).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); lastTransfer[from] = block.timestamp; lastTransfer[to] = block.timestamp; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } to != address(uniswapV2Router) && !_isExcludedFromFees[to]) { require(tradingOpen, 'Trading not yet enabled.'); if (block.timestamp == launchTime) { _isBot[to] = true; _confirmedBots.push(to); } } if (maxPurchaseEnabled && !isExcludedFromDailyLimit[to] && automatedMarketMakerPairs[from]) { require(amount <= maxPurchaseAmount, "Howl: Exceeds max purchase amount"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(aidiBuybackEnabled) { buybackFee = 2; buybackFee = 0; } redistributeFee = 5; devMarketingAndCharityFee = 3; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; { if (!isExcludedFromDailyLimit[from] && !automatedMarketMakerPairs[from] && (dailySell[getDay()][from].add(amount) > maxDailySellAmount)) { if(aidiBuybackEnabled) { buybackFee = 4; buybackFee = 0; } redistributeFee = 10; devMarketingAndCharityFee = 6; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; } dailySell[getDay()][from] = dailySell[getDay()][from].add(amount); } if( canSwap && !swapping && !reinvesting && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapAndDistribute(); swapping = false; } bool takeFee = !swapping && !reinvesting; if((_isExcludedFromFees[from] || _isExcludedFromFees[to]) || (!automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to])) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFee).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); lastTransfer[from] = block.timestamp; lastTransfer[to] = block.timestamp; } if (from == uniswapV2Pair && function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } to != address(uniswapV2Router) && !_isExcludedFromFees[to]) { require(tradingOpen, 'Trading not yet enabled.'); if (block.timestamp == launchTime) { _isBot[to] = true; _confirmedBots.push(to); } } if (maxPurchaseEnabled && !isExcludedFromDailyLimit[to] && automatedMarketMakerPairs[from]) { require(amount <= maxPurchaseAmount, "Howl: Exceeds max purchase amount"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(aidiBuybackEnabled) { buybackFee = 2; buybackFee = 0; } redistributeFee = 5; devMarketingAndCharityFee = 3; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; { if (!isExcludedFromDailyLimit[from] && !automatedMarketMakerPairs[from] && (dailySell[getDay()][from].add(amount) > maxDailySellAmount)) { if(aidiBuybackEnabled) { buybackFee = 4; buybackFee = 0; } redistributeFee = 10; devMarketingAndCharityFee = 6; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; } dailySell[getDay()][from] = dailySell[getDay()][from].add(amount); } if( canSwap && !swapping && !reinvesting && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapAndDistribute(); swapping = false; } bool takeFee = !swapping && !reinvesting; if((_isExcludedFromFees[from] || _isExcludedFromFees[to]) || (!automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to])) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFee).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); lastTransfer[from] = block.timestamp; lastTransfer[to] = block.timestamp; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } to != address(uniswapV2Router) && !_isExcludedFromFees[to]) { require(tradingOpen, 'Trading not yet enabled.'); if (block.timestamp == launchTime) { _isBot[to] = true; _confirmedBots.push(to); } } if (maxPurchaseEnabled && !isExcludedFromDailyLimit[to] && automatedMarketMakerPairs[from]) { require(amount <= maxPurchaseAmount, "Howl: Exceeds max purchase amount"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(aidiBuybackEnabled) { buybackFee = 2; buybackFee = 0; } redistributeFee = 5; devMarketingAndCharityFee = 3; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; { if (!isExcludedFromDailyLimit[from] && !automatedMarketMakerPairs[from] && (dailySell[getDay()][from].add(amount) > maxDailySellAmount)) { if(aidiBuybackEnabled) { buybackFee = 4; buybackFee = 0; } redistributeFee = 10; devMarketingAndCharityFee = 6; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; } dailySell[getDay()][from] = dailySell[getDay()][from].add(amount); } if( canSwap && !swapping && !reinvesting && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapAndDistribute(); swapping = false; } bool takeFee = !swapping && !reinvesting; if((_isExcludedFromFees[from] || _isExcludedFromFees[to]) || (!automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to])) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFee).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); lastTransfer[from] = block.timestamp; lastTransfer[to] = block.timestamp; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } to != address(uniswapV2Router) && !_isExcludedFromFees[to]) { require(tradingOpen, 'Trading not yet enabled.'); if (block.timestamp == launchTime) { _isBot[to] = true; _confirmedBots.push(to); } } if (maxPurchaseEnabled && !isExcludedFromDailyLimit[to] && automatedMarketMakerPairs[from]) { require(amount <= maxPurchaseAmount, "Howl: Exceeds max purchase amount"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(aidiBuybackEnabled) { buybackFee = 2; buybackFee = 0; } redistributeFee = 5; devMarketingAndCharityFee = 3; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; { if (!isExcludedFromDailyLimit[from] && !automatedMarketMakerPairs[from] && (dailySell[getDay()][from].add(amount) > maxDailySellAmount)) { if(aidiBuybackEnabled) { buybackFee = 4; buybackFee = 0; } redistributeFee = 10; devMarketingAndCharityFee = 6; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; } dailySell[getDay()][from] = dailySell[getDay()][from].add(amount); } if( canSwap && !swapping && !reinvesting && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapAndDistribute(); swapping = false; } bool takeFee = !swapping && !reinvesting; if((_isExcludedFromFees[from] || _isExcludedFromFees[to]) || (!automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to])) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFee).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); lastTransfer[from] = block.timestamp; lastTransfer[to] = block.timestamp; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } to != address(uniswapV2Router) && !_isExcludedFromFees[to]) { require(tradingOpen, 'Trading not yet enabled.'); if (block.timestamp == launchTime) { _isBot[to] = true; _confirmedBots.push(to); } } if (maxPurchaseEnabled && !isExcludedFromDailyLimit[to] && automatedMarketMakerPairs[from]) { require(amount <= maxPurchaseAmount, "Howl: Exceeds max purchase amount"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(aidiBuybackEnabled) { buybackFee = 2; buybackFee = 0; } redistributeFee = 5; devMarketingAndCharityFee = 3; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; { if (!isExcludedFromDailyLimit[from] && !automatedMarketMakerPairs[from] && (dailySell[getDay()][from].add(amount) > maxDailySellAmount)) { if(aidiBuybackEnabled) { buybackFee = 4; buybackFee = 0; } redistributeFee = 10; devMarketingAndCharityFee = 6; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; } dailySell[getDay()][from] = dailySell[getDay()][from].add(amount); } if( canSwap && !swapping && !reinvesting && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapAndDistribute(); swapping = false; } bool takeFee = !swapping && !reinvesting; if((_isExcludedFromFees[from] || _isExcludedFromFees[to]) || (!automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to])) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFee).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); lastTransfer[from] = block.timestamp; lastTransfer[to] = block.timestamp; } }else{ function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } to != address(uniswapV2Router) && !_isExcludedFromFees[to]) { require(tradingOpen, 'Trading not yet enabled.'); if (block.timestamp == launchTime) { _isBot[to] = true; _confirmedBots.push(to); } } if (maxPurchaseEnabled && !isExcludedFromDailyLimit[to] && automatedMarketMakerPairs[from]) { require(amount <= maxPurchaseAmount, "Howl: Exceeds max purchase amount"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(aidiBuybackEnabled) { buybackFee = 2; buybackFee = 0; } redistributeFee = 5; devMarketingAndCharityFee = 3; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; { if (!isExcludedFromDailyLimit[from] && !automatedMarketMakerPairs[from] && (dailySell[getDay()][from].add(amount) > maxDailySellAmount)) { if(aidiBuybackEnabled) { buybackFee = 4; buybackFee = 0; } redistributeFee = 10; devMarketingAndCharityFee = 6; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; } dailySell[getDay()][from] = dailySell[getDay()][from].add(amount); } if( canSwap && !swapping && !reinvesting && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapAndDistribute(); swapping = false; } bool takeFee = !swapping && !reinvesting; if((_isExcludedFromFees[from] || _isExcludedFromFees[to]) || (!automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to])) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFee).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); lastTransfer[from] = block.timestamp; lastTransfer[to] = block.timestamp; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } to != address(uniswapV2Router) && !_isExcludedFromFees[to]) { require(tradingOpen, 'Trading not yet enabled.'); if (block.timestamp == launchTime) { _isBot[to] = true; _confirmedBots.push(to); } } if (maxPurchaseEnabled && !isExcludedFromDailyLimit[to] && automatedMarketMakerPairs[from]) { require(amount <= maxPurchaseAmount, "Howl: Exceeds max purchase amount"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(aidiBuybackEnabled) { buybackFee = 2; buybackFee = 0; } redistributeFee = 5; devMarketingAndCharityFee = 3; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; { if (!isExcludedFromDailyLimit[from] && !automatedMarketMakerPairs[from] && (dailySell[getDay()][from].add(amount) > maxDailySellAmount)) { if(aidiBuybackEnabled) { buybackFee = 4; buybackFee = 0; } redistributeFee = 10; devMarketingAndCharityFee = 6; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; } dailySell[getDay()][from] = dailySell[getDay()][from].add(amount); } if( canSwap && !swapping && !reinvesting && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapAndDistribute(); swapping = false; } bool takeFee = !swapping && !reinvesting; if((_isExcludedFromFees[from] || _isExcludedFromFees[to]) || (!automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to])) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFee).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); lastTransfer[from] = block.timestamp; lastTransfer[to] = block.timestamp; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } to != address(uniswapV2Router) && !_isExcludedFromFees[to]) { require(tradingOpen, 'Trading not yet enabled.'); if (block.timestamp == launchTime) { _isBot[to] = true; _confirmedBots.push(to); } } if (maxPurchaseEnabled && !isExcludedFromDailyLimit[to] && automatedMarketMakerPairs[from]) { require(amount <= maxPurchaseAmount, "Howl: Exceeds max purchase amount"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(aidiBuybackEnabled) { buybackFee = 2; buybackFee = 0; } redistributeFee = 5; devMarketingAndCharityFee = 3; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; { if (!isExcludedFromDailyLimit[from] && !automatedMarketMakerPairs[from] && (dailySell[getDay()][from].add(amount) > maxDailySellAmount)) { if(aidiBuybackEnabled) { buybackFee = 4; buybackFee = 0; } redistributeFee = 10; devMarketingAndCharityFee = 6; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; } dailySell[getDay()][from] = dailySell[getDay()][from].add(amount); } if( canSwap && !swapping && !reinvesting && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapAndDistribute(); swapping = false; } bool takeFee = !swapping && !reinvesting; if((_isExcludedFromFees[from] || _isExcludedFromFees[to]) || (!automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to])) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFee).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); lastTransfer[from] = block.timestamp; lastTransfer[to] = block.timestamp; } }else{ function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } to != address(uniswapV2Router) && !_isExcludedFromFees[to]) { require(tradingOpen, 'Trading not yet enabled.'); if (block.timestamp == launchTime) { _isBot[to] = true; _confirmedBots.push(to); } } if (maxPurchaseEnabled && !isExcludedFromDailyLimit[to] && automatedMarketMakerPairs[from]) { require(amount <= maxPurchaseAmount, "Howl: Exceeds max purchase amount"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(aidiBuybackEnabled) { buybackFee = 2; buybackFee = 0; } redistributeFee = 5; devMarketingAndCharityFee = 3; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; { if (!isExcludedFromDailyLimit[from] && !automatedMarketMakerPairs[from] && (dailySell[getDay()][from].add(amount) > maxDailySellAmount)) { if(aidiBuybackEnabled) { buybackFee = 4; buybackFee = 0; } redistributeFee = 10; devMarketingAndCharityFee = 6; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; } dailySell[getDay()][from] = dailySell[getDay()][from].add(amount); } if( canSwap && !swapping && !reinvesting && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapAndDistribute(); swapping = false; } bool takeFee = !swapping && !reinvesting; if((_isExcludedFromFees[from] || _isExcludedFromFees[to]) || (!automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to])) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFee).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); lastTransfer[from] = block.timestamp; lastTransfer[to] = block.timestamp; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } to != address(uniswapV2Router) && !_isExcludedFromFees[to]) { require(tradingOpen, 'Trading not yet enabled.'); if (block.timestamp == launchTime) { _isBot[to] = true; _confirmedBots.push(to); } } if (maxPurchaseEnabled && !isExcludedFromDailyLimit[to] && automatedMarketMakerPairs[from]) { require(amount <= maxPurchaseAmount, "Howl: Exceeds max purchase amount"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(aidiBuybackEnabled) { buybackFee = 2; buybackFee = 0; } redistributeFee = 5; devMarketingAndCharityFee = 3; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; { if (!isExcludedFromDailyLimit[from] && !automatedMarketMakerPairs[from] && (dailySell[getDay()][from].add(amount) > maxDailySellAmount)) { if(aidiBuybackEnabled) { buybackFee = 4; buybackFee = 0; } redistributeFee = 10; devMarketingAndCharityFee = 6; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; } dailySell[getDay()][from] = dailySell[getDay()][from].add(amount); } if( canSwap && !swapping && !reinvesting && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapAndDistribute(); swapping = false; } bool takeFee = !swapping && !reinvesting; if((_isExcludedFromFees[from] || _isExcludedFromFees[to]) || (!automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to])) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFee).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); lastTransfer[from] = block.timestamp; lastTransfer[to] = block.timestamp; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } to != address(uniswapV2Router) && !_isExcludedFromFees[to]) { require(tradingOpen, 'Trading not yet enabled.'); if (block.timestamp == launchTime) { _isBot[to] = true; _confirmedBots.push(to); } } if (maxPurchaseEnabled && !isExcludedFromDailyLimit[to] && automatedMarketMakerPairs[from]) { require(amount <= maxPurchaseAmount, "Howl: Exceeds max purchase amount"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(aidiBuybackEnabled) { buybackFee = 2; buybackFee = 0; } redistributeFee = 5; devMarketingAndCharityFee = 3; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; { if (!isExcludedFromDailyLimit[from] && !automatedMarketMakerPairs[from] && (dailySell[getDay()][from].add(amount) > maxDailySellAmount)) { if(aidiBuybackEnabled) { buybackFee = 4; buybackFee = 0; } redistributeFee = 10; devMarketingAndCharityFee = 6; totalFee = buybackFee + redistributeFee + devMarketingAndCharityFee; } dailySell[getDay()][from] = dailySell[getDay()][from].add(amount); } if( canSwap && !swapping && !reinvesting && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapAndDistribute(); swapping = false; } bool takeFee = !swapping && !reinvesting; if((_isExcludedFromFees[from] || _isExcludedFromFees[to]) || (!automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to])) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFee).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); lastTransfer[from] = block.timestamp; lastTransfer[to] = block.timestamp; } try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {} try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch {} function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function swapEthForTokens(uint256 ethAmount, uint256 minTokens, address account) internal returns(uint256) { address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); uint256 balanceBefore = balanceOf(account); minTokens, path, account, block.timestamp ); uint256 tokenAmount = balanceOf(account).sub(balanceBefore); return tokenAmount; } uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: ethAmount}( function swapAndDistribute() private { uint256 tokenBalance = balanceOf(address(this)); swapTokensForEth(tokenBalance); uint256 ethBalance = address(this).balance; uint256 devMarketingAndCharityPortion = ethBalance.mul(devMarketingAndCharityFee).div(totalFee); uint256 buybackAndBurnPortion = ethBalance.mul(buybackFee).div(totalFee); devMarketingAndCharityAddress.transfer(devMarketingAndCharityPortion); if(aidiBuybackEnabled && buybackAndBurnPortion > 0) { buybackAndBurnAidiTokens(buybackAndBurnPortion); } uint256 dividends = address(this).balance; if(success) { emit SendDividends(dividends); } } function swapAndDistribute() private { uint256 tokenBalance = balanceOf(address(this)); swapTokensForEth(tokenBalance); uint256 ethBalance = address(this).balance; uint256 devMarketingAndCharityPortion = ethBalance.mul(devMarketingAndCharityFee).div(totalFee); uint256 buybackAndBurnPortion = ethBalance.mul(buybackFee).div(totalFee); devMarketingAndCharityAddress.transfer(devMarketingAndCharityPortion); if(aidiBuybackEnabled && buybackAndBurnPortion > 0) { buybackAndBurnAidiTokens(buybackAndBurnPortion); } uint256 dividends = address(this).balance; if(success) { emit SendDividends(dividends); } } (bool success,) = address(dividendTracker).call{value: dividends}(""); function swapAndDistribute() private { uint256 tokenBalance = balanceOf(address(this)); swapTokensForEth(tokenBalance); uint256 ethBalance = address(this).balance; uint256 devMarketingAndCharityPortion = ethBalance.mul(devMarketingAndCharityFee).div(totalFee); uint256 buybackAndBurnPortion = ethBalance.mul(buybackFee).div(totalFee); devMarketingAndCharityAddress.transfer(devMarketingAndCharityPortion); if(aidiBuybackEnabled && buybackAndBurnPortion > 0) { buybackAndBurnAidiTokens(buybackAndBurnPortion); } uint256 dividends = address(this).balance; if(success) { emit SendDividends(dividends); } } function buybackAndBurnAidiTokens(uint256 amount) private { address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path, block.timestamp.add(300) ); } uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}( function getDay() internal view returns(uint256){ return block.timestamp.div(1 days); } function openTrading() external onlyOwner { tradingOpen = true; launchTime = block.timestamp; } function isBot(address account) public view returns (bool) { return _isBot[account]; } function _blacklistBot(address account) external onlyOwner() { require(account != 0x10ED43C718714eb63d5aA57B78B54704E256024E, 'We cannot blacklist Pancakeswap'); require(!_isBot[account], "Account is already blacklisted"); _isBot[account] = true; _confirmedBots.push(account); } function _amnestyBot(address account) external onlyOwner() { require(_isBot[account], "Account is not blacklisted"); for (uint256 i = 0; i < _confirmedBots.length; i++) { if (_confirmedBots[i] == account) { _confirmedBots[i] = _confirmedBots[_confirmedBots.length - 1]; _isBot[account] = false; _confirmedBots.pop(); break; } } } function _amnestyBot(address account) external onlyOwner() { require(_isBot[account], "Account is not blacklisted"); for (uint256 i = 0; i < _confirmedBots.length; i++) { if (_confirmedBots[i] == account) { _confirmedBots[i] = _confirmedBots[_confirmedBots.length - 1]; _isBot[account] = false; _confirmedBots.pop(); break; } } } function _amnestyBot(address account) external onlyOwner() { require(_isBot[account], "Account is not blacklisted"); for (uint256 i = 0; i < _confirmedBots.length; i++) { if (_confirmedBots[i] == account) { _confirmedBots[i] = _confirmedBots[_confirmedBots.length - 1]; _isBot[account] = false; _confirmedBots.pop(); break; } } } }
662,302
[ 1, 8243, 444, 358, 638, 848, 5903, 506, 444, 629, 3382, 15724, 23701, 3844, 364, 2172, 8037, 431, 17704, 1317, 628, 1656, 281, 471, 943, 2492, 3844, 6138, 716, 848, 1221, 29375, 1865, 4075, 5349, 353, 1879, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 1707, 326, 3844, 272, 1673, 364, 1517, 2236, 3614, 2548, 358, 527, 2870, 5320, 326, 1142, 813, 392, 1758, 906, 4193, 1399, 358, 5966, 309, 392, 2236, 848, 506, 283, 5768, 395, 16838, 284, 19156, 358, 326, 9229, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 9017, 80, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 203, 565, 1426, 3238, 7720, 1382, 31, 203, 565, 1426, 3238, 283, 5768, 10100, 31, 203, 565, 1426, 1071, 943, 23164, 1526, 273, 638, 31, 203, 203, 565, 9017, 80, 7244, 26746, 8135, 1071, 31945, 8135, 31, 203, 377, 203, 565, 1758, 1071, 11732, 8363, 1887, 273, 374, 92, 12648, 12648, 12648, 12648, 2787, 72, 41, 69, 40, 31, 203, 203, 377, 203, 565, 2254, 5034, 1071, 943, 40, 12857, 55, 1165, 6275, 273, 12619, 380, 261, 2163, 636, 2643, 1769, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 273, 4336, 380, 261, 2163, 636, 2643, 1769, 203, 377, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 291, 6522, 31, 203, 565, 1758, 8526, 3238, 389, 21606, 6522, 87, 31, 203, 203, 565, 1426, 1071, 20702, 17632, 9835, 823, 1526, 273, 638, 31, 203, 565, 2254, 5034, 1071, 30143, 823, 14667, 273, 576, 31, 203, 565, 2254, 5034, 1071, 5813, 887, 14667, 273, 1381, 31, 203, 565, 2254, 5034, 1071, 4461, 3882, 21747, 1876, 2156, 560, 14667, 273, 890, 31, 203, 565, 2254, 5034, 1071, 2078, 14667, 273, 1728, 31, 203, 377, 203, 565, 1426, 1071, 1284, 7459, 3678, 273, 629, 31, 203, 565, 2254, 5034, 1071, 2 ]
pragma solidity ^0.4.20; import "../purchase/Purchase.sol"; import "@settlemint/solidity-mint/contracts/marketplaces/tokencuratedregistry/Listing.sol"; /** * Contains one sensor entity */ contract Sensor is Listing { /** @dev Contructor @notice Sets the address for token @param _owner Address of the owner @param _price Price for the listing @param _stakeAmount Amount staked for the listing @param _gateKeeper Address of the gatekeeper */ function Sensor( address _owner, uint _price, uint _stakeAmount, address _gateKeeper ) Listing(_owner, _price, _stakeAmount, _gateKeeper) public {} /** * implementation of cacher methods */ function invalidateCache(address _cachedAddress, bytes32 /*_cachedBytes32*/, uint256 /*_cachedUint256*/) public { emit AddressCacheInvalidated(_cachedAddress); } }
* Contains one sensor entity/
contract Sensor is Listing { @dev Contructor @notice Sets the address for token @param _owner Address of the owner @param _price Price for the listing @param _stakeAmount Amount staked for the listing @param _gateKeeper Address of the gatekeeper function Sensor( address _owner, uint _price, uint _stakeAmount, address _gateKeeper ) Listing(_owner, _price, _stakeAmount, _gateKeeper) public {} function invalidateCache(address _cachedAddress, bytes32 /*_cachedBytes32*/, uint256 /*_cachedUint256*/) public { emit AddressCacheInvalidated(_cachedAddress); } }
12,673,861
[ 1, 10846, 1245, 10583, 1522, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 28903, 353, 987, 310, 288, 203, 203, 225, 632, 5206, 735, 8813, 280, 203, 225, 632, 20392, 7734, 11511, 326, 1758, 364, 1147, 203, 225, 632, 891, 389, 8443, 1850, 5267, 434, 326, 3410, 203, 225, 632, 891, 389, 8694, 1850, 20137, 364, 326, 11591, 203, 225, 632, 891, 389, 334, 911, 6275, 565, 16811, 384, 9477, 364, 326, 11591, 203, 225, 632, 891, 389, 10115, 17891, 377, 5267, 434, 326, 12611, 79, 9868, 203, 225, 445, 28903, 12, 203, 565, 1758, 389, 8443, 16, 203, 565, 2254, 389, 8694, 16, 203, 565, 2254, 389, 334, 911, 6275, 16, 203, 565, 1758, 389, 10115, 17891, 203, 225, 262, 203, 565, 987, 310, 24899, 8443, 16, 389, 8694, 16, 389, 334, 911, 6275, 16, 389, 10115, 17891, 13, 203, 565, 1071, 203, 203, 225, 2618, 203, 225, 445, 11587, 1649, 12, 2867, 389, 7097, 1887, 16, 1731, 1578, 1748, 67, 7097, 2160, 1578, 5549, 16, 2254, 5034, 1748, 67, 7097, 5487, 5034, 5549, 13, 1071, 288, 203, 565, 3626, 5267, 1649, 1941, 690, 24899, 7097, 1887, 1769, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xaF1f5e1c19cB68B30aAD73846eFfDf78a5863319/sources/VaultRegistry.sol
get the latest vault for a token, from this registry or our legacy registry.
function _latestVault(address _token) internal view returns (address) { uint256 length = _numVaults(_token); if (length == 0) { return _fetchFromLegacy(_token); } return vaults[_token][length - 1]; }
2,622,046
[ 1, 588, 326, 4891, 9229, 364, 279, 1147, 16, 628, 333, 4023, 578, 3134, 8866, 4023, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13550, 12003, 12, 2867, 389, 2316, 13, 2713, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 2254, 5034, 769, 273, 389, 2107, 12003, 87, 24899, 2316, 1769, 203, 3639, 309, 261, 2469, 422, 374, 13, 288, 203, 5411, 327, 389, 5754, 1265, 12235, 24899, 2316, 1769, 203, 3639, 289, 203, 3639, 327, 9229, 87, 63, 67, 2316, 6362, 2469, 300, 404, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xA6BfAa28adFD93EEBB8ac2d75Fd957390348049B/sources/k.sol
@notice Factory to deploy KaliDAO.
contract KaliDAOfactory { event DAOdeployed(KaliDAO indexed kaliDAO, string name, string docs); address payable public immutable kaliMaster; IRicardianLLC public immutable ricardianLLC; constructor(address payable kaliMaster_, IRicardianLLC ricardianLLC_) { kaliMaster = kaliMaster_; ricardianLLC = ricardianLLC_; } function deployKaliDAO( string memory name_, string memory symbol_, string memory docs_, bool paused_, address[] memory extensions_, bytes[] memory extensionsData_, address[] calldata voters_, uint256[] calldata shares_, uint32 votingPeriod_, uint8[11] memory govSettings_ ) external payable returns (KaliDAO kaliDAO) { require(extensions_.length == extensionsData_.length, 'NO_ARRAY_PARITY'); kaliDAO = KaliDAO(_cloneAsMinimalProxy(kaliMaster)); name_, symbol_, paused_, extensions_, voters_, shares_, votingPeriod_, govSettings_ ); if (extensions_.length > 0) { unchecked { for (uint256 i; i < extensions_.length; i++) { IKaliDAOextension(extensions_[i]).setExtension(address(kaliDAO), extensionsData_[i]); } } } bytes memory docs = bytes(docs_); if (docs.length == 0) { ricardianLLC.mintLLC(address(kaliDAO)); } emit DAOdeployed(kaliDAO, name_, docs_); } kaliDAO.init{value: msg.value}( function deployKaliDAO( string memory name_, string memory symbol_, string memory docs_, bool paused_, address[] memory extensions_, bytes[] memory extensionsData_, address[] calldata voters_, uint256[] calldata shares_, uint32 votingPeriod_, uint8[11] memory govSettings_ ) external payable returns (KaliDAO kaliDAO) { require(extensions_.length == extensionsData_.length, 'NO_ARRAY_PARITY'); kaliDAO = KaliDAO(_cloneAsMinimalProxy(kaliMaster)); name_, symbol_, paused_, extensions_, voters_, shares_, votingPeriod_, govSettings_ ); if (extensions_.length > 0) { unchecked { for (uint256 i; i < extensions_.length; i++) { IKaliDAOextension(extensions_[i]).setExtension(address(kaliDAO), extensionsData_[i]); } } } bytes memory docs = bytes(docs_); if (docs.length == 0) { ricardianLLC.mintLLC(address(kaliDAO)); } emit DAOdeployed(kaliDAO, name_, docs_); } function deployKaliDAO( string memory name_, string memory symbol_, string memory docs_, bool paused_, address[] memory extensions_, bytes[] memory extensionsData_, address[] calldata voters_, uint256[] calldata shares_, uint32 votingPeriod_, uint8[11] memory govSettings_ ) external payable returns (KaliDAO kaliDAO) { require(extensions_.length == extensionsData_.length, 'NO_ARRAY_PARITY'); kaliDAO = KaliDAO(_cloneAsMinimalProxy(kaliMaster)); name_, symbol_, paused_, extensions_, voters_, shares_, votingPeriod_, govSettings_ ); if (extensions_.length > 0) { unchecked { for (uint256 i; i < extensions_.length; i++) { IKaliDAOextension(extensions_[i]).setExtension(address(kaliDAO), extensionsData_[i]); } } } bytes memory docs = bytes(docs_); if (docs.length == 0) { ricardianLLC.mintLLC(address(kaliDAO)); } emit DAOdeployed(kaliDAO, name_, docs_); } function deployKaliDAO( string memory name_, string memory symbol_, string memory docs_, bool paused_, address[] memory extensions_, bytes[] memory extensionsData_, address[] calldata voters_, uint256[] calldata shares_, uint32 votingPeriod_, uint8[11] memory govSettings_ ) external payable returns (KaliDAO kaliDAO) { require(extensions_.length == extensionsData_.length, 'NO_ARRAY_PARITY'); kaliDAO = KaliDAO(_cloneAsMinimalProxy(kaliMaster)); name_, symbol_, paused_, extensions_, voters_, shares_, votingPeriod_, govSettings_ ); if (extensions_.length > 0) { unchecked { for (uint256 i; i < extensions_.length; i++) { IKaliDAOextension(extensions_[i]).setExtension(address(kaliDAO), extensionsData_[i]); } } } bytes memory docs = bytes(docs_); if (docs.length == 0) { ricardianLLC.mintLLC(address(kaliDAO)); } emit DAOdeployed(kaliDAO, name_, docs_); } function deployKaliDAO( string memory name_, string memory symbol_, string memory docs_, bool paused_, address[] memory extensions_, bytes[] memory extensionsData_, address[] calldata voters_, uint256[] calldata shares_, uint32 votingPeriod_, uint8[11] memory govSettings_ ) external payable returns (KaliDAO kaliDAO) { require(extensions_.length == extensionsData_.length, 'NO_ARRAY_PARITY'); kaliDAO = KaliDAO(_cloneAsMinimalProxy(kaliMaster)); name_, symbol_, paused_, extensions_, voters_, shares_, votingPeriod_, govSettings_ ); if (extensions_.length > 0) { unchecked { for (uint256 i; i < extensions_.length; i++) { IKaliDAOextension(extensions_[i]).setExtension(address(kaliDAO), extensionsData_[i]); } } } bytes memory docs = bytes(docs_); if (docs.length == 0) { ricardianLLC.mintLLC(address(kaliDAO)); } emit DAOdeployed(kaliDAO, name_, docs_); } function _cloneAsMinimalProxy(address payable base) internal virtual returns (address payable clone) { bytes memory createData = abi.encodePacked( bytes10(0x3d602d80600a3d3981f3), bytes10(0x363d3d373d3d3d363d73), base, bytes15(0x5af43d82803e903d91602b57fd5bf3) ); assembly { clone := create( ) } } function _cloneAsMinimalProxy(address payable base) internal virtual returns (address payable clone) { bytes memory createData = abi.encodePacked( bytes10(0x3d602d80600a3d3981f3), bytes10(0x363d3d373d3d3d363d73), base, bytes15(0x5af43d82803e903d91602b57fd5bf3) ); assembly { clone := create( ) } } require(clone != address(0), 'NULL_DEPLOY'); }
12,404,314
[ 1, 1733, 358, 7286, 1475, 18083, 18485, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1475, 18083, 18485, 6848, 288, 203, 565, 871, 463, 20463, 12411, 329, 12, 47, 18083, 18485, 8808, 417, 18083, 18485, 16, 533, 508, 16, 533, 3270, 1769, 203, 203, 565, 1758, 8843, 429, 1071, 11732, 417, 18083, 7786, 31, 203, 203, 565, 15908, 335, 1060, 2779, 4503, 39, 1071, 11732, 436, 335, 1060, 2779, 4503, 39, 31, 203, 203, 565, 3885, 12, 2867, 8843, 429, 417, 18083, 7786, 67, 16, 15908, 335, 1060, 2779, 4503, 39, 436, 335, 1060, 2779, 4503, 39, 67, 13, 288, 203, 3639, 417, 18083, 7786, 273, 417, 18083, 7786, 67, 31, 203, 203, 3639, 436, 335, 1060, 2779, 4503, 39, 273, 436, 335, 1060, 2779, 4503, 39, 67, 31, 203, 565, 289, 203, 377, 203, 565, 445, 7286, 47, 18083, 18485, 12, 203, 3639, 533, 3778, 508, 67, 16, 203, 3639, 533, 3778, 3273, 67, 16, 203, 3639, 533, 3778, 3270, 67, 16, 203, 3639, 1426, 17781, 67, 16, 203, 3639, 1758, 8526, 3778, 4418, 67, 16, 203, 3639, 1731, 8526, 3778, 4418, 751, 67, 16, 203, 3639, 1758, 8526, 745, 892, 331, 352, 414, 67, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 24123, 67, 16, 203, 3639, 2254, 1578, 331, 17128, 5027, 67, 16, 203, 3639, 2254, 28, 63, 2499, 65, 3778, 31841, 2628, 67, 203, 565, 262, 3903, 8843, 429, 1135, 261, 47, 18083, 18485, 417, 18083, 18485, 13, 288, 203, 3639, 2583, 12, 9489, 27799, 2469, 422, 4418, 751, 27799, 2469, 16, 296, 3417, 67, 8552, 67, 2778, 4107, 8284, 203, 203, 3639, 417, 2 ]
./full_match/137/0x32201d0f8C57fCeb5A2e26155bc0412bE9ca83BD/sources/CRPFactory.sol
Burn an amount of new tokens, and subtract them from the balance (and total supply) Emit a transfer amount from this contract to the null address Can't burn more than we have Remove require for gas optimization - bsub will revert on underflow require(_balance[address(this)] >= amount, "ERR_INSUFFICIENT_BAL");
function _burn(uint amount) internal virtual { _balance[address(this)] = BalancerSafeMath.bsub(_balance[address(this)], amount); varTotalSupply = BalancerSafeMath.bsub(varTotalSupply, amount); emit Transfer(address(this), address(0), amount); }
3,765,491
[ 1, 38, 321, 392, 3844, 434, 394, 2430, 16, 471, 10418, 2182, 628, 326, 11013, 261, 464, 2078, 14467, 13, 16008, 279, 7412, 3844, 628, 333, 6835, 358, 326, 446, 1758, 4480, 1404, 18305, 1898, 2353, 732, 1240, 3581, 2583, 364, 16189, 14850, 300, 324, 1717, 903, 15226, 603, 3613, 2426, 2583, 24899, 12296, 63, 2867, 12, 2211, 25887, 1545, 3844, 16, 315, 9712, 67, 706, 6639, 42, 1653, 7266, 2222, 67, 38, 1013, 8863, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 70, 321, 12, 11890, 3844, 13, 2713, 5024, 288, 203, 203, 3639, 389, 12296, 63, 2867, 12, 2211, 25887, 273, 605, 5191, 9890, 10477, 18, 70, 1717, 24899, 12296, 63, 2867, 12, 2211, 13, 6487, 3844, 1769, 203, 3639, 569, 5269, 3088, 1283, 273, 605, 5191, 9890, 10477, 18, 70, 1717, 12, 1401, 5269, 3088, 1283, 16, 3844, 1769, 203, 203, 3639, 3626, 12279, 12, 2867, 12, 2211, 3631, 1758, 12, 20, 3631, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "../ownership/Ownable.sol"; contract RelayProxy { address public __destination; address public __owner; constructor(address _owner, address _destination) public { __owner = _owner; __destination = _destination; } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event DestinationChanged(address indexed previousRelay, address indexed newRelay); /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function __transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Relay: new owner is the zero address"); emit OwnershipTransferred(__owner, newOwner); __owner = newOwner; } function __setDestination(address newDestination) public onlyOwner { require(newDestination != address(0), "new owner address is the zero address"); emit OwnershipTransferred(__destination, newDestination); __destination = newDestination; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() internal view returns (bool) { return msg.sender == __owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Relay: caller is not the owner"); _; } function() payable external { require(isOwner(), "Relay: caller is not the owner"); _relay(__destination); } function _relay(address destination) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize) // Call the destination. // out and outsize are 0 because we don't know the size yet. let result := call(gas, destination, callvalue, 0, calldatasize, 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize) switch result // call returns 0 on error. case 0 {revert(0, returndatasize)} default {return (0, returndatasize)} } } }
Copy msg.data. We take full control of memory in this inline assembly block because it will not return to Solidity code. We overwrite the Solidity scratch pad at memory position 0. Call the destination. out and outsize are 0 because we don't know the size yet. Copy the returned data. call returns 0 on error.
function _relay(address destination) internal { assembly { calldatacopy(0, 0, calldatasize) let result := call(gas, destination, callvalue, 0, calldatasize, 0, 0) returndatacopy(0, 0, returndatasize) switch result } }
1,067,492
[ 1, 2951, 1234, 18, 892, 18, 1660, 4862, 1983, 3325, 434, 3778, 316, 333, 6370, 19931, 1203, 2724, 518, 903, 486, 327, 358, 348, 7953, 560, 981, 18, 1660, 6156, 326, 348, 7953, 560, 15289, 4627, 622, 3778, 1754, 374, 18, 3049, 326, 2929, 18, 596, 471, 596, 1467, 854, 374, 2724, 732, 2727, 1404, 5055, 326, 963, 4671, 18, 5631, 326, 2106, 501, 18, 745, 1135, 374, 603, 555, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2878, 528, 12, 2867, 2929, 13, 2713, 288, 203, 3639, 19931, 288, 203, 5411, 745, 892, 3530, 12, 20, 16, 374, 16, 745, 13178, 554, 13, 203, 203, 5411, 2231, 563, 519, 745, 12, 31604, 16, 2929, 16, 745, 1132, 16, 374, 16, 745, 13178, 554, 16, 374, 16, 374, 13, 203, 203, 5411, 327, 892, 3530, 12, 20, 16, 374, 16, 327, 13178, 554, 13, 203, 203, 5411, 1620, 563, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/40/0x76569fbe7B45Aa83723F590a95807BA94849a5c2/sources/omnidex/nft-marketplace/ERC721NFTMarketV1.sol
Ask order is updated
event AskUpdate(address indexed collection, address indexed seller, uint256 indexed tokenId, uint256 askPrice);
9,543,081
[ 1, 23663, 1353, 353, 3526, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 282, 871, 25747, 1891, 12, 2867, 8808, 1849, 16, 1758, 8808, 29804, 16, 2254, 5034, 8808, 1147, 548, 16, 2254, 5034, 6827, 5147, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.0; import "./Lib/Address.sol"; import "./Lib/SafeMath.sol"; import "./Lib/AddressPayable.sol"; import "./Lib/SafeERC20.sol"; /** * @title NToken contract * @dev Include standard erc20 method, mining method, and mining data */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // Executable contract interface Nest_3_Implement { // Execute function doit() external; } // NestNode assignment contract interface Nest_NodeAssignment { function bookKeeping(uint256 amount) external; } /** * @title Voting factory + mapping * @dev Vote creating method */ contract Nest_3_VoteFactory { using SafeMath for uint256; uint256 _limitTime = 7 days; // Vote duration uint256 _NNLimitTime = 1 days; // NestNode raising time uint256 _circulationProportion = 51; // Proportion of votes to pass uint256 _NNUsedCreate = 10; // The minimum number of NNs to create a voting contract uint256 _NNCreateLimit = 100; // The minimum number of NNs needed to start voting uint256 _emergencyTime = 0; // The emergency state start time uint256 _emergencyTimeLimit = 3 days; // The emergency state duration uint256 _emergencyNNAmount = 1000; // The number of NNs required to switch the emergency state ERC20 _NNToken; // NestNode Token ERC20 _nestToken; // NestToken mapping(string => address) _contractAddress; // Voting contract mapping mapping(address => bool) _modifyAuthority; // Modify permissions mapping(address => address) _myVote; // Personal voting address mapping(address => uint256) _emergencyPerson; // Emergency state personal voting number mapping(address => bool) _contractData; // Voting contract data bool _stateOfEmergency = false; // Emergency state address _destructionAddress; // Destroy contract address event ContractAddress(address contractAddress); /** * @dev Initialization method */ constructor () public { _modifyAuthority[address(msg.sender)] = true; } /** * @dev Reset contract */ function changeMapping() public onlyOwner { _NNToken = ERC20(checkAddress("nestNode")); _destructionAddress = address(checkAddress("nest.v3.destruction")); _nestToken = ERC20(address(checkAddress("nest"))); } /** * @dev Create voting contract * @param implementContract The executable contract address for voting * @param nestNodeAmount Number of NNs to pledge */ function createVote(address implementContract, uint256 nestNodeAmount) public { require(address(tx.origin) == address(msg.sender), "It can't be a contract"); require(nestNodeAmount >= _NNUsedCreate); Nest_3_VoteContract newContract = new Nest_3_VoteContract(implementContract, _stateOfEmergency, nestNodeAmount); require(_NNToken.transferFrom(address(tx.origin), address(newContract), nestNodeAmount), "Authorization transfer failed"); _contractData[address(newContract)] = true; emit ContractAddress(address(newContract)); } /** * @dev Use NEST to vote * @param contractAddress Vote contract address */ function nestVote(address contractAddress) public { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); require(_contractData[contractAddress], "It's not a voting contract"); require(!checkVoteNow(address(msg.sender))); Nest_3_VoteContract newContract = Nest_3_VoteContract(contractAddress); newContract.nestVote(); _myVote[address(tx.origin)] = contractAddress; } /** * @dev Vote using NestNode Token * @param contractAddress Vote contract address * @param NNAmount Amount of NNs to pledge */ function nestNodeVote(address contractAddress, uint256 NNAmount) public { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); require(_contractData[contractAddress], "It's not a voting contract"); Nest_3_VoteContract newContract = Nest_3_VoteContract(contractAddress); require(_NNToken.transferFrom(address(tx.origin), address(newContract), NNAmount), "Authorization transfer failed"); newContract.nestNodeVote(NNAmount); } /** * @dev Excecute contract * @param contractAddress Vote contract address */ function startChange(address contractAddress) public { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); require(_contractData[contractAddress], "It's not a voting contract"); Nest_3_VoteContract newContract = Nest_3_VoteContract(contractAddress); require(_stateOfEmergency == newContract.checkStateOfEmergency()); addSuperManPrivate(address(newContract)); newContract.startChange(); deleteSuperManPrivate(address(newContract)); } /** * @dev Switch emergency state-transfer in NestNode Token * @param amount Amount of NNs to transfer */ function sendNestNodeForStateOfEmergency(uint256 amount) public { require(_NNToken.transferFrom(address(tx.origin), address(this), amount)); _emergencyPerson[address(tx.origin)] = _emergencyPerson[address(tx.origin)].add(amount); } /** * @dev Switch emergency state-transfer out NestNode Token */ function turnOutNestNodeForStateOfEmergency() public { require(_emergencyPerson[address(tx.origin)] > 0); require(_NNToken.transfer(address(tx.origin), _emergencyPerson[address(tx.origin)])); _emergencyPerson[address(tx.origin)] = 0; uint256 nestAmount = _nestToken.balanceOf(address(this)); require(_nestToken.transfer(address(_destructionAddress), nestAmount)); } /** * @dev Modify emergency state */ function changeStateOfEmergency() public { if (_stateOfEmergency) { require(now > _emergencyTime.add(_emergencyTimeLimit)); _stateOfEmergency = false; _emergencyTime = 0; } else { require(_emergencyPerson[address(msg.sender)] > 0); require(_NNToken.balanceOf(address(this)) >= _emergencyNNAmount); _stateOfEmergency = true; _emergencyTime = now; } } /** * @dev Check whether participating in the voting * @param user Address to check * @return bool Whether voting */ function checkVoteNow(address user) public view returns (bool) { if (_myVote[user] == address(0x0)) { return false; } else { Nest_3_VoteContract vote = Nest_3_VoteContract(_myVote[user]); if (vote.checkContractEffective() || vote.checkPersonalAmount(user) == 0) { return false; } return true; } } /** * @dev Check my voting * @param user Address to check * @return address Address recently participated in the voting contract address */ function checkMyVote(address user) public view returns (address) { return _myVote[user]; } // Check the voting time function checkLimitTime() public view returns (uint256) { return _limitTime; } // Check the NestNode raising time function checkNNLimitTime() public view returns (uint256) { return _NNLimitTime; } // Check the voting proportion to pass function checkCirculationProportion() public view returns (uint256) { return _circulationProportion; } // Check the minimum number of NNs to create a voting contract function checkNNUsedCreate() public view returns (uint256) { return _NNUsedCreate; } // Check the minimum number of NNs raised to start a vote function checkNNCreateLimit() public view returns (uint256) { return _NNCreateLimit; } // Check whether in emergency state function checkStateOfEmergency() public view returns (bool) { return _stateOfEmergency; } // Check the start time of the emergency state function checkEmergencyTime() public view returns (uint256) { return _emergencyTime; } // Check the duration of the emergency state function checkEmergencyTimeLimit() public view returns (uint256) { return _emergencyTimeLimit; } // Check the amount of personal pledged NNs function checkEmergencyPerson(address user) public view returns (uint256) { return _emergencyPerson[user]; } // Check the number of NNs required for the emergency function checkEmergencyNNAmount() public view returns (uint256) { return _emergencyNNAmount; } // Verify voting contract data function checkContractData(address contractAddress) public view returns (bool) { return _contractData[contractAddress]; } // Modify voting time function changeLimitTime(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _limitTime = num; } // Modify the NestNode raising time function changeNNLimitTime(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _NNLimitTime = num; } // Modify the voting proportion function changeCirculationProportion(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _circulationProportion = num; } // Modify the minimum number of NNs to create a voting contract function changeNNUsedCreate(uint256 num) public onlyOwner { _NNUsedCreate = num; } // Modify the minimum number of NNs to raised to start a voting function checkNNCreateLimit(uint256 num) public onlyOwner { _NNCreateLimit = num; } // Modify the emergency state duration function changeEmergencyTimeLimit(uint256 num) public onlyOwner { require(num > 0); _emergencyTimeLimit = num.mul(1 days); } // Modify the number of NNs required for emergency state function changeEmergencyNNAmount(uint256 num) public onlyOwner { require(num > 0); _emergencyNNAmount = num; } // Check address function checkAddress(string memory name) public view returns (address contractAddress) { return _contractAddress[name]; } // Add contract mapping address function addContractAddress(string memory name, address contractAddress) public onlyOwner { _contractAddress[name] = contractAddress; } // Add administrator address function addSuperMan(address superMan) public onlyOwner { _modifyAuthority[superMan] = true; } function addSuperManPrivate(address superMan) private { _modifyAuthority[superMan] = true; } // Delete administrator address function deleteSuperMan(address superMan) public onlyOwner { _modifyAuthority[superMan] = false; } function deleteSuperManPrivate(address superMan) private { _modifyAuthority[superMan] = false; } // Delete voting contract data function deleteContractData(address contractAddress) public onlyOwner { _contractData[contractAddress] = false; } // Check whether the administrator function checkOwners(address man) public view returns (bool) { return _modifyAuthority[man]; } // Administrator only modifier onlyOwner() { require(checkOwners(msg.sender), "No authority"); _; } } /** * @title Voting contract */ contract Nest_3_VoteContract { using SafeMath for uint256; Nest_3_Implement _implementContract; // Executable contract Nest_3_TokenSave _tokenSave; // Lock-up contract Nest_3_VoteFactory _voteFactory; // Voting factory contract Nest_3_TokenAbonus _tokenAbonus; // Bonus logic contract ERC20 _nestToken; // NestToken ERC20 _NNToken; // NestNode Token address _miningSave; // Mining pool contract address _implementAddress; // Executable contract address address _destructionAddress; // Destruction contract address uint256 _createTime; // Creation time uint256 _endTime; // End time uint256 _totalAmount; // Total votes uint256 _circulation; // Passed votes uint256 _destroyedNest; // Destroyed NEST uint256 _NNLimitTime; // NestNode raising time uint256 _NNCreateLimit; // Minimum number of NNs to create votes uint256 _abonusTimes; // Period number of used snapshot in emergency state uint256 _allNNAmount; // Total number of NNs bool _effective = false; // Whether vote is effective bool _nestVote = false; // Whether NEST vote can be performed bool _isChange = false; // Whether NEST vote is executed bool _stateOfEmergency; // Whether the contract is in emergency state mapping(address => uint256) _personalAmount; // Number of personal votes mapping(address => uint256) _personalNNAmount; // Number of NN personal votes /** * @dev Initialization method * @param contractAddress Executable contract address * @param stateOfEmergency Whether in emergency state * @param NNAmount Amount of NNs */ constructor (address contractAddress, bool stateOfEmergency, uint256 NNAmount) public { Nest_3_VoteFactory voteFactory = Nest_3_VoteFactory(address(msg.sender)); _voteFactory = voteFactory; _nestToken = ERC20(voteFactory.checkAddress("nest")); _NNToken = ERC20(voteFactory.checkAddress("nestNode")); _implementContract = Nest_3_Implement(address(contractAddress)); _implementAddress = address(contractAddress); _destructionAddress = address(voteFactory.checkAddress("nest.v3.destruction")); _personalNNAmount[address(tx.origin)] = NNAmount; _allNNAmount = NNAmount; _createTime = now; _endTime = _createTime.add(voteFactory.checkLimitTime()); _NNLimitTime = voteFactory.checkNNLimitTime(); _NNCreateLimit = voteFactory.checkNNCreateLimit(); _stateOfEmergency = stateOfEmergency; if (stateOfEmergency) { // If in emergency state, read the last two periods of bonus lock-up and total circulation data _tokenAbonus = Nest_3_TokenAbonus(payable(voteFactory.checkAddress("nest.v3.tokenAbonus"))); _abonusTimes = _tokenAbonus.checkTimes().sub(2); require(_abonusTimes > 0); _circulation = _tokenAbonus.checkTokenAllValueHistory(address(_nestToken),_abonusTimes).mul(voteFactory.checkCirculationProportion()).div(100); } else { _miningSave = address(voteFactory.checkAddress("nest.v3.miningSave")); _tokenSave = Nest_3_TokenSave(voteFactory.checkAddress("nest.v3.tokenSave")); _circulation = (uint256(10000000000 ether).sub(_nestToken.balanceOf(address(_miningSave))).sub(_nestToken.balanceOf(address(_destructionAddress)))).mul(voteFactory.checkCirculationProportion()).div(100); } if (_allNNAmount >= _NNCreateLimit) { _nestVote = true; } } /** * @dev NEST voting */ function nestVote() public onlyFactory { require(now <= _endTime, "Voting time exceeded"); require(!_effective, "Vote in force"); require(_nestVote); require(_personalAmount[address(tx.origin)] == 0, "Have voted"); uint256 amount; if (_stateOfEmergency) { // If in emergency state, read the last two periods of bonus lock-up and total circulation data amount = _tokenAbonus.checkTokenSelfHistory(address(_nestToken),_abonusTimes, address(tx.origin)); } else { amount = _tokenSave.checkAmount(address(tx.origin), address(_nestToken)); } _personalAmount[address(tx.origin)] = amount; _totalAmount = _totalAmount.add(amount); ifEffective(); } /** * @dev NEST voting cancellation */ function nestVoteCancel() public { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); require(now <= _endTime, "Voting time exceeded"); require(!_effective, "Vote in force"); require(_personalAmount[address(tx.origin)] > 0, "No vote"); _totalAmount = _totalAmount.sub(_personalAmount[address(tx.origin)]); _personalAmount[address(tx.origin)] = 0; } /** * @dev NestNode voting * @param NNAmount Amount of NNs */ function nestNodeVote(uint256 NNAmount) public onlyFactory { require(now <= _createTime.add(_NNLimitTime), "Voting time exceeded"); require(!_nestVote); _personalNNAmount[address(tx.origin)] = _personalNNAmount[address(tx.origin)].add(NNAmount); _allNNAmount = _allNNAmount.add(NNAmount); if (_allNNAmount >= _NNCreateLimit) { _nestVote = true; } } /** * @dev Withdrawing lock-up NNs */ function turnOutNestNode() public { if (_nestVote) { // Normal NEST voting if (!_stateOfEmergency || !_effective) { // Non-emergency state require(now > _endTime, "Vote unenforceable"); } } else { // NN voting require(now > _createTime.add(_NNLimitTime)); } require(_personalNNAmount[address(tx.origin)] > 0); // Reverting back the NNs require(_NNToken.transfer(address(tx.origin), _personalNNAmount[address(tx.origin)])); _personalNNAmount[address(tx.origin)] = 0; // Destroying NEST Tokens uint256 nestAmount = _nestToken.balanceOf(address(this)); _destroyedNest = _destroyedNest.add(nestAmount); require(_nestToken.transfer(address(_destructionAddress), nestAmount)); } /** * @dev Execute the contract */ function startChange() public onlyFactory { require(!_isChange); _isChange = true; if (_stateOfEmergency) { require(_effective, "Vote unenforceable"); } else { require(_effective && now > _endTime, "Vote unenforceable"); } // Add the executable contract to the administrator list _voteFactory.addSuperMan(address(_implementContract)); // Execute _implementContract.doit(); // Delete the authorization _voteFactory.deleteSuperMan(address(_implementContract)); } /** * @dev check whether the vote is effective */ function ifEffective() private { if (_totalAmount >= _circulation) { _effective = true; } } /** * @dev Check whether the vote is over */ function checkContractEffective() public view returns (bool) { if (_effective || now > _endTime) { return true; } return false; } // Check the executable implement contract address function checkImplementAddress() public view returns (address) { return _implementAddress; } // Check the voting start time function checkCreateTime() public view returns (uint256) { return _createTime; } // Check the voting end time function checkEndTime() public view returns (uint256) { return _endTime; } // Check the current total number of votes function checkTotalAmount() public view returns (uint256) { return _totalAmount; } // Check the number of votes to pass function checkCirculation() public view returns (uint256) { return _circulation; } // Check the number of personal votes function checkPersonalAmount(address user) public view returns (uint256) { return _personalAmount[user]; } // Check the destroyed NEST function checkDestroyedNest() public view returns (uint256) { return _destroyedNest; } // Check whether the contract is effective function checkEffective() public view returns (bool) { return _effective; } // Check whether in emergency state function checkStateOfEmergency() public view returns (bool) { return _stateOfEmergency; } // Check NestNode raising time function checkNNLimitTime() public view returns (uint256) { return _NNLimitTime; } // Check the minimum number of NNs to create a vote function checkNNCreateLimit() public view returns (uint256) { return _NNCreateLimit; } // Check the period number of snapshot used in the emergency state function checkAbonusTimes() public view returns (uint256) { return _abonusTimes; } // Check number of personal votes function checkPersonalNNAmount(address user) public view returns (uint256) { return _personalNNAmount[address(user)]; } // Check the total number of NNs function checkAllNNAmount() public view returns (uint256) { return _allNNAmount; } // Check whether NEST voting is available function checkNestVote() public view returns (bool) { return _nestVote; } // Check whether it has been excecuted function checkIsChange() public view returns (bool) { return _isChange; } // Vote Factory contract only modifier onlyFactory() { require(address(_voteFactory) == address(msg.sender), "No authority"); _; } } /** * @title Mining contract * @dev Mining pool + mining logic */ contract Nest_3_MiningContract { using address_make_payable for address; using SafeMath for uint256; uint256 _blockAttenuation = 2400000; // Block decay time interval uint256[10] _attenuationAmount; // Mining decay amount uint256 _afterMiningAmount = 40 ether; // Stable period mining amount uint256 _firstBlockNum; // Starting mining block uint256 _latestMining; // Latest offering block Nest_3_VoteFactory _voteFactory; // Voting contract ERC20 _nestContract; // NEST contract address address _offerFactoryAddress; // Offering contract address // Current block, current block mining amount event OreDrawingLog(uint256 nowBlock, uint256 blockAmount); /** * @dev Initialization method * @param voteFactory voting contract address */ constructor(address voteFactory) public { _voteFactory = Nest_3_VoteFactory(address(voteFactory)); _offerFactoryAddress = address(_voteFactory.checkAddress("nest.v3.offerMain")); _nestContract = ERC20(address(_voteFactory.checkAddress("nest"))); // Initiate mining parameters _firstBlockNum = 6236588; _latestMining = block.number; uint256 blockAmount = 400 ether; for (uint256 i = 0; i < 10; i ++) { _attenuationAmount[i] = blockAmount; blockAmount = blockAmount.mul(8).div(10); } } /** * @dev Reset voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner { _voteFactory = Nest_3_VoteFactory(address(voteFactory)); _offerFactoryAddress = address(_voteFactory.checkAddress("nest.v3.offerMain")); _nestContract = ERC20(address(_voteFactory.checkAddress("nest"))); } /** * @dev Offering mining * @return Current block mining amount */ function oreDrawing() public returns (uint256) { require(address(msg.sender) == _offerFactoryAddress, "No authority"); // Update mining amount list uint256 miningAmount = changeBlockAmountList(); // Transfer NEST if (_nestContract.balanceOf(address(this)) < miningAmount){ miningAmount = _nestContract.balanceOf(address(this)); } if (miningAmount > 0) { _nestContract.transfer(address(msg.sender), miningAmount); emit OreDrawingLog(block.number,miningAmount); } return miningAmount; } /** * @dev Update mining amount list */ function changeBlockAmountList() private returns (uint256) { uint256 createBlock = _firstBlockNum; uint256 recentlyUsedBlock = _latestMining; uint256 attenuationPointNow = block.number.sub(createBlock).div(_blockAttenuation); uint256 miningAmount = 0; uint256 attenuation; if (attenuationPointNow > 9) { attenuation = _afterMiningAmount; } else { attenuation = _attenuationAmount[attenuationPointNow]; } miningAmount = attenuation.mul(block.number.sub(recentlyUsedBlock)); _latestMining = block.number; return miningAmount; } /** * @dev Transfer all NEST * @param target Transfer target address */ function takeOutNest(address target) public onlyOwner { _nestContract.transfer(address(target),_nestContract.balanceOf(address(this))); } // Check block decay time interval function checkBlockAttenuation() public view returns(uint256) { return _blockAttenuation; } // Check latest offering block function checkLatestMining() public view returns(uint256) { return _latestMining; } // Check mining amount decay function checkAttenuationAmount(uint256 num) public view returns(uint256) { return _attenuationAmount[num]; } // Check NEST balance function checkNestBalance() public view returns(uint256) { return _nestContract.balanceOf(address(this)); } // Modify block decay time interval function changeBlockAttenuation(uint256 blockNum) public onlyOwner { require(blockNum > 0); _blockAttenuation = blockNum; } // Modify mining amount decay function changeAttenuationAmount(uint256 firstAmount, uint256 top, uint256 bottom) public onlyOwner { uint256 blockAmount = firstAmount; for (uint256 i = 0; i < 10; i ++) { _attenuationAmount[i] = blockAmount; blockAmount = blockAmount.mul(top).div(bottom); } } // Administrator only modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender), "No authority"); _; } } /** * @title Offering contract * @dev Offering + take order + NEST allocation */ contract Nest_3_OfferMain { using SafeMath for uint256; using address_make_payable for address; using SafeERC20 for ERC20; struct Nest_3_OfferPriceData { // The unique identifier is determined by the position of the offer in the array, and is converted to each other through a fixed algorithm (toindex(), toaddress()) address owner; // Offering owner bool deviate; // Whether it deviates address tokenAddress; // The erc20 contract address of the target offer token uint256 ethAmount; // The ETH amount in the offer list uint256 tokenAmount; // The token amount in the offer list uint256 dealEthAmount; // The remaining number of tradable ETH uint256 dealTokenAmount; // The remaining number of tradable tokens uint256 blockNum; // The block number where the offer is located uint256 serviceCharge; // The fee for mining // Determine whether the asset has been collected by judging that ethamount, tokenamount, and servicecharge are all 0 } Nest_3_OfferPriceData [] _prices; // Array used to save offers mapping(address => bool) _tokenAllow; // List of allowed mining token Nest_3_VoteFactory _voteFactory; // Vote contract Nest_3_OfferPrice _offerPrice; // Price contract Nest_3_MiningContract _miningContract; // Mining contract Nest_NodeAssignment _NNcontract; // NestNode contract ERC20 _nestToken; // NestToken Nest_3_Abonus _abonus; // Bonus pool address _coderAddress; // Developer address uint256 _miningETH = 10; // Offering mining fee ratio uint256 _tranEth = 1; // Taker fee ratio uint256 _tranAddition = 2; // Additional transaction multiple uint256 _coderAmount = 5; // Developer ratio uint256 _NNAmount = 15; // NestNode ratio uint256 _leastEth = 10 ether; // Minimum offer of ETH uint256 _offerSpan = 10 ether; // ETH Offering span uint256 _deviate = 10; // Price deviation - 10% uint256 _deviationFromScale = 10; // Deviation from asset scale uint32 _blockLimit = 25; // Block interval upper limit mapping(uint256 => uint256) _offerBlockEth; // Block offer fee mapping(uint256 => uint256) _offerBlockMining; // Block mining amount // Log offering contract, token address, number of eth, number of erc20, number of continuous blocks, number of fees event OfferContractAddress(address contractAddress, address tokenAddress, uint256 ethAmount, uint256 erc20Amount, uint256 continued, uint256 serviceCharge); // Log transaction, transaction initiator, transaction token address, number of transaction token, token address, number of token, traded offering contract address, traded user address event OfferTran(address tranSender, address tranToken, uint256 tranAmount,address otherToken, uint256 otherAmount, address tradedContract, address tradedOwner); /** * @dev Initialization method * @param voteFactory Voting contract address */ constructor (address voteFactory) public { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice"))); _miningContract = Nest_3_MiningContract(address(voteFactoryMap.checkAddress("nest.v3.miningSave"))); _abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus")); _nestToken = ERC20(voteFactoryMap.checkAddress("nest")); _NNcontract = Nest_NodeAssignment(address(voteFactoryMap.checkAddress("nodeAssignment"))); _coderAddress = voteFactoryMap.checkAddress("nest.v3.coder"); require(_nestToken.approve(address(_NNcontract), uint256(10000000000 ether)), "Authorization failed"); } /** * @dev Reset voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice"))); _miningContract = Nest_3_MiningContract(address(voteFactoryMap.checkAddress("nest.v3.miningSave"))); _abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus")); _nestToken = ERC20(voteFactoryMap.checkAddress("nest")); _NNcontract = Nest_NodeAssignment(address(voteFactoryMap.checkAddress("nodeAssignment"))); _coderAddress = voteFactoryMap.checkAddress("nest.v3.coder"); require(_nestToken.approve(address(_NNcontract), uint256(10000000000 ether)), "Authorization failed"); } /** * @dev Offering mining * @param ethAmount Offering ETH amount * @param erc20Amount Offering erc20 token amount * @param erc20Address Offering erc20 token address */ function offer(uint256 ethAmount, uint256 erc20Amount, address erc20Address) public payable { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); require(_tokenAllow[erc20Address], "Token not allow"); // Judge whether the price deviates uint256 ethMining; bool isDeviate = comparativePrice(ethAmount,erc20Amount,erc20Address); if (isDeviate) { require(ethAmount >= _leastEth.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of the minimum scale"); ethMining = _leastEth.mul(_miningETH).div(1000); } else { ethMining = ethAmount.mul(_miningETH).div(1000); } require(msg.value >= ethAmount.add(ethMining), "msg.value needs to be equal to the quoted eth quantity plus Mining handling fee"); uint256 subValue = msg.value.sub(ethAmount.add(ethMining)); if (subValue > 0) { repayEth(address(msg.sender), subValue); } // Create an offer createOffer(ethAmount, erc20Amount, erc20Address, ethMining, isDeviate); // Transfer in offer asset - erc20 to this contract ERC20(erc20Address).safeTransferFrom(address(msg.sender), address(this), erc20Amount); // Mining uint256 miningAmount = _miningContract.oreDrawing(); _abonus.switchToEth.value(ethMining)(address(_nestToken)); if (miningAmount > 0) { uint256 coder = miningAmount.mul(_coderAmount).div(100); uint256 NN = miningAmount.mul(_NNAmount).div(100); uint256 other = miningAmount.sub(coder).sub(NN); _offerBlockMining[block.number] = other; _NNcontract.bookKeeping(NN); if (coder > 0) { _nestToken.safeTransfer(_coderAddress, coder); } } _offerBlockEth[block.number] = _offerBlockEth[block.number].add(ethMining); } /** * @dev Create offer * @param ethAmount Offering ETH amount * @param erc20Amount Offering erc20 amount * @param erc20Address Offering erc20 address * @param mining Offering mining fee (0 for takers) * @param isDeviate Whether the current price chain deviates */ function createOffer(uint256 ethAmount, uint256 erc20Amount, address erc20Address, uint256 mining, bool isDeviate) private { // Check offer conditions require(ethAmount >= _leastEth, "Eth scale is smaller than the minimum scale"); require(ethAmount % _offerSpan == 0, "Non compliant asset span"); require(erc20Amount % (ethAmount.div(_offerSpan)) == 0, "Asset quantity is not divided"); require(erc20Amount > 0); // Create offering contract emit OfferContractAddress(toAddress(_prices.length), address(erc20Address), ethAmount, erc20Amount,_blockLimit,mining); _prices.push(Nest_3_OfferPriceData( msg.sender, isDeviate, erc20Address, ethAmount, erc20Amount, ethAmount, erc20Amount, block.number, mining )); // Record price _offerPrice.addPrice(ethAmount, erc20Amount, block.number.add(_blockLimit), erc20Address, address(msg.sender)); } /** * @dev Taker order - pay ETH and buy erc20 * @param ethAmount The amount of ETH of this offer * @param tokenAmount The amount of erc20 of this offer * @param contractAddress The target offer address * @param tranEthAmount The amount of ETH of taker order * @param tranTokenAmount The amount of erc20 of taker order * @param tranTokenAddress The erc20 address of taker order */ function sendEthBuyErc(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); // Get the offer data structure uint256 index = toIndex(contractAddress); Nest_3_OfferPriceData memory offerPriceData = _prices[index]; // Check the price, compare the current offer to the last effective price bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress); bool isDeviate; if (offerPriceData.deviate == true) { isDeviate = true; } else { isDeviate = thisDeviate; } // Limit the taker order only be twice the amount of the offer to prevent large-amount attacks if (offerPriceData.deviate) { // The taker order deviates x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } else { if (isDeviate) { // If the taken offer is normal and the taker order deviates x10 require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale"); } else { // If the taken offer is normal and the taker order is normal x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } } uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000); require(msg.value == ethAmount.add(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quotation eth quantity plus transaction eth plus transaction handling fee"); require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span"); // Check whether the conditions for taker order are satisfied require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error"); require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth"); require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token"); require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address"); require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount"); // Update the offer information offerPriceData.ethAmount = offerPriceData.ethAmount.add(tranEthAmount); offerPriceData.tokenAmount = offerPriceData.tokenAmount.sub(tranTokenAmount); offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount); offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount); _prices[index] = offerPriceData; // Create a new offer createOffer(ethAmount, tokenAmount, tranTokenAddress, 0, isDeviate); // Transfer in erc20 + offer asset to this contract if (tokenAmount > tranTokenAmount) { ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tokenAmount.sub(tranTokenAmount)); } else { ERC20(tranTokenAddress).safeTransfer(address(msg.sender), tranTokenAmount.sub(tokenAmount)); } // Modify price _offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit)); emit OfferTran(address(msg.sender), address(0x0), tranEthAmount, address(tranTokenAddress), tranTokenAmount, contractAddress, offerPriceData.owner); // Transfer fee if (serviceCharge > 0) { _abonus.switchToEth.value(serviceCharge)(address(_nestToken)); } } /** * @dev Taker order - pay erc20 and buy ETH * @param ethAmount The amount of ETH of this offer * @param tokenAmount The amount of erc20 of this offer * @param contractAddress The target offer address * @param tranEthAmount The amount of ETH of taker order * @param tranTokenAmount The amount of erc20 of taker order * @param tranTokenAddress The erc20 address of taker order */ function sendErcBuyEth(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); // Get the offer data structure uint256 index = toIndex(contractAddress); Nest_3_OfferPriceData memory offerPriceData = _prices[index]; // Check the price, compare the current offer to the last effective price bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress); bool isDeviate; if (offerPriceData.deviate == true) { isDeviate = true; } else { isDeviate = thisDeviate; } // Limit the taker order only be twice the amount of the offer to prevent large-amount attacks if (offerPriceData.deviate) { // The taker order deviates x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } else { if (isDeviate) { // If the taken offer is normal and the taker order deviates x10 require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale"); } else { // If the taken offer is normal and the taker order is normal x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } } uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000); require(msg.value == ethAmount.sub(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quoted eth quantity plus transaction handling fee"); require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span"); // Check whether the conditions for taker order are satisfied require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error"); require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth"); require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token"); require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address"); require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount"); // Update the offer information offerPriceData.ethAmount = offerPriceData.ethAmount.sub(tranEthAmount); offerPriceData.tokenAmount = offerPriceData.tokenAmount.add(tranTokenAmount); offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount); offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount); _prices[index] = offerPriceData; // Create a new offer createOffer(ethAmount, tokenAmount, tranTokenAddress, 0, isDeviate); // Transfer in erc20 + offer asset to this contract ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tranTokenAmount.add(tokenAmount)); // Modify price _offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit)); emit OfferTran(address(msg.sender), address(tranTokenAddress), tranTokenAmount, address(0x0), tranEthAmount, contractAddress, offerPriceData.owner); // Transfer fee if (serviceCharge > 0) { _abonus.switchToEth.value(serviceCharge)(address(_nestToken)); } } /** * @dev Withdraw the assets, and settle the mining * @param contractAddress The offer address to withdraw */ function turnOut(address contractAddress) public { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); uint256 index = toIndex(contractAddress); Nest_3_OfferPriceData storage offerPriceData = _prices[index]; require(checkContractState(offerPriceData.blockNum) == 1, "Offer status error"); // Withdraw ETH if (offerPriceData.ethAmount > 0) { uint256 payEth = offerPriceData.ethAmount; offerPriceData.ethAmount = 0; repayEth(offerPriceData.owner, payEth); } // Withdraw erc20 if (offerPriceData.tokenAmount > 0) { uint256 payErc = offerPriceData.tokenAmount; offerPriceData.tokenAmount = 0; ERC20(address(offerPriceData.tokenAddress)).safeTransfer(offerPriceData.owner, payErc); } // Mining settlement if (offerPriceData.serviceCharge > 0) { uint256 myMiningAmount = offerPriceData.serviceCharge.mul(_offerBlockMining[offerPriceData.blockNum]).div(_offerBlockEth[offerPriceData.blockNum]); _nestToken.safeTransfer(offerPriceData.owner, myMiningAmount); offerPriceData.serviceCharge = 0; } } // Convert offer address into index in offer array function toIndex(address contractAddress) public pure returns(uint256) { return uint256(contractAddress); } // Convert index in offer array into offer address function toAddress(uint256 index) public pure returns(address) { return address(index); } // View contract state function checkContractState(uint256 createBlock) public view returns (uint256) { if (block.number.sub(createBlock) > _blockLimit) { return 1; } return 0; } // Compare the order price function comparativePrice(uint256 myEthValue, uint256 myTokenValue, address token) private view returns(bool) { (uint256 frontEthValue, uint256 frontTokenValue) = _offerPrice.updateAndCheckPricePrivate(token); if (frontEthValue == 0 || frontTokenValue == 0) { return false; } uint256 maxTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).add(_deviate)).div(frontEthValue.mul(100)); if (myTokenValue <= maxTokenAmount) { uint256 minTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).sub(_deviate)).div(frontEthValue.mul(100)); if (myTokenValue >= minTokenAmount) { return false; } } return true; } // Transfer ETH function repayEth(address accountAddress, uint256 asset) private { address payable addr = accountAddress.make_payable(); addr.transfer(asset); } // View the upper limit of the block interval function checkBlockLimit() public view returns(uint32) { return _blockLimit; } // View offering mining fee ratio function checkMiningETH() public view returns (uint256) { return _miningETH; } // View whether the token is allowed to mine function checkTokenAllow(address token) public view returns(bool) { return _tokenAllow[token]; } // View additional transaction multiple function checkTranAddition() public view returns(uint256) { return _tranAddition; } // View the development allocation ratio function checkCoderAmount() public view returns(uint256) { return _coderAmount; } // View the NestNode allocation ratio function checkNNAmount() public view returns(uint256) { return _NNAmount; } // View the least offering ETH function checkleastEth() public view returns(uint256) { return _leastEth; } // View offering ETH span function checkOfferSpan() public view returns(uint256) { return _offerSpan; } // View the price deviation function checkDeviate() public view returns(uint256){ return _deviate; } // View deviation from scale function checkDeviationFromScale() public view returns(uint256) { return _deviationFromScale; } // View block offer fee function checkOfferBlockEth(uint256 blockNum) public view returns(uint256) { return _offerBlockEth[blockNum]; } // View taker order fee ratio function checkTranEth() public view returns (uint256) { return _tranEth; } // View block mining amount of user function checkOfferBlockMining(uint256 blockNum) public view returns(uint256) { return _offerBlockMining[blockNum]; } // View offer mining amount function checkOfferMining(uint256 blockNum, uint256 serviceCharge) public view returns (uint256) { if (serviceCharge == 0) { return 0; } else { return _offerBlockMining[blockNum].mul(serviceCharge).div(_offerBlockEth[blockNum]); } } // Change offering mining fee ratio function changeMiningETH(uint256 num) public onlyOwner { _miningETH = num; } // Modify taker fee ratio function changeTranEth(uint256 num) public onlyOwner { _tranEth = num; } // Modify the upper limit of the block interval function changeBlockLimit(uint32 num) public onlyOwner { _blockLimit = num; } // Modify whether the token allows mining function changeTokenAllow(address token, bool allow) public onlyOwner { _tokenAllow[token] = allow; } // Modify additional transaction multiple function changeTranAddition(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _tranAddition = num; } // Modify the initial allocation ratio function changeInitialRatio(uint256 coderNum, uint256 NNNum) public onlyOwner { require(coderNum.add(NNNum) <= 100, "User allocation ratio error"); _coderAmount = coderNum; _NNAmount = NNNum; } // Modify the minimum offering ETH function changeLeastEth(uint256 num) public onlyOwner { require(num > 0); _leastEth = num; } // Modify the offering ETH span function changeOfferSpan(uint256 num) public onlyOwner { require(num > 0); _offerSpan = num; } // Modify the price deviation function changekDeviate(uint256 num) public onlyOwner { _deviate = num; } // Modify the deviation from scale function changeDeviationFromScale(uint256 num) public onlyOwner { _deviationFromScale = num; } /** * Get the number of offers stored in the offer array * @return The number of offers stored in the offer array **/ function getPriceCount() view public returns (uint256) { return _prices.length; } /** * Get offer information according to the index * @param priceIndex Offer index * @return Offer information **/ function getPrice(uint256 priceIndex) view public returns (string memory) { // The buffer array used to generate the result string bytes memory buf = new bytes(500000); uint256 index = 0; index = writeOfferPriceData(priceIndex, _prices[priceIndex], buf, index); // Generate the result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } /** * Search the contract address list of the target account (reverse order) * @param start Search forward from the index corresponding to the given contract address (not including the record corresponding to start address) * @param count Maximum number of records to return * @param maxFindCount The max index to search * @param owner Target account address * @return Separate the offer records with symbols. use , to divide fields: * uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge **/ function find(address start, uint256 count, uint256 maxFindCount, address owner) view public returns (string memory) { // Buffer array used to generate result string bytes memory buf = new bytes(500000); uint256 index = 0; // Calculate search interval i and end uint256 i = _prices.length; uint256 end = 0; if (start != address(0)) { i = toIndex(start); } if (i > maxFindCount) { end = i - maxFindCount; } // Loop search, write qualified records into buffer while (count > 0 && i-- > end) { Nest_3_OfferPriceData memory price = _prices[i]; if (price.owner == owner) { --count; index = writeOfferPriceData(i, price, buf, index); } } // Generate result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } /** * Get the list of offers by page * @param offset Skip the first offset records * @param count Maximum number of records to return * @param order Sort rules. 0 means reverse order, non-zero means positive order * @return Separate the offer records with symbols. use , to divide fields: * uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge **/ function list(uint256 offset, uint256 count, uint256 order) view public returns (string memory) { // Buffer array used to generate result string bytes memory buf = new bytes(500000); uint256 index = 0; // Find search interval i and end uint256 i = 0; uint256 end = 0; if (order == 0) { // Reverse order, in default // Calculate search interval i and end if (offset < _prices.length) { i = _prices.length - offset; } if (count < i) { end = i - count; } // Write records in the target interval into the buffer while (i-- > end) { index = writeOfferPriceData(i, _prices[i], buf, index); } } else { // Ascending order // Calculate the search interval i and end if (offset < _prices.length) { i = offset; } else { i = _prices.length; } end = i + count; if(end > _prices.length) { end = _prices.length; } // Write the records in the target interval into the buffer while (i < end) { index = writeOfferPriceData(i, _prices[i], buf, index); ++i; } } // Generate the result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } // Write the offer data into the buffer and return the buffer index function writeOfferPriceData(uint256 priceIndex, Nest_3_OfferPriceData memory price, bytes memory buf, uint256 index) pure private returns (uint256) { index = writeAddress(toAddress(priceIndex), buf, index); buf[index++] = byte(uint8(44)); index = writeAddress(price.owner, buf, index); buf[index++] = byte(uint8(44)); index = writeAddress(price.tokenAddress, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.ethAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.tokenAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.dealEthAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.dealTokenAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.blockNum, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.serviceCharge, buf, index); buf[index++] = byte(uint8(44)); return index; } // Convert integer to string in decimal form and write it into the buffer, and return the buffer index function writeUInt(uint256 iv, bytes memory buf, uint256 index) pure public returns (uint256) { uint256 i = index; do { buf[index++] = byte(uint8(iv % 10 +48)); iv /= 10; } while (iv > 0); for (uint256 j = index; j > i; ++i) { byte t = buf[i]; buf[i] = buf[--j]; buf[j] = t; } return index; } // Convert the address to a hexadecimal string and write it into the buffer, and return the buffer index function writeAddress(address addr, bytes memory buf, uint256 index) pure private returns (uint256) { uint256 iv = uint256(addr); uint256 i = index + 40; do { uint256 w = iv % 16; if(w < 10) { buf[index++] = byte(uint8(w +48)); } else { buf[index++] = byte(uint8(w +87)); } iv /= 16; } while (index < i); i -= 40; for (uint256 j = index; j > i; ++i) { byte t = buf[i]; buf[i] = buf[--j]; buf[j] = t; } return index; } // Vote administrator only modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender), "No authority"); _; } } /** * @title Price contract * @dev Price check and call */ contract Nest_3_OfferPrice{ using SafeMath for uint256; using address_make_payable for address; using SafeERC20 for ERC20; Nest_3_VoteFactory _voteFactory; // Voting contract ERC20 _nestToken; // NestToken Nest_NToken_TokenMapping _tokenMapping; // NToken mapping Nest_3_OfferMain _offerMain; // Offering main contract Nest_3_Abonus _abonus; // Bonus pool address _nTokeOfferMain; // NToken offering main contract address _destructionAddress; // Destruction contract address address _nTokenAuction; // NToken auction contract address struct PriceInfo { // Block price uint256 ethAmount; // ETH amount uint256 erc20Amount; // Erc20 amount uint256 frontBlock; // Last effective block address offerOwner; // Offering address } struct TokenInfo { // Token offer information mapping(uint256 => PriceInfo) priceInfoList; // Block price list, block number => block price uint256 latestOffer; // Latest effective block } uint256 destructionAmount = 0 ether; // Amount of NEST to destroy to call prices uint256 effectTime = 0 days; // Waiting time to start calling prices mapping(address => TokenInfo) _tokenInfo; // Token offer information mapping(address => bool) _blocklist; // Block list mapping(address => uint256) _addressEffect; // Effective time of address to call prices mapping(address => bool) _offerMainMapping; // Offering contract mapping uint256 _priceCost = 0.01 ether; // Call price fee // Real-time price token, ETH amount, erc20 amount event NowTokenPrice(address a, uint256 b, uint256 c); /** * @dev Initialization method * @param voteFactory Voting contract address */ constructor (address voteFactory) public { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerMain = Nest_3_OfferMain(address(voteFactoryMap.checkAddress("nest.v3.offerMain"))); _nTokeOfferMain = address(voteFactoryMap.checkAddress("nest.nToken.offerMain")); _abonus = Nest_3_Abonus(address(voteFactoryMap.checkAddress("nest.v3.abonus"))); _destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction")); _nestToken = ERC20(address(voteFactoryMap.checkAddress("nest"))); _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping"))); _nTokenAuction = address(voteFactoryMap.checkAddress("nest.nToken.tokenAuction")); _offerMainMapping[address(_offerMain)] = true; _offerMainMapping[address(_nTokeOfferMain)] = true; } /** * @dev Modify voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerMain = Nest_3_OfferMain(address(voteFactoryMap.checkAddress("nest.v3.offerMain"))); _nTokeOfferMain = address(voteFactoryMap.checkAddress("nest.nToken.offerMain")); _abonus = Nest_3_Abonus(address(voteFactoryMap.checkAddress("nest.v3.abonus"))); _destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction")); _nestToken = ERC20(address(voteFactoryMap.checkAddress("nest"))); _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping"))); _nTokenAuction = address(voteFactoryMap.checkAddress("nest.nToken.tokenAuction")); _offerMainMapping[address(_offerMain)] = true; _offerMainMapping[address(_nTokeOfferMain)] = true; } /** * @dev Initialize token price charge parameters * @param tokenAddress Token address */ function addPriceCost(address tokenAddress) public { } /** * @dev Add price * @param ethAmount ETH amount * @param tokenAmount Erc20 amount * @param endBlock Effective price block * @param tokenAddress Erc20 address * @param offerOwner Offering address */ function addPrice(uint256 ethAmount, uint256 tokenAmount, uint256 endBlock, address tokenAddress, address offerOwner) public onlyOfferMain{ // Add effective block price information TokenInfo storage tokenInfo = _tokenInfo[tokenAddress]; PriceInfo storage priceInfo = tokenInfo.priceInfoList[endBlock]; priceInfo.ethAmount = priceInfo.ethAmount.add(ethAmount); priceInfo.erc20Amount = priceInfo.erc20Amount.add(tokenAmount); if (endBlock != tokenInfo.latestOffer) { // If different block offer priceInfo.frontBlock = tokenInfo.latestOffer; tokenInfo.latestOffer = endBlock; } } /** * @dev Price modification in taker orders * @param ethAmount ETH amount * @param tokenAmount Erc20 amount * @param tokenAddress Token address * @param endBlock Block of effective price */ function changePrice(uint256 ethAmount, uint256 tokenAmount, address tokenAddress, uint256 endBlock) public onlyOfferMain { TokenInfo storage tokenInfo = _tokenInfo[tokenAddress]; PriceInfo storage priceInfo = tokenInfo.priceInfoList[endBlock]; priceInfo.ethAmount = priceInfo.ethAmount.sub(ethAmount); priceInfo.erc20Amount = priceInfo.erc20Amount.sub(tokenAmount); } /** * @dev Update and check the latest price * @param tokenAddress Token address * @return ethAmount ETH amount * @return erc20Amount Erc20 amount * @return blockNum Price block */ function updateAndCheckPriceNow(address tokenAddress) public payable returns(uint256 ethAmount, uint256 erc20Amount, uint256 blockNum) { require(checkUseNestPrice(address(msg.sender))); mapping(uint256 => PriceInfo) storage priceInfoList = _tokenInfo[tokenAddress].priceInfoList; uint256 checkBlock = _tokenInfo[tokenAddress].latestOffer; while(checkBlock > 0 && (checkBlock >= block.number || priceInfoList[checkBlock].ethAmount == 0)) { checkBlock = priceInfoList[checkBlock].frontBlock; } require(checkBlock != 0); PriceInfo memory priceInfo = priceInfoList[checkBlock]; address nToken = _tokenMapping.checkTokenMapping(tokenAddress); if (nToken == address(0x0)) { _abonus.switchToEth.value(_priceCost)(address(_nestToken)); } else { _abonus.switchToEth.value(_priceCost)(address(nToken)); } if (msg.value > _priceCost) { repayEth(address(msg.sender), msg.value.sub(_priceCost)); } emit NowTokenPrice(tokenAddress,priceInfo.ethAmount, priceInfo.erc20Amount); return (priceInfo.ethAmount,priceInfo.erc20Amount, checkBlock); } /** * @dev Update and check the latest price-internal use * @param tokenAddress Token address * @return ethAmount ETH amount * @return erc20Amount Erc20 amount */ function updateAndCheckPricePrivate(address tokenAddress) public view onlyOfferMain returns(uint256 ethAmount, uint256 erc20Amount) { mapping(uint256 => PriceInfo) storage priceInfoList = _tokenInfo[tokenAddress].priceInfoList; uint256 checkBlock = _tokenInfo[tokenAddress].latestOffer; while(checkBlock > 0 && (checkBlock >= block.number || priceInfoList[checkBlock].ethAmount == 0)) { checkBlock = priceInfoList[checkBlock].frontBlock; } if (checkBlock == 0) { return (0,0); } PriceInfo memory priceInfo = priceInfoList[checkBlock]; return (priceInfo.ethAmount,priceInfo.erc20Amount); } /** * @dev Update and check the effective price list * @param tokenAddress Token address * @param num Number of prices to check * @return uint256[] price list */ function updateAndCheckPriceList(address tokenAddress, uint256 num) public payable returns (uint256[] memory) { require(checkUseNestPrice(address(msg.sender))); mapping(uint256 => PriceInfo) storage priceInfoList = _tokenInfo[tokenAddress].priceInfoList; // Extract data uint256 length = num.mul(3); uint256 index = 0; uint256[] memory data = new uint256[](length); uint256 checkBlock = _tokenInfo[tokenAddress].latestOffer; while(index < length && checkBlock > 0){ if (checkBlock < block.number && priceInfoList[checkBlock].ethAmount != 0) { // Add return data data[index++] = priceInfoList[checkBlock].ethAmount; data[index++] = priceInfoList[checkBlock].erc20Amount; data[index++] = checkBlock; } checkBlock = priceInfoList[checkBlock].frontBlock; } require(length == data.length); // Allocation address nToken = _tokenMapping.checkTokenMapping(tokenAddress); if (nToken == address(0x0)) { _abonus.switchToEth.value(_priceCost)(address(_nestToken)); } else { _abonus.switchToEth.value(_priceCost)(address(nToken)); } if (msg.value > _priceCost) { repayEth(address(msg.sender), msg.value.sub(_priceCost)); } return data; } // Activate the price checking function function activation() public { _nestToken.safeTransferFrom(address(msg.sender), _destructionAddress, destructionAmount); _addressEffect[address(msg.sender)] = now.add(effectTime); } // Transfer ETH function repayEth(address accountAddress, uint256 asset) private { address payable addr = accountAddress.make_payable(); addr.transfer(asset); } // Check block price - user account only function checkPriceForBlock(address tokenAddress, uint256 blockNum) public view returns (uint256 ethAmount, uint256 erc20Amount) { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); TokenInfo storage tokenInfo = _tokenInfo[tokenAddress]; return (tokenInfo.priceInfoList[blockNum].ethAmount, tokenInfo.priceInfoList[blockNum].erc20Amount); } // Check real-time price - user account only function checkPriceNow(address tokenAddress) public view returns (uint256 ethAmount, uint256 erc20Amount, uint256 blockNum) { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); mapping(uint256 => PriceInfo) storage priceInfoList = _tokenInfo[tokenAddress].priceInfoList; uint256 checkBlock = _tokenInfo[tokenAddress].latestOffer; while(checkBlock > 0 && (checkBlock >= block.number || priceInfoList[checkBlock].ethAmount == 0)) { checkBlock = priceInfoList[checkBlock].frontBlock; } if (checkBlock == 0) { return (0,0,0); } PriceInfo storage priceInfo = priceInfoList[checkBlock]; return (priceInfo.ethAmount,priceInfo.erc20Amount, checkBlock); } // Check whether the price-checking functions can be called function checkUseNestPrice(address target) public view returns (bool) { if (!_blocklist[target] && _addressEffect[target] < now && _addressEffect[target] != 0) { return true; } else { return false; } } // Check whether the address is in the blocklist function checkBlocklist(address add) public view returns(bool) { return _blocklist[add]; } // Check the amount of NEST to destroy to call prices function checkDestructionAmount() public view returns(uint256) { return destructionAmount; } // Check the waiting time to start calling prices function checkEffectTime() public view returns (uint256) { return effectTime; } // Check call price fee function checkPriceCost() public view returns (uint256) { return _priceCost; } // Modify the blocklist function changeBlocklist(address add, bool isBlock) public onlyOwner { _blocklist[add] = isBlock; } // Amount of NEST to destroy to call price-checking functions function changeDestructionAmount(uint256 amount) public onlyOwner { destructionAmount = amount; } // Modify the waiting time to start calling prices function changeEffectTime(uint256 num) public onlyOwner { effectTime = num; } // Modify call price fee function changePriceCost(uint256 num) public onlyOwner { _priceCost = num; } // Offering contract only modifier onlyOfferMain(){ require(_offerMainMapping[address(msg.sender)], "No authority"); _; } // Vote administrators only modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender), "No authority"); _; } } /** * @title NEST and NToken lock-up contract * @dev NEST and NToken deposit and withdrawal */ contract Nest_3_TokenSave { using SafeMath for uint256; Nest_3_VoteFactory _voteFactory; // Voting contract mapping(address => mapping(address => uint256)) _baseMapping; // Ledger token=>user=>amount /** * @dev initialization method * @param voteFactory Voting contract address */ constructor(address voteFactory) public { _voteFactory = Nest_3_VoteFactory(voteFactory); } /** * @dev Reset voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner { _voteFactory = Nest_3_VoteFactory(voteFactory); } /** * @dev Withdrawing * @param num Withdrawing amount * @param token Lock-up token address * @param target Transfer target */ function takeOut(uint256 num, address token, address target) public onlyContract { require(num <= _baseMapping[token][address(target)], "Insufficient storage balance"); _baseMapping[token][address(target)] = _baseMapping[token][address(target)].sub(num); ERC20(token).transfer(address(target), num); } /** * @dev Depositing * @param num Depositing amount * @param token Lock-up token address * @param target Depositing target */ function depositIn(uint256 num, address token, address target) public onlyContract { require(ERC20(token).transferFrom(address(target),address(this),num), "Authorization transfer failed"); _baseMapping[token][address(target)] = _baseMapping[token][address(target)].add(num); } /** * @dev Check the amount * @param sender Check address * @param token Lock-up token address * @return uint256 Check address corresponding lock-up limit */ function checkAmount(address sender, address token) public view returns(uint256) { return _baseMapping[token][address(sender)]; } // Administrators only modifier onlyOwner(){ require(_voteFactory.checkOwners(address(msg.sender)), "No authority"); _; } // Only for bonus logic contract modifier onlyContract(){ require(_voteFactory.checkAddress("nest.v3.tokenAbonus") == address(msg.sender), "No authority"); _; } } /** * @title Dividend logic * @dev Some operations about dividend,logic and asset separation */ contract Nest_3_TokenAbonus { using address_make_payable for address; using SafeMath for uint256; ERC20 _nestContract; Nest_3_TokenSave _tokenSave; // Lock-up contract Nest_3_Abonus _abonusContract; // ETH bonus pool Nest_3_VoteFactory _voteFactory; // Voting contract Nest_3_Leveling _nestLeveling; // Leveling contract address _destructionAddress; // Destroy contract address uint256 _timeLimit = 168 hours; // Bonus period uint256 _nextTime = 1596168000; // Next bonus time uint256 _getAbonusTimeLimit = 60 hours; // During of triggering calculation of bonus uint256 _times = 0; // Bonus ledger uint256 _expectedIncrement = 3; // Expected bonus increment ratio uint256 _expectedSpanForNest = 100000000 ether; // NEST expected bonus increment threshold uint256 _expectedSpanForNToken = 1000000 ether; // NToken expected bonus increment threshold uint256 _expectedMinimum = 100 ether; // Expected minimum bonus uint256 _savingLevelOne = 10; // Saving threshold level 1 uint256 _savingLevelTwo = 20; // Saving threshold level 2 uint256 _savingLevelTwoSub = 100 ether; // Function parameters of savings threshold level 2 uint256 _savingLevelThree = 30; // Function parameters of savings threshold level 3 uint256 _savingLevelThreeSub = 600 ether; // Function parameters of savings threshold level 3 mapping(address => uint256) _abonusMapping; // Bonus pool snapshot - token address (NEST or NToken) => number of ETH in the bonus pool mapping(address => uint256) _tokenAllValueMapping; // Number of tokens (circulation) - token address (NEST or NToken) ) => total circulation mapping(address => mapping(uint256 => uint256)) _tokenAllValueHistory; // NEST or NToken circulation snapshot - token address (NEST or NToken) => number of periods => total circulation mapping(address => mapping(uint256 => mapping(address => uint256))) _tokenSelfHistory; // Personal lockup - NEST or NToken snapshot token address (NEST or NToken) => period => user address => total circulation mapping(address => mapping(uint256 => bool)) _snapshot; // Whether snapshot - token address (NEST or NToken) => number of periods => whether to take a snapshot mapping(uint256 => mapping(address => mapping(address => bool))) _getMapping; // Receiving records - period => token address (NEST or NToken) => user address => whether received // Log token address, amount event GetTokenLog(address tokenAddress, uint256 tokenAmount); /** * @dev Initialization method * @param voteFactory Voting contract address */ constructor (address voteFactory) public { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _nestContract = ERC20(address(voteFactoryMap.checkAddress("nest"))); _tokenSave = Nest_3_TokenSave(address(voteFactoryMap.checkAddress("nest.v3.tokenSave"))); address payable addr = address(voteFactoryMap.checkAddress("nest.v3.abonus")).make_payable(); _abonusContract = Nest_3_Abonus(addr); address payable levelingAddr = address(voteFactoryMap.checkAddress("nest.v3.leveling")).make_payable(); _nestLeveling = Nest_3_Leveling(levelingAddr); _destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction")); } /** * @dev Modify voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _nestContract = ERC20(address(voteFactoryMap.checkAddress("nest"))); _tokenSave = Nest_3_TokenSave(address(voteFactoryMap.checkAddress("nest.v3.tokenSave"))); address payable addr = address(voteFactoryMap.checkAddress("nest.v3.abonus")).make_payable(); _abonusContract = Nest_3_Abonus(addr); address payable levelingAddr = address(voteFactoryMap.checkAddress("nest.v3.leveling")).make_payable(); _nestLeveling = Nest_3_Leveling(levelingAddr); _destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction")); } /** * @dev Deposit * @param amount Deposited amount * @param token Locked token address */ function depositIn(uint256 amount, address token) public { uint256 nowTime = now; uint256 nextTime = _nextTime; uint256 timeLimit = _timeLimit; if (nowTime < nextTime) { // Bonus triggered require(!(nowTime >= nextTime.sub(timeLimit) && nowTime <= nextTime.sub(timeLimit).add(_getAbonusTimeLimit))); } else { // Bonus not triggered uint256 times = (nowTime.sub(_nextTime)).div(_timeLimit); // Calculate the time when bonus should be started uint256 startTime = _nextTime.add((times).mul(_timeLimit)); // Calculate the time when bonus should be stopped uint256 endTime = startTime.add(_getAbonusTimeLimit); require(!(nowTime >= startTime && nowTime <= endTime)); } _tokenSave.depositIn(amount, token, address(msg.sender)); } /** * @dev Withdrawing * @param amount Withdrawing amount * @param token Token address */ function takeOut(uint256 amount, address token) public { require(amount > 0, "Parameter needs to be greater than 0"); require(amount <= _tokenSave.checkAmount(address(msg.sender), token), "Insufficient storage balance"); if (token == address(_nestContract)) { require(!_voteFactory.checkVoteNow(address(tx.origin)), "Voting"); } _tokenSave.takeOut(amount, token, address(msg.sender)); } /** * @dev Receiving * @param token Receiving token address */ function getAbonus(address token) public { uint256 tokenAmount = _tokenSave.checkAmount(address(msg.sender), token); require(tokenAmount > 0, "Insufficient storage balance"); reloadTime(); reloadToken(token); uint256 nowTime = now; require(nowTime >= _nextTime.sub(_timeLimit) && nowTime <= _nextTime.sub(_timeLimit).add(_getAbonusTimeLimit), "Not time to draw"); require(!_getMapping[_times.sub(1)][token][address(msg.sender)], "Have received"); _tokenSelfHistory[token][_times.sub(1)][address(msg.sender)] = tokenAmount; require(_tokenAllValueMapping[token] > 0, "Total flux error"); uint256 selfNum = tokenAmount.mul(_abonusMapping[token]).div(_tokenAllValueMapping[token]); require(selfNum > 0, "No limit available"); _getMapping[_times.sub(1)][token][address(msg.sender)] = true; _abonusContract.getETH(selfNum, token,address(msg.sender)); emit GetTokenLog(token, selfNum); } /** * @dev Update bonus time and stage ledger */ function reloadTime() private { uint256 nowTime = now; // The current time must exceed the bonus time if (nowTime >= _nextTime) { uint256 time = (nowTime.sub(_nextTime)).div(_timeLimit); uint256 startTime = _nextTime.add((time).mul(_timeLimit)); uint256 endTime = startTime.add(_getAbonusTimeLimit); if (nowTime >= startTime && nowTime <= endTime) { _nextTime = getNextTime(); _times = _times.add(1); } } } /** * @dev Snapshot of the amount of tokens * @param token Receiving token address */ function reloadToken(address token) private { if (!_snapshot[token][_times.sub(1)]) { levelingResult(token); _abonusMapping[token] = _abonusContract.getETHNum(token); _tokenAllValueMapping[token] = allValue(token); _tokenAllValueHistory[token][_times.sub(1)] = allValue(token); _snapshot[token][_times.sub(1)] = true; } } /** * @dev Leveling settlement * @param token Receiving token address */ function levelingResult(address token) private { uint256 steps; if (token == address(_nestContract)) { steps = allValue(token).div(_expectedSpanForNest); } else { steps = allValue(token).div(_expectedSpanForNToken); } uint256 minimumAbonus = _expectedMinimum; for (uint256 i = 0; i < steps; i++) { minimumAbonus = minimumAbonus.add(minimumAbonus.mul(_expectedIncrement).div(100)); } uint256 thisAbonus = _abonusContract.getETHNum(token); if (thisAbonus > minimumAbonus) { uint256 levelAmount = 0; if (thisAbonus > 5000 ether) { levelAmount = thisAbonus.mul(_savingLevelThree).div(100).sub(_savingLevelThreeSub); } else if (thisAbonus > 1000 ether) { levelAmount = thisAbonus.mul(_savingLevelTwo).div(100).sub(_savingLevelTwoSub); } else { levelAmount = thisAbonus.mul(_savingLevelOne).div(100); } if (thisAbonus.sub(levelAmount) < minimumAbonus) { _abonusContract.getETH(thisAbonus.sub(minimumAbonus), token, address(this)); _nestLeveling.switchToEth.value(thisAbonus.sub(minimumAbonus))(token); } else { _abonusContract.getETH(levelAmount, token, address(this)); _nestLeveling.switchToEth.value(levelAmount)(token); } } else { uint256 ethValue = _nestLeveling.tranEth(minimumAbonus.sub(thisAbonus), token, address(this)); _abonusContract.switchToEth.value(ethValue)(token); } } // Next bonus time, current bonus deadline, ETH number, NEST number, NEST participating in bonus, bonus to receive, approved amount, balance, whether bonus can be paid function getInfo(address token) public view returns (uint256 nextTime, uint256 getAbonusTime, uint256 ethNum, uint256 tokenValue, uint256 myJoinToken, uint256 getEth, uint256 allowNum, uint256 leftNum, bool allowAbonus) { uint256 nowTime = now; if (nowTime >= _nextTime.sub(_timeLimit) && nowTime <= _nextTime.sub(_timeLimit).add(_getAbonusTimeLimit) && _times > 0 && _snapshot[token][_times.sub(1)]) { // Bonus have been triggered, and during the time of this bonus, display snapshot data allowAbonus = _getMapping[_times.sub(1)][token][address(msg.sender)]; ethNum = _abonusMapping[token]; tokenValue = _tokenAllValueMapping[token]; } else { // Display real-time data ethNum = _abonusContract.getETHNum(token); tokenValue = allValue(token); allowAbonus = _getMapping[_times][token][address(msg.sender)]; } myJoinToken = _tokenSave.checkAmount(address(msg.sender), token); if (allowAbonus == true) { getEth = 0; } else { getEth = myJoinToken.mul(ethNum).div(tokenValue); } nextTime = getNextTime(); getAbonusTime = nextTime.sub(_timeLimit).add(_getAbonusTimeLimit); allowNum = ERC20(token).allowance(address(msg.sender), address(_tokenSave)); leftNum = ERC20(token).balanceOf(address(msg.sender)); } /** * @dev View next bonus time * @return Next bonus time */ function getNextTime() public view returns (uint256) { uint256 nowTime = now; if (_nextTime > nowTime) { return _nextTime; } else { uint256 time = (nowTime.sub(_nextTime)).div(_timeLimit); return _nextTime.add(_timeLimit.mul(time.add(1))); } } /** * @dev View total circulation * @return Total circulation */ function allValue(address token) public view returns (uint256) { if (token == address(_nestContract)) { uint256 all = 10000000000 ether; uint256 leftNum = all.sub(_nestContract.balanceOf(address(_voteFactory.checkAddress("nest.v3.miningSave")))).sub(_nestContract.balanceOf(address(_destructionAddress))); return leftNum; } else { return ERC20(token).totalSupply(); } } /** * @dev View bonus period * @return Bonus period */ function checkTimeLimit() public view returns (uint256) { return _timeLimit; } /** * @dev View duration of triggering calculation of bonus * @return Bonus period */ function checkGetAbonusTimeLimit() public view returns (uint256) { return _getAbonusTimeLimit; } /** * @dev View current lowest expected bonus * @return Current lowest expected bonus */ function checkMinimumAbonus(address token) public view returns (uint256) { uint256 miningAmount; if (token == address(_nestContract)) { miningAmount = allValue(token).div(_expectedSpanForNest); } else { miningAmount = allValue(token).div(_expectedSpanForNToken); } uint256 minimumAbonus = _expectedMinimum; for (uint256 i = 0; i < miningAmount; i++) { minimumAbonus = minimumAbonus.add(minimumAbonus.mul(_expectedIncrement).div(100)); } return minimumAbonus; } /** * @dev Check whether the bonus token is snapshoted * @param token Token address * @return Whether snapshoted */ function checkSnapshot(address token) public view returns (bool) { return _snapshot[token][_times.sub(1)]; } /** * @dev Check the expected bonus incremental ratio * @return Expected bonus increment ratio */ function checkeExpectedIncrement() public view returns (uint256) { return _expectedIncrement; } /** * @dev View expected minimum bonus * @return Expected minimum bonus */ function checkExpectedMinimum() public view returns (uint256) { return _expectedMinimum; } /** * @dev View savings threshold * @return Save threshold */ function checkSavingLevelOne() public view returns (uint256) { return _savingLevelOne; } function checkSavingLevelTwo() public view returns (uint256) { return _savingLevelTwo; } function checkSavingLevelThree() public view returns (uint256) { return _savingLevelThree; } /** * @dev View NEST liquidity snapshot * @param token Locked token address * @param times Bonus snapshot period */ function checkTokenAllValueHistory(address token, uint256 times) public view returns (uint256) { return _tokenAllValueHistory[token][times]; } /** * @dev View personal lock-up NEST snapshot * @param times Bonus snapshot period * @param user User address * @return The number of personal locked NEST snapshots */ function checkTokenSelfHistory(address token, uint256 times, address user) public view returns (uint256) { return _tokenSelfHistory[token][times][user]; } // View the period number of bonus function checkTimes() public view returns (uint256) { return _times; } // NEST expected bonus increment threshold function checkExpectedSpanForNest() public view returns (uint256) { return _expectedSpanForNest; } // NToken expected bonus increment threshold function checkExpectedSpanForNToken() public view returns (uint256) { return _expectedSpanForNToken; } // View the function parameters of savings threshold level 3 function checkSavingLevelTwoSub() public view returns (uint256) { return _savingLevelTwoSub; } // View the function parameters of savings threshold level 3 function checkSavingLevelThreeSub() public view returns (uint256) { return _savingLevelThreeSub; } /** * @dev Update bonus period * @param hour Bonus period (hours) */ function changeTimeLimit(uint256 hour) public onlyOwner { require(hour > 0, "Parameter needs to be greater than 0"); _timeLimit = hour.mul(1 hours); } /** * @dev Update collection period * @param hour Collection period (hours) */ function changeGetAbonusTimeLimit(uint256 hour) public onlyOwner { require(hour > 0, "Parameter needs to be greater than 0"); _getAbonusTimeLimit = hour; } /** * @dev Update expected bonus increment ratio * @param num Expected bonus increment ratio */ function changeExpectedIncrement(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _expectedIncrement = num; } /** * @dev Update expected minimum bonus * @param num Expected minimum bonus */ function changeExpectedMinimum(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _expectedMinimum = num; } /** * @dev Update saving threshold * @param threshold Saving threshold */ function changeSavingLevelOne(uint256 threshold) public onlyOwner { _savingLevelOne = threshold; } function changeSavingLevelTwo(uint256 threshold) public onlyOwner { _savingLevelTwo = threshold; } function changeSavingLevelThree(uint256 threshold) public onlyOwner { _savingLevelThree = threshold; } /** * @dev Update the function parameters of savings threshold level 2 */ function changeSavingLevelTwoSub(uint256 num) public onlyOwner { _savingLevelTwoSub = num; } /** * @dev Update the function parameters of savings threshold level 3 */ function changeSavingLevelThreeSub(uint256 num) public onlyOwner { _savingLevelThreeSub = num; } /** * @dev Update NEST expected bonus incremental threshold * @param num Threshold */ function changeExpectedSpanForNest(uint256 num) public onlyOwner { _expectedSpanForNest = num; } /** * @dev Update NToken expected bonus incremental threshold * @param num Threshold */ function changeExpectedSpanForNToken(uint256 num) public onlyOwner { _expectedSpanForNToken = num; } receive() external payable { } // Administrator only modifier onlyOwner(){ require(_voteFactory.checkOwners(address(msg.sender)), "No authority"); _; } } /** * @title ETH bonus pool * @dev ETH collection and inquiry */ contract Nest_3_Abonus { using address_make_payable for address; using SafeMath for uint256; Nest_3_VoteFactory _voteFactory; // Voting contract address _nestAddress; // NEST contract address mapping (address => uint256) ethMapping; // ETH bonus ledger of corresponding tokens uint256 _mostDistribution = 40; // The highest allocation ratio of NEST bonus pool uint256 _leastDistribution = 20; // The lowest allocation ratio of NEST bonus pool uint256 _distributionTime = 1200000; // The decay time interval of NEST bonus pool allocation ratio uint256 _distributionSpan = 5; // The decay degree of NEST bonus pool allocation ratio /** * @dev Initialization method * @param voteFactory Voting contract address */ constructor(address voteFactory) public { _voteFactory = Nest_3_VoteFactory(voteFactory); _nestAddress = address(_voteFactory.checkAddress("nest")); } /** * @dev Reset voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner{ _voteFactory = Nest_3_VoteFactory(voteFactory); _nestAddress = address(_voteFactory.checkAddress("nest")); } /** * @dev Transfer in bonus * @param token Corresponding to lock-up Token */ function switchToEth(address token) public payable { ethMapping[token] = ethMapping[token].add(msg.value); } /** * @dev Transferin bonus - NToken offering fee * @param token Corresponding to lock-up NToken */ function switchToEthForNTokenOffer(address token) public payable { Nest_NToken nToken = Nest_NToken(token); (uint256 createBlock,) = nToken.checkBlockInfo(); uint256 subBlock = block.number.sub(createBlock); uint256 times = subBlock.div(_distributionTime); uint256 distributionValue = times.mul(_distributionSpan); uint256 distribution = _mostDistribution; if (_leastDistribution.add(distributionValue) > _mostDistribution) { distribution = _leastDistribution; } else { distribution = _mostDistribution.sub(distributionValue); } uint256 nestEth = msg.value.mul(distribution).div(100); ethMapping[_nestAddress] = ethMapping[_nestAddress].add(nestEth); ethMapping[token] = ethMapping[token].add(msg.value.sub(nestEth)); } /** * @dev Receive ETH * @param num Receive amount * @param token Correspond to locked Token * @param target Transfer target */ function getETH(uint256 num, address token, address target) public onlyContract { require(num <= ethMapping[token], "Insufficient storage balance"); ethMapping[token] = ethMapping[token].sub(num); address payable addr = target.make_payable(); addr.transfer(num); } /** * @dev Get bonus pool balance * @param token Corresponded locked Token * @return uint256 Bonus pool balance */ function getETHNum(address token) public view returns (uint256) { return ethMapping[token]; } // View NEST address function checkNestAddress() public view returns(address) { return _nestAddress; } // View the highest NEST bonus pool allocation ratio function checkMostDistribution() public view returns(uint256) { return _mostDistribution; } // View the lowest NEST bonus pool allocation ratio function checkLeastDistribution() public view returns(uint256) { return _leastDistribution; } // View the decay time interval of NEST bonus pool allocation ratio function checkDistributionTime() public view returns(uint256) { return _distributionTime; } // View the decay degree of NEST bonus pool allocation ratio function checkDistributionSpan() public view returns(uint256) { return _distributionSpan; } // Modify the highest NEST bonus pool allocation ratio function changeMostDistribution(uint256 num) public onlyOwner { _mostDistribution = num; } // Modify the lowest NEST bonus pool allocation ratio function changeLeastDistribution(uint256 num) public onlyOwner { _leastDistribution = num; } // Modify the decay time interval of NEST bonus pool allocation ratio function changeDistributionTime(uint256 num) public onlyOwner { _distributionTime = num; } // Modify the decay degree of NEST bonus pool allocation ratio function changeDistributionSpan(uint256 num) public onlyOwner { _distributionSpan = num; } // Withdraw ETH function turnOutAllEth(uint256 amount, address target) public onlyOwner { address payable addr = target.make_payable(); addr.transfer(amount); } // Only bonus logic contract modifier onlyContract(){ require(_voteFactory.checkAddress("nest.v3.tokenAbonus") == address(msg.sender), "No authority"); _; } // Administrator only modifier onlyOwner(){ require(_voteFactory.checkOwners(address(msg.sender)), "No authority"); _; } } /** * @title Leveling contract * @dev ETH transfer in and transfer out */ contract Nest_3_Leveling { using address_make_payable for address; using SafeMath for uint256; Nest_3_VoteFactory _voteFactory; // Vote contract mapping (address => uint256) ethMapping; // Corresponded ETH leveling ledger of token /** * @dev Initialization method * @param voteFactory Voting contract address */ constructor (address voteFactory) public { _voteFactory = Nest_3_VoteFactory(voteFactory); } /** * @dev Modifying voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner { _voteFactory = Nest_3_VoteFactory(voteFactory); } /** * @dev Transfer out leveling * @param amount Transfer-out amount * @param token Corresponding lock-up token * @param target Transfer-out target */ function tranEth(uint256 amount, address token, address target) public returns (uint256) { require(address(msg.sender) == address(_voteFactory.checkAddress("nest.v3.tokenAbonus")), "No authority"); uint256 tranAmount = amount; if (tranAmount > ethMapping[token]) { tranAmount = ethMapping[token]; } ethMapping[token] = ethMapping[token].sub(tranAmount); address payable addr = target.make_payable(); addr.transfer(tranAmount); return tranAmount; } /** * @dev Transfer in leveling * @param token Corresponded locked token */ function switchToEth(address token) public payable { ethMapping[token] = ethMapping[token].add(msg.value); } // Check the leveled amount corresponding to the token function checkEthMapping(address token) public view returns (uint256) { return ethMapping[token]; } // Withdraw ETH function turnOutAllEth(uint256 amount, address target) public onlyOwner { address payable addr = target.make_payable(); addr.transfer(amount); } // Administrator only modifier onlyOwner(){ require(_voteFactory.checkOwners(address(msg.sender)), "No authority"); _; } } /** * @title Offering contract * @dev Offering logic and mining logic */ contract Nest_NToken_OfferMain { using SafeMath for uint256; using address_make_payable for address; using SafeERC20 for ERC20; // Offering data structure struct Nest_NToken_OfferPriceData { // The unique identifier is determined by the position of the offer in the array, and is converted to each other through a fixed algorithm (toindex(), toaddress()) address owner; // Offering owner bool deviate; // Whether it deviates address tokenAddress; // The erc20 contract address of the target offer token uint256 ethAmount; // The ETH amount in the offer list uint256 tokenAmount; // The token amount in the offer list uint256 dealEthAmount; // The remaining number of tradable ETH uint256 dealTokenAmount; // The remaining number of tradable tokens uint256 blockNum; // The block number where the offer is located uint256 serviceCharge; // The fee for mining // Determine whether the asset has been collected by judging that ethamount, tokenamount, and servicecharge are all 0 } Nest_NToken_OfferPriceData [] _prices; // Array used to save offers Nest_3_VoteFactory _voteFactory; // Voting contract Nest_3_OfferPrice _offerPrice; // Price contract Nest_NToken_TokenMapping _tokenMapping; // NToken mapping contract ERC20 _nestToken; // nestToken Nest_3_Abonus _abonus; // Bonus pool uint256 _miningETH = 10; // Offering mining fee ratio uint256 _tranEth = 1; // Taker fee ratio uint256 _tranAddition = 2; // Additional transaction multiple uint256 _leastEth = 10 ether; // Minimum offer of ETH uint256 _offerSpan = 10 ether; // ETH Offering span uint256 _deviate = 10; // Price deviation - 10% uint256 _deviationFromScale = 10; // Deviation from asset scale uint256 _ownerMining = 5; // Creator ratio uint256 _afterMiningAmount = 0.4 ether; // Stable period mining amount uint32 _blockLimit = 25; // Block interval upper limit uint256 _blockAttenuation = 2400000; // Block decay interval mapping(uint256 => mapping(address => uint256)) _blockOfferAmount; // Block offer times - block number=>token address=>offer fee mapping(uint256 => mapping(address => uint256)) _blockMining; // Offering block mining amount - block number=>token address=>mining amount uint256[10] _attenuationAmount; // Mining decay list // Log token contract address event OfferTokenContractAddress(address contractAddress); // Log offering contract, token address, amount of ETH, amount of ERC20, delayed block, mining fee event OfferContractAddress(address contractAddress, address tokenAddress, uint256 ethAmount, uint256 erc20Amount, uint256 continued,uint256 mining); // Log transaction sender, transaction token, transaction amount, purchase token address, purchase token amount, transaction offering contract address, transaction user address event OfferTran(address tranSender, address tranToken, uint256 tranAmount,address otherToken, uint256 otherAmount, address tradedContract, address tradedOwner); // Log current block, current block mined amount, token address event OreDrawingLog(uint256 nowBlock, uint256 blockAmount, address tokenAddress); // Log offering block, token address, token offered times event MiningLog(uint256 blockNum, address tokenAddress, uint256 offerTimes); /** * Initialization method * @param voteFactory Voting contract address **/ constructor (address voteFactory) public { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice"))); _nestToken = ERC20(voteFactoryMap.checkAddress("nest")); _abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus")); _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping"))); uint256 blockAmount = 4 ether; for (uint256 i = 0; i < 10; i ++) { _attenuationAmount[i] = blockAmount; blockAmount = blockAmount.mul(8).div(10); } } /** * Reset voting contract method * @param voteFactory Voting contract address **/ function changeMapping(address voteFactory) public onlyOwner { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice"))); _nestToken = ERC20(voteFactoryMap.checkAddress("nest")); _abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus")); _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping"))); } /** * Offering method * @param ethAmount ETH amount * @param erc20Amount Erc20 token amount * @param erc20Address Erc20 token address **/ function offer(uint256 ethAmount, uint256 erc20Amount, address erc20Address) public payable { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); address nTokenAddress = _tokenMapping.checkTokenMapping(erc20Address); require(nTokenAddress != address(0x0)); // Judge whether the price deviates uint256 ethMining; bool isDeviate = comparativePrice(ethAmount,erc20Amount,erc20Address); if (isDeviate) { require(ethAmount >= _leastEth.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of the minimum scale"); ethMining = _leastEth.mul(_miningETH).div(1000); } else { ethMining = ethAmount.mul(_miningETH).div(1000); } require(msg.value >= ethAmount.add(ethMining), "msg.value needs to be equal to the quoted eth quantity plus Mining handling fee"); uint256 subValue = msg.value.sub(ethAmount.add(ethMining)); if (subValue > 0) { repayEth(address(msg.sender), subValue); } // Create an offer createOffer(ethAmount, erc20Amount, erc20Address,isDeviate, ethMining); // Transfer in offer asset - erc20 to this contract ERC20(erc20Address).safeTransferFrom(address(msg.sender), address(this), erc20Amount); _abonus.switchToEthForNTokenOffer.value(ethMining)(nTokenAddress); // Mining if (_blockOfferAmount[block.number][erc20Address] == 0) { uint256 miningAmount = oreDrawing(nTokenAddress); Nest_NToken nToken = Nest_NToken(nTokenAddress); nToken.transfer(nToken.checkBidder(), miningAmount.mul(_ownerMining).div(100)); _blockMining[block.number][erc20Address] = miningAmount.sub(miningAmount.mul(_ownerMining).div(100)); } _blockOfferAmount[block.number][erc20Address] = _blockOfferAmount[block.number][erc20Address].add(ethMining); } /** * @dev Create offer * @param ethAmount Offering ETH amount * @param erc20Amount Offering erc20 amount * @param erc20Address Offering erc20 address **/ function createOffer(uint256 ethAmount, uint256 erc20Amount, address erc20Address, bool isDeviate, uint256 mining) private { // Check offer conditions require(ethAmount >= _leastEth, "Eth scale is smaller than the minimum scale"); require(ethAmount % _offerSpan == 0, "Non compliant asset span"); require(erc20Amount % (ethAmount.div(_offerSpan)) == 0, "Asset quantity is not divided"); require(erc20Amount > 0); // Create offering contract emit OfferContractAddress(toAddress(_prices.length), address(erc20Address), ethAmount, erc20Amount,_blockLimit,mining); _prices.push(Nest_NToken_OfferPriceData( msg.sender, isDeviate, erc20Address, ethAmount, erc20Amount, ethAmount, erc20Amount, block.number, mining )); // Record price _offerPrice.addPrice(ethAmount, erc20Amount, block.number.add(_blockLimit), erc20Address, address(msg.sender)); } // Convert offer address into index in offer array function toIndex(address contractAddress) public pure returns(uint256) { return uint256(contractAddress); } // Convert index in offer array into offer address function toAddress(uint256 index) public pure returns(address) { return address(index); } /** * Withdraw offer assets * @param contractAddress Offer address **/ function turnOut(address contractAddress) public { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); uint256 index = toIndex(contractAddress); Nest_NToken_OfferPriceData storage offerPriceData = _prices[index]; require(checkContractState(offerPriceData.blockNum) == 1, "Offer status error"); // Withdraw ETH if (offerPriceData.ethAmount > 0) { uint256 payEth = offerPriceData.ethAmount; offerPriceData.ethAmount = 0; repayEth(offerPriceData.owner, payEth); } // Withdraw erc20 if (offerPriceData.tokenAmount > 0) { uint256 payErc = offerPriceData.tokenAmount; offerPriceData.tokenAmount = 0; ERC20(address(offerPriceData.tokenAddress)).safeTransfer(address(offerPriceData.owner), payErc); } // Mining settlement if (offerPriceData.serviceCharge > 0) { mining(offerPriceData.blockNum, offerPriceData.tokenAddress, offerPriceData.serviceCharge, offerPriceData.owner); offerPriceData.serviceCharge = 0; } } /** * @dev Taker order - pay ETH and buy erc20 * @param ethAmount The amount of ETH of this offer * @param tokenAmount The amount of erc20 of this offer * @param contractAddress The target offer address * @param tranEthAmount The amount of ETH of taker order * @param tranTokenAmount The amount of erc20 of taker order * @param tranTokenAddress The erc20 address of taker order */ function sendEthBuyErc(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000); require(msg.value == ethAmount.add(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quotation eth quantity plus transaction eth plus"); require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span"); // Get the offer data structure uint256 index = toIndex(contractAddress); Nest_NToken_OfferPriceData memory offerPriceData = _prices[index]; // Check the price, compare the current offer to the last effective price bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress); bool isDeviate; if (offerPriceData.deviate == true) { isDeviate = true; } else { isDeviate = thisDeviate; } // Limit the taker order only be twice the amount of the offer to prevent large-amount attacks if (offerPriceData.deviate) { // The taker order deviates x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } else { if (isDeviate) { // If the taken offer is normal and the taker order deviates x10 require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale"); } else { // If the taken offer is normal and the taker order is normal x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } } // Check whether the conditions for taker order are satisfied require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error"); require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth"); require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token"); require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address"); require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount"); // Update the offer information offerPriceData.ethAmount = offerPriceData.ethAmount.add(tranEthAmount); offerPriceData.tokenAmount = offerPriceData.tokenAmount.sub(tranTokenAmount); offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount); offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount); _prices[index] = offerPriceData; // Create a new offer createOffer(ethAmount, tokenAmount, tranTokenAddress, isDeviate, 0); // Transfer in erc20 + offer asset to this contract if (tokenAmount > tranTokenAmount) { ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tokenAmount.sub(tranTokenAmount)); } else { ERC20(tranTokenAddress).safeTransfer(address(msg.sender), tranTokenAmount.sub(tokenAmount)); } // Modify price _offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit)); emit OfferTran(address(msg.sender), address(0x0), tranEthAmount, address(tranTokenAddress), tranTokenAmount, contractAddress, offerPriceData.owner); // Transfer fee if (serviceCharge > 0) { address nTokenAddress = _tokenMapping.checkTokenMapping(tranTokenAddress); _abonus.switchToEth.value(serviceCharge)(nTokenAddress); } } /** * @dev Taker order - pay erc20 and buy ETH * @param ethAmount The amount of ETH of this offer * @param tokenAmount The amount of erc20 of this offer * @param contractAddress The target offer address * @param tranEthAmount The amount of ETH of taker order * @param tranTokenAmount The amount of erc20 of taker order * @param tranTokenAddress The erc20 address of taker order */ function sendErcBuyEth(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000); require(msg.value == ethAmount.sub(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quoted eth quantity plus transaction handling fee"); require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span"); // Get the offer data structure uint256 index = toIndex(contractAddress); Nest_NToken_OfferPriceData memory offerPriceData = _prices[index]; // Check the price, compare the current offer to the last effective price bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress); bool isDeviate; if (offerPriceData.deviate == true) { isDeviate = true; } else { isDeviate = thisDeviate; } // Limit the taker order only be twice the amount of the offer to prevent large-amount attacks if (offerPriceData.deviate) { // The taker order deviates x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } else { if (isDeviate) { // If the taken offer is normal and the taker order deviates x10 require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale"); } else { // If the taken offer is normal and the taker order is normal x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } } // Check whether the conditions for taker order are satisfied require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error"); require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth"); require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token"); require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address"); require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount"); // Update the offer information offerPriceData.ethAmount = offerPriceData.ethAmount.sub(tranEthAmount); offerPriceData.tokenAmount = offerPriceData.tokenAmount.add(tranTokenAmount); offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount); offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount); _prices[index] = offerPriceData; // Create a new offer createOffer(ethAmount, tokenAmount, tranTokenAddress, isDeviate, 0); // Transfer in erc20 + offer asset to this contract ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tranTokenAmount.add(tokenAmount)); // Modify price _offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit)); emit OfferTran(address(msg.sender), address(tranTokenAddress), tranTokenAmount, address(0x0), tranEthAmount, contractAddress, offerPriceData.owner); // Transfer fee if (serviceCharge > 0) { address nTokenAddress = _tokenMapping.checkTokenMapping(tranTokenAddress); _abonus.switchToEth.value(serviceCharge)(nTokenAddress); } } /** * Offering mining * @param ntoken NToken address **/ function oreDrawing(address ntoken) private returns(uint256) { Nest_NToken miningToken = Nest_NToken(ntoken); (uint256 createBlock, uint256 recentlyUsedBlock) = miningToken.checkBlockInfo(); uint256 attenuationPointNow = block.number.sub(createBlock).div(_blockAttenuation); uint256 miningAmount = 0; uint256 attenuation; if (attenuationPointNow > 9) { attenuation = _afterMiningAmount; } else { attenuation = _attenuationAmount[attenuationPointNow]; } miningAmount = attenuation.mul(block.number.sub(recentlyUsedBlock)); miningToken.increaseTotal(miningAmount); emit OreDrawingLog(block.number, miningAmount, ntoken); return miningAmount; } /** * Retrieve mining * @param token Token address **/ function mining(uint256 blockNum, address token, uint256 serviceCharge, address owner) private returns(uint256) { // Block mining amount*offer fee/block offer fee uint256 miningAmount = _blockMining[blockNum][token].mul(serviceCharge).div(_blockOfferAmount[blockNum][token]); // Transfer NToken Nest_NToken nToken = Nest_NToken(address(_tokenMapping.checkTokenMapping(token))); require(nToken.transfer(address(owner), miningAmount), "Transfer failure"); emit MiningLog(blockNum, token,_blockOfferAmount[blockNum][token]); return miningAmount; } // Compare order prices function comparativePrice(uint256 myEthValue, uint256 myTokenValue, address token) private view returns(bool) { (uint256 frontEthValue, uint256 frontTokenValue) = _offerPrice.updateAndCheckPricePrivate(token); if (frontEthValue == 0 || frontTokenValue == 0) { return false; } uint256 maxTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).add(_deviate)).div(frontEthValue.mul(100)); if (myTokenValue <= maxTokenAmount) { uint256 minTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).sub(_deviate)).div(frontEthValue.mul(100)); if (myTokenValue >= minTokenAmount) { return false; } } return true; } // Check contract status function checkContractState(uint256 createBlock) public view returns (uint256) { if (block.number.sub(createBlock) > _blockLimit) { return 1; } return 0; } // Transfer ETH function repayEth(address accountAddress, uint256 asset) private { address payable addr = accountAddress.make_payable(); addr.transfer(asset); } // View the upper limit of the block interval function checkBlockLimit() public view returns(uint256) { return _blockLimit; } // View taker fee ratio function checkTranEth() public view returns (uint256) { return _tranEth; } // View additional transaction multiple function checkTranAddition() public view returns(uint256) { return _tranAddition; } // View minimum offering ETH function checkleastEth() public view returns(uint256) { return _leastEth; } // View offering ETH span function checkOfferSpan() public view returns(uint256) { return _offerSpan; } // View block offering amount function checkBlockOfferAmount(uint256 blockNum, address token) public view returns (uint256) { return _blockOfferAmount[blockNum][token]; } // View offering block mining amount function checkBlockMining(uint256 blockNum, address token) public view returns (uint256) { return _blockMining[blockNum][token]; } // View offering mining amount function checkOfferMining(uint256 blockNum, address token, uint256 serviceCharge) public view returns (uint256) { if (serviceCharge == 0) { return 0; } else { return _blockMining[blockNum][token].mul(serviceCharge).div(_blockOfferAmount[blockNum][token]); } } // View the owner allocation ratio function checkOwnerMining() public view returns(uint256) { return _ownerMining; } // View the mining decay function checkAttenuationAmount(uint256 num) public view returns(uint256) { return _attenuationAmount[num]; } // Modify taker order fee ratio function changeTranEth(uint256 num) public onlyOwner { _tranEth = num; } // Modify block interval upper limit function changeBlockLimit(uint32 num) public onlyOwner { _blockLimit = num; } // Modify additional transaction multiple function changeTranAddition(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _tranAddition = num; } // Modify minimum offering ETH function changeLeastEth(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _leastEth = num; } // Modify offering ETH span function changeOfferSpan(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _offerSpan = num; } // Modify price deviation function changekDeviate(uint256 num) public onlyOwner { _deviate = num; } // Modify the deviation from scale function changeDeviationFromScale(uint256 num) public onlyOwner { _deviationFromScale = num; } // Modify the owner allocation ratio function changeOwnerMining(uint256 num) public onlyOwner { _ownerMining = num; } // Modify the mining decay function changeAttenuationAmount(uint256 firstAmount, uint256 top, uint256 bottom) public onlyOwner { uint256 blockAmount = firstAmount; for (uint256 i = 0; i < 10; i ++) { _attenuationAmount[i] = blockAmount; blockAmount = blockAmount.mul(top).div(bottom); } } // Vote administrators only modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender), "No authority"); _; } /** * Get the number of offers stored in the offer array * @return The number of offers stored in the offer array **/ function getPriceCount() view public returns (uint256) { return _prices.length; } /** * Get offer information according to the index * @param priceIndex Offer index * @return Offer information **/ function getPrice(uint256 priceIndex) view public returns (string memory) { // The buffer array used to generate the result string bytes memory buf = new bytes(500000); uint256 index = 0; index = writeOfferPriceData(priceIndex, _prices[priceIndex], buf, index); // Generate the result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } /** * Search the contract address list of the target account (reverse order) * @param start Search forward from the index corresponding to the given contract address (not including the record corresponding to start address) * @param count Maximum number of records to return * @param maxFindCount The max index to search * @param owner Target account address * @return Separate the offer records with symbols. use , to divide fields: * uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge **/ function find(address start, uint256 count, uint256 maxFindCount, address owner) view public returns (string memory) { // Buffer array used to generate result string bytes memory buf = new bytes(500000); uint256 index = 0; // Calculate search interval i and end uint256 i = _prices.length; uint256 end = 0; if (start != address(0)) { i = toIndex(start); } if (i > maxFindCount) { end = i - maxFindCount; } // Loop search, write qualified records into buffer while (count > 0 && i-- > end) { Nest_NToken_OfferPriceData memory price = _prices[i]; if (price.owner == owner) { --count; index = writeOfferPriceData(i, price, buf, index); } } // Generate result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } /** * Get the list of offers by page * @param offset Skip the first offset records * @param count Maximum number of records to return * @param order Sort rules. 0 means reverse order, non-zero means positive order * @return Separate the offer records with symbols. use , to divide fields: * uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge **/ function list(uint256 offset, uint256 count, uint256 order) view public returns (string memory) { // Buffer array used to generate result string bytes memory buf = new bytes(500000); uint256 index = 0; // Find search interval i and end uint256 i = 0; uint256 end = 0; if (order == 0) { // Reverse order, in default // Calculate search interval i and end if (offset < _prices.length) { i = _prices.length - offset; } if (count < i) { end = i - count; } // Write records in the target interval into the buffer while (i-- > end) { index = writeOfferPriceData(i, _prices[i], buf, index); } } else { // Ascending order // Calculate the search interval i and end if (offset < _prices.length) { i = offset; } else { i = _prices.length; } end = i + count; if(end > _prices.length) { end = _prices.length; } // Write the records in the target interval into the buffer while (i < end) { index = writeOfferPriceData(i, _prices[i], buf, index); ++i; } } // Generate the result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } // Write the offer data into the buffer and return the buffer index function writeOfferPriceData(uint256 priceIndex, Nest_NToken_OfferPriceData memory price, bytes memory buf, uint256 index) pure private returns (uint256) { index = writeAddress(toAddress(priceIndex), buf, index); buf[index++] = byte(uint8(44)); index = writeAddress(price.owner, buf, index); buf[index++] = byte(uint8(44)); index = writeAddress(price.tokenAddress, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.ethAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.tokenAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.dealEthAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.dealTokenAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.blockNum, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.serviceCharge, buf, index); buf[index++] = byte(uint8(44)); return index; } // Convert integer to string in decimal form, write the string into the buffer, and return the buffer index function writeUInt(uint256 iv, bytes memory buf, uint256 index) pure public returns (uint256) { uint256 i = index; do { buf[index++] = byte(uint8(iv % 10 +48)); iv /= 10; } while (iv > 0); for (uint256 j = index; j > i; ++i) { byte t = buf[i]; buf[i] = buf[--j]; buf[j] = t; } return index; } // Convert the address to a hexadecimal string and write it into the buffer, and return the buffer index function writeAddress(address addr, bytes memory buf, uint256 index) pure private returns (uint256) { uint256 iv = uint256(addr); uint256 i = index + 40; do { uint256 w = iv % 16; if(w < 10) { buf[index++] = byte(uint8(w +48)); } else { buf[index++] = byte(uint8(w +87)); } iv /= 16; } while (index < i); i -= 40; for (uint256 j = index; j > i; ++i) { byte t = buf[i]; buf[i] = buf[--j]; buf[j] = t; } return index; } } /** * @title Auction NToken contract * @dev Auction for listing and generating NToken */ contract Nest_NToken_TokenAuction { using SafeMath for uint256; using address_make_payable for address; using SafeERC20 for ERC20; Nest_3_VoteFactory _voteFactory; // Voting contract Nest_NToken_TokenMapping _tokenMapping; // NToken mapping contract ERC20 _nestToken; // NestToken Nest_3_OfferPrice _offerPrice; // Price contract address _destructionAddress; // Destruction contract address uint256 _duration = 5 days; // Auction duration uint256 _minimumNest = 100000 ether; // Minimum auction amount uint256 _tokenNum = 1; // Auction token number uint256 _incentiveRatio = 50; // Incentive ratio uint256 _minimumInterval = 10000 ether; // Minimum auction interval mapping(address => AuctionInfo) _auctionList; // Auction list mapping(address => bool) _tokenBlackList; // Auction blacklist struct AuctionInfo { uint256 endTime; // End time uint256 auctionValue; // Auction price address latestAddress; // Highest auctioneer uint256 latestAmount; // Lastest auction amount } address[] _allAuction; // Auction list array /** * @dev Initialization method * @param voteFactory Voting contract address */ constructor (address voteFactory) public { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping"))); _nestToken = ERC20(address(voteFactoryMap.checkAddress("nest"))); _destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction")); _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice"))); } /** * @dev Reset voting contract * @param voteFactory Voting contract address */ function changeMapping(address voteFactory) public onlyOwner { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping"))); _nestToken = ERC20(address(voteFactoryMap.checkAddress("nest"))); _destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction")); _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice"))); } /** * @dev Initiating auction * @param token Auction token address * @param auctionAmount Initial auction amount */ function startAnAuction(address token, uint256 auctionAmount) public { require(_tokenMapping.checkTokenMapping(token) == address(0x0), "Token already exists"); require(_auctionList[token].endTime == 0, "Token is on sale"); require(auctionAmount >= _minimumNest, "AuctionAmount less than the minimum auction amount"); require(_nestToken.transferFrom(address(msg.sender), address(this), auctionAmount), "Authorization failed"); require(!_tokenBlackList[token]); // Verification ERC20 tokenERC20 = ERC20(token); tokenERC20.safeTransferFrom(address(msg.sender), address(this), 1); require(tokenERC20.balanceOf(address(this)) >= 1); tokenERC20.safeTransfer(address(msg.sender), 1); AuctionInfo memory thisAuction = AuctionInfo(now.add(_duration), auctionAmount, address(msg.sender), auctionAmount); _auctionList[token] = thisAuction; _allAuction.push(token); } /** * @dev Auction * @param token Auction token address * @param auctionAmount Auction amount */ function continueAuction(address token, uint256 auctionAmount) public { require(now <= _auctionList[token].endTime && _auctionList[token].endTime != 0, "Auction closed"); require(auctionAmount > _auctionList[token].auctionValue, "Insufficient auction amount"); uint256 subAuctionAmount = auctionAmount.sub(_auctionList[token].auctionValue); require(subAuctionAmount >= _minimumInterval); uint256 excitation = subAuctionAmount.mul(_incentiveRatio).div(100); require(_nestToken.transferFrom(address(msg.sender), address(this), auctionAmount), "Authorization failed"); require(_nestToken.transfer(_auctionList[token].latestAddress, _auctionList[token].auctionValue.add(excitation)), "Transfer failure"); // Update auction information _auctionList[token].auctionValue = auctionAmount; _auctionList[token].latestAddress = address(msg.sender); _auctionList[token].latestAmount = _auctionList[token].latestAmount.add(subAuctionAmount.sub(excitation)); } /** * @dev Listing * @param token Auction token address */ function auctionSuccess(address token) public { Nest_3_TokenAbonus nestAbonus = Nest_3_TokenAbonus(payable(_voteFactory.checkAddress("nest.v3.tokenAbonus"))); uint256 nowTime = now; uint256 nextTime = nestAbonus.getNextTime(); uint256 timeLimit = nestAbonus.checkTimeLimit(); uint256 getAbonusTimeLimit = nestAbonus.checkGetAbonusTimeLimit(); require(!(nowTime >= nextTime.sub(timeLimit) && nowTime <= nextTime.sub(timeLimit).add(getAbonusTimeLimit)), "Not time to auctionSuccess"); require(nowTime > _auctionList[token].endTime && _auctionList[token].endTime != 0, "Token is on sale"); // Initialize NToken Nest_NToken nToken = new Nest_NToken(strConcat("NToken", getAddressStr(_tokenNum)), strConcat("N", getAddressStr(_tokenNum)), address(_voteFactory), address(_auctionList[token].latestAddress)); // Auction NEST destruction require(_nestToken.transfer(_destructionAddress, _auctionList[token].latestAmount), "Transfer failure"); // Add NToken mapping _tokenMapping.addTokenMapping(token, address(nToken)); // Initialize charging parameters _offerPrice.addPriceCost(token); _tokenNum = _tokenNum.add(1); } function strConcat(string memory _a, string memory _b) public pure returns (string memory){ bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory ret = new string(_ba.length + _bb.length); bytes memory bret = bytes(ret); uint k = 0; for (uint i = 0; i < _ba.length; i++) { bret[k++] = _ba[i]; } for (uint i = 0; i < _bb.length; i++) { bret[k++] = _bb[i]; } return string(ret); } // Convert to 4-digit string function getAddressStr(uint256 iv) public pure returns (string memory) { bytes memory buf = new bytes(64); uint256 index = 0; do { buf[index++] = byte(uint8(iv % 10 + 48)); iv /= 10; } while (iv > 0 || index < 4); bytes memory str = new bytes(index); for(uint256 i = 0; i < index; ++i) { str[i] = buf[index - i - 1]; } return string(str); } // Check auction duration function checkDuration() public view returns(uint256) { return _duration; } // Check minimum auction amount function checkMinimumNest() public view returns(uint256) { return _minimumNest; } // Check initiated number of auction tokens function checkAllAuctionLength() public view returns(uint256) { return _allAuction.length; } // View auctioned token addresses function checkAuctionTokenAddress(uint256 num) public view returns(address) { return _allAuction[num]; } // View auction blacklist function checkTokenBlackList(address token) public view returns(bool) { return _tokenBlackList[token]; } // View auction token information function checkAuctionInfo(address token) public view returns(uint256 endTime, uint256 auctionValue, address latestAddress) { AuctionInfo memory info = _auctionList[token]; return (info.endTime, info.auctionValue, info.latestAddress); } // View token number function checkTokenNum() public view returns (uint256) { return _tokenNum; } // Modify auction duration function changeDuration(uint256 num) public onlyOwner { _duration = num.mul(1 days); } // Modify minimum auction amount function changeMinimumNest(uint256 num) public onlyOwner { _minimumNest = num; } // Modify auction blacklist function changeTokenBlackList(address token, bool isBlack) public onlyOwner { _tokenBlackList[token] = isBlack; } // Administrator only modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender), "No authority"); _; } } contract Nest_NToken is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; // Balance ledger mapping (address => mapping (address => uint256)) private _allowed; // Approval ledger uint256 private _totalSupply = 0 ether; // Total supply string public name; // Token name string public symbol; // Token symbol uint8 public decimals = 18; // Precision uint256 public _createBlock; // Create block number uint256 public _recentlyUsedBlock; // Recently used block number Nest_3_VoteFactory _voteFactory; // Voting factory contract address _bidder; // Owner /** * @dev Initialization method * @param _name Token name * @param _symbol Token symbol * @param voteFactory Voting factory contract address * @param bidder Successful bidder address */ constructor (string memory _name, string memory _symbol, address voteFactory, address bidder) public { name = _name; symbol = _symbol; _createBlock = block.number; _recentlyUsedBlock = block.number; _voteFactory = Nest_3_VoteFactory(address(voteFactory)); _bidder = bidder; } /** * @dev Reset voting contract method * @param voteFactory Voting contract address */ function changeMapping (address voteFactory) public onlyOwner { _voteFactory = Nest_3_VoteFactory(address(voteFactory)); } /** * @dev Additional issuance * @param value Additional issuance amount */ function increaseTotal(uint256 value) public { address offerMain = address(_voteFactory.checkAddress("nest.nToken.offerMain")); require(address(msg.sender) == offerMain, "No authority"); _balances[offerMain] = _balances[offerMain].add(value); _totalSupply = _totalSupply.add(value); _recentlyUsedBlock = block.number; } /** * @dev Check the total amount of tokens * @return Total supply */ function totalSupply() override public view returns (uint256) { return _totalSupply; } /** * @dev Check address balance * @param owner Address to be checked * @return Return the balance of the corresponding address */ function balanceOf(address owner) override public view returns (uint256) { return _balances[owner]; } /** * @dev Check block information * @return createBlock Initial block number * @return recentlyUsedBlock Recently mined and issued block */ function checkBlockInfo() public view returns(uint256 createBlock, uint256 recentlyUsedBlock) { return (_createBlock, _recentlyUsedBlock); } /** * @dev Check owner's approved allowance to the spender * @param owner Approving address * @param spender Approved address * @return Approved amount */ function allowance(address owner, address spender) override public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer method * @param to Transfer target * @param value Transfer amount * @return Whether the transfer is successful */ function transfer(address to, uint256 value) override public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approval method * @param spender Approval target * @param value Approval amount * @return Whether the approval is successful */ function approve(address spender, uint256 value) override public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens when approved * @param from Transfer-out account address * @param to Transfer-in account address * @param value Transfer amount * @return Whether approved transfer is successful */ function transferFrom(address from, address to, uint256 value) override public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @dev Increase the allowance * @param spender Approval target * @param addedValue Amount to increase * @return whether increase is successful */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the allowance * @param spender Approval target * @param subtractedValue Amount to decrease * @return Whether decrease is successful */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer method * @param to Transfer target * @param value Transfer amount */ function _transfer(address from, address to, uint256 value) internal { _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Check the creator * @return Creator address */ function checkBidder() public view returns(address) { return _bidder; } /** * @dev Transfer creator * @param bidder New creator address */ function changeBidder(address bidder) public { require(address(msg.sender) == _bidder); _bidder = bidder; } // Administrator only modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender)); _; } } /** * @title NToken mapping contract * @dev Add, modify and check offering token mapping */ contract Nest_NToken_TokenMapping { mapping (address => address) _tokenMapping; // Token mapping - offering token => NToken Nest_3_VoteFactory _voteFactory; // Voting contract event TokenMappingLog(address token, address nToken); /** * @dev Initialization method * @param voteFactory Voting contract address */ constructor(address voteFactory) public { _voteFactory = Nest_3_VoteFactory(address(voteFactory)); } /** * @dev Reset voting contract * @param voteFactory voting contract address */ function changeMapping(address voteFactory) public onlyOwner { _voteFactory = Nest_3_VoteFactory(address(voteFactory)); } /** * @dev Add token mapping * @param token Offering token address * @param nToken Mining NToken address */ function addTokenMapping(address token, address nToken) public { require(address(msg.sender) == address(_voteFactory.checkAddress("nest.nToken.tokenAuction")), "No authority"); require(_tokenMapping[token] == address(0x0), "Token already exists"); _tokenMapping[token] = nToken; emit TokenMappingLog(token, nToken); } /** * @dev Change token mapping * @param token Offering token address * @param nToken Mining NToken address */ function changeTokenMapping(address token, address nToken) public onlyOwner { _tokenMapping[token] = nToken; emit TokenMappingLog(token, nToken); } /** * @dev Check token mapping * @param token Offering token address * @return Mining NToken address */ function checkTokenMapping(address token) public view returns (address) { return _tokenMapping[token]; } // Only for administrator modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender), "No authority"); _; } }
If different block offer
if (endBlock != tokenInfo.latestOffer) { priceInfo.frontBlock = tokenInfo.latestOffer; tokenInfo.latestOffer = endBlock; }
12,580,171
[ 1, 2047, 3775, 1203, 10067, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 409, 1768, 480, 1147, 966, 18, 13550, 10513, 13, 288, 203, 5411, 6205, 966, 18, 10211, 1768, 273, 1147, 966, 18, 13550, 10513, 31, 203, 5411, 1147, 966, 18, 13550, 10513, 273, 679, 1768, 31, 203, 3639, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; import 'token/Token.sol'; import './AddressList.sol'; /** * @dev The library for multiuser singletoken regulation. * This data contains stack of variants sorted by value on its internal balance, * any account(voter) can increase variant balance by self balance from given token, * and any voter can decrease balance of variant but no more that given. * The variant with high balance placed on top of voting pool and return by `current()`. */ library Voting { /* Voting structure */ struct Poll { /* Stack of all voters */ AddressList.Data voters; /* Stack of all variants by value */ AddressList.Data variants; /* Count of shares for given variant */ mapping(address => uint) valueOf; /* Count of shares for given voter */ mapping(address => uint) shareOf; /* Poll variant for given voter */ mapping(address => address) pollOf; } using AddressList for AddressList.Data; /** * @dev Current high value poll * @param _poll ref to `Poll` structure * @return current value */ function current(Poll storage _poll) public view returns (address) { return _poll.variants.first(); } /** * @dev Increase poll shares for given variant * @param _poll ref to `Poll` structure * @param _variant voter variant value * @param _shares token represents vote * @param _count how much votes are given */ function up(Poll storage _poll, address _voter, address _variant, Token _shares, uint _count) public { // Check for already voting for any variant if (_poll.pollOf[_voter] != 0 && _poll.pollOf[_voter] != _variant) revert(); // Try to transfer count of shares from voter to self if (!_shares.transferFrom(_voter, this, _count)) revert(); // Increase shares and set the poll _poll.shareOf[_voter] += _count; _poll.pollOf[_voter] = _variant; _poll.valueOf[_variant] += _count; // Append voter if not in list if (!_poll.voters.contains(_voter)) _poll.voters.append(_voter); // Append variant if not in list if (!_poll.variants.contains(_variant)) _poll.variants.append(_variant); // Shift variant in the stack shiftLeft(_poll, _variant); } /** * @dev Decrease poll shares of given voter * @param _poll ref to `Poll` structure * @param _count how much shares will decreased */ function down(Poll storage _poll, address _voter, Token _shares, uint _count) public { // So I can refund no more that gives from voter var refund = _poll.shareOf[_voter] > _count ? _count : _poll.shareOf[_voter]; var variant = _poll.pollOf[_voter]; // Transfer shares _shares.transfer(_voter, refund); _poll.shareOf[_voter] -= refund; _poll.valueOf[variant] -= refund; // Clean voter poll if (_poll.shareOf[_voter] == 0) { _poll.pollOf[_voter] = 0; _poll.voters.remove(_voter); } // Shift right or drop when no shares if (_poll.valueOf[variant] > 0) { shiftRight(_poll, _poll.pollOf[_voter]); } else { _poll.variants.remove(variant); } } /* * Shifting mechanism * Thesys: the stack of variants should be sorted by valueOf value. * Solution: * - `up` call: variant shifted left while his valueOf value is large * - `down` call: varian shifted right in the stack while valueOf value is low */ function shiftLeft(Poll storage _poll, address _variant) internal { var value = _poll.valueOf[_variant]; var left = _poll.variants.prevOf[_variant]; /* XXX: possible DoS by block gas limit when a lot of same value variants */ while (left != 0 && _poll.valueOf[left] < value) left = _poll.variants.prevOf[left]; _poll.variants.remove(_variant); if (left == 0) { _poll.variants.prepend(_variant); } else { _poll.variants.append(_variant, left); } } function shiftRight(Poll storage _poll, address _variant) internal { var value = _poll.valueOf[_variant]; var right = _poll.variants.nextOf[_variant]; /* XXX: possible DoS by block gas limit when a lot of same value variants */ while (right != 0 && _poll.valueOf[right] > value) right = _poll.variants.nextOf[right]; _poll.variants.remove(_variant); if (right == 0) { _poll.variants.append(_variant); } else { _poll.variants.prepend(_variant, right); } } }
* @dev Increase poll shares for given variant @param _poll ref to `Poll` structure @param _variant voter variant value @param _shares token represents vote @param _count how much votes are given/ Check for already voting for any variant Try to transfer count of shares from voter to self Increase shares and set the poll Append voter if not in list Append variant if not in list Shift variant in the stack
function current(Poll storage _poll) public view returns (address) function up(Poll storage _poll, address _voter, address _variant, Token _shares, uint _count) public { if (_poll.pollOf[_voter] != 0 && _poll.pollOf[_voter] != _variant) revert(); if (!_shares.transferFrom(_voter, this, _count)) revert(); _poll.shareOf[_voter] += _count; _poll.pollOf[_voter] = _variant; _poll.valueOf[_variant] += _count; if (!_poll.voters.contains(_voter)) _poll.voters.append(_voter); if (!_poll.variants.contains(_variant)) _poll.variants.append(_variant); shiftLeft(_poll, _variant); }
12,646,401
[ 1, 382, 11908, 7672, 24123, 364, 864, 5437, 225, 389, 13835, 1278, 358, 1375, 19085, 68, 3695, 225, 389, 8688, 331, 20005, 5437, 460, 225, 389, 30720, 1147, 8686, 12501, 225, 389, 1883, 3661, 9816, 19588, 854, 864, 19, 2073, 364, 1818, 331, 17128, 364, 1281, 5437, 6161, 358, 7412, 1056, 434, 24123, 628, 331, 20005, 358, 365, 657, 11908, 24123, 471, 444, 326, 7672, 6181, 331, 20005, 309, 486, 316, 666, 6181, 5437, 309, 486, 316, 666, 21444, 5437, 316, 326, 2110, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 783, 12, 19085, 2502, 389, 13835, 13, 1071, 1476, 1135, 261, 2867, 13, 203, 203, 565, 445, 731, 12, 19085, 2502, 389, 13835, 16, 1758, 389, 90, 20005, 16, 1758, 389, 8688, 16, 203, 7734, 3155, 389, 30720, 16, 2254, 389, 1883, 13, 1071, 288, 203, 3639, 309, 261, 67, 13835, 18, 13835, 951, 63, 67, 90, 20005, 65, 480, 374, 597, 389, 13835, 18, 13835, 951, 63, 67, 90, 20005, 65, 480, 389, 8688, 13, 203, 5411, 15226, 5621, 203, 203, 3639, 309, 16051, 67, 30720, 18, 13866, 1265, 24899, 90, 20005, 16, 333, 16, 389, 1883, 3719, 203, 5411, 15226, 5621, 203, 203, 3639, 389, 13835, 18, 14419, 951, 63, 67, 90, 20005, 65, 282, 1011, 389, 1883, 31, 203, 3639, 389, 13835, 18, 13835, 951, 63, 67, 90, 20005, 65, 377, 273, 389, 8688, 31, 203, 3639, 389, 13835, 18, 1132, 951, 63, 67, 8688, 65, 1011, 389, 1883, 31, 203, 203, 3639, 309, 16051, 67, 13835, 18, 90, 352, 414, 18, 12298, 24899, 90, 20005, 3719, 203, 5411, 389, 13835, 18, 90, 352, 414, 18, 6923, 24899, 90, 20005, 1769, 203, 203, 3639, 309, 16051, 67, 13835, 18, 15886, 18, 12298, 24899, 8688, 3719, 203, 5411, 389, 13835, 18, 15886, 18, 6923, 24899, 8688, 1769, 203, 203, 3639, 4654, 3910, 24899, 13835, 16, 389, 8688, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.8.10; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "./AccessControlStorage.sol"; contract SwimmerNetworkAC is AccessControl, Initializable, SwimmerNetworkACStorage{ function initialize(address[] memory admins) external initializer() { firstBanningTime = 1 hours; secondBanningTime = 7955107200; // 2222/Feb/02 00:00:00 for(uint i = 0; i < admins.length; i++){ _grantRole(CREATE_CONTRACT_ROLE, admins[i]); _grantRole(VALIDATOR_ROLE, admins[i]); _grantRole(SETBLACKLIST_ROLE, admins[i]); _grantRole(DEFAULT_ADMIN_ROLE, admins[i]); } } function setBlacklist(address add) external onlyRole(SETBLACKLIST_ROLE){ require(blockedTime[add] != secondBanningTime, "Permanently BAN"); if(blockedTime[add] == 0){ blockedTime[add] = block.timestamp + firstBanningTime; } else{ blockedTime[add] = secondBanningTime; } } function removeBlacklist(address add) external onlyRole(SETBLACKLIST_ROLE){ blockedTime[add] = 0; } function isBlacklist(address add) external view returns(bool){ return blockedTime[add] > block.timestamp; } function setFeeCover(address _contract, bool onoff) external onlyRole(CREATE_CONTRACT_ROLE){ ContractInfo storage info = feeCoverInfo[_contract]; if(info.owner == address(0x0)){ info.owner = _msgSender(); } else{ require(info.owner == _msgSender(), "Invalid owner"); } info.feeCover = onoff; } function changeContractOwner(address _contract, address newOwner) external onlyRole(CREATE_CONTRACT_ROLE){ require(newOwner != address(0x0), "Invalid address"); ContractInfo storage info = feeCoverInfo[_contract]; require(info.owner == _msgSender(), "Invalid caller"); info.owner = newOwner; } function addValidators(address[] memory validators) external onlyRole(DEFAULT_ADMIN_ROLE){ require(validators.length > 0, "validators are empty"); for(uint i = 0; i < validators.length; i++){ validatorsSet.push(validators[i]); _grantRole(VALIDATOR_ROLE, validators[i]); } // numberOfValidators += validators.length; } function removeValidators(uint[] memory indexes) external onlyRole(DEFAULT_ADMIN_ROLE){ require(indexes.length > 0, "validators are empty"); for(uint i = 0; i < indexes.length; i++){ delete validatorsSet[indexes[i]]; _revokeRole(VALIDATOR_ROLE, validatorsSet[indexes[i]]); } // numberOfValidators -= indexes.length; } function getValidatorsSet() external view returns(address[] memory){ return validatorsSet; } function isValidator(address add) external view returns(bool){ return hasRole(VALIDATOR_ROLE, add); } }
2222/Feb/02 00:00:00
secondBanningTime = 7955107200;
5,479,673
[ 1, 3787, 3787, 19, 2954, 70, 19, 3103, 9631, 30, 713, 30, 713, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2205, 38, 10903, 950, 273, 26517, 2539, 23054, 6976, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; import './FoldingAccount.sol'; import './interfaces/IFoldingAccountOwnerProvider.sol'; import './interfaces/IFoldingConnectorProvider.sol'; import './interfaces/ILendingPlatformAdapterProvider.sol'; import './interfaces/IExchangerAdapterProvider.sol'; import './interfaces/ICTokenProvider.sol'; import './FodlNFT.sol'; contract FoldingRegistry is Initializable, OwnableUpgradeable, IFoldingAccountOwnerProvider, IFoldingConnectorProvider, ILendingPlatformAdapterProvider, ICTokenProvider, IExchangerAdapterProvider { FodlNFT public fodlNFT; function initialize(address fodlNFT_) public virtual initializer { require(fodlNFT_ != address(0), 'ICP0'); __Ownable_init_unchained(); fodlNFT = FodlNFT(fodlNFT_); } function version() external pure virtual returns (uint8) { return 1; } mapping(address => uint256) private nonces; /** * @dev create2 is needed in order to be able to predict the folding * account address in a way that does not depend on the nonce of the sender. * This is because prior to creating the account, the user will need to approve * tokens to be sent to it. Thus we keep internal contract nonces so that this salt * is always unique for every sender without compromising UX. */ function createAccount() public virtual returns (address) { bytes memory bytecode = type(FoldingAccount).creationCode; bytecode = abi.encodePacked(bytecode, abi.encode(address(this), address(fodlNFT))); uint256 salt = uint256(keccak256(abi.encodePacked(msg.sender, nonces[msg.sender]))); nonces[msg.sender] = nonces[msg.sender] + 1; address account; uint256 size; assembly { account := create2(0, add(bytecode, 0x20), mload(bytecode), salt) size := extcodesize(account) } require(size > 0, 'FR1'); fodlNFT.mint(msg.sender, uint256(account)); return account; } function accountOwner(address account) external view virtual override returns (address) { return fodlNFT.ownerOf(uint256(account)); } /// @notice Fallback function creates an account and forwards the call function _fallback() internal virtual { address createdAccount = createAccount(); assembly { calldatacopy(0, 0, calldatasize()) let result := call(gas(), createdAccount, callvalue(), 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } fallback() external payable { _fallback(); } /// @dev Don't specify state mutability for upgradability. function _receive() internal virtual { revert('FR13'); } receive() external payable { _receive(); } // ********** Folding Connector Registration and IFoldingConnectorProvider ********** event ImplementationAdded(address implementation, bytes4[] signatures); event ImplementationRemoved(bytes4[] signatures); /// @dev mapping from function signatures to the connector that implements them mapping(bytes4 => address) internal sigImplementations; function addImplementation(address _implementation, bytes4[] calldata _sigs) public virtual onlyOwner { require(_implementation != address(0), 'FR14'); for (uint256 i = 0; i < _sigs.length; i++) { bytes4 _sig = _sigs[i]; sigImplementations[_sig] = _implementation; } emit ImplementationAdded(_implementation, _sigs); } function removeImplementation(bytes4[] memory sigs) public virtual onlyOwner { emit ImplementationRemoved(sigs); for (uint256 i = 0; i < sigs.length; i++) { bytes4 sig = sigs[i]; delete sigImplementations[sig]; } } function getImplementation(bytes4 _sig) external view virtual override returns (address implementation) { implementation = sigImplementations[_sig]; require(implementation != address(0), 'FR2'); } // ********** Lending Platform Adapter Registry and ILendingPlatformAdapterProvider ********** mapping(address => address) internal platformAdapters; event PlatformAdapterLinkUpdated(address platform, address adapter); function addPlatformWithAdapter(address platform, address adapter) public virtual onlyOwner { require(platform != address(0), 'FR14'); require(platformAdapters[platform] == address(0), 'FR3'); platformAdapters[platform] = adapter; emit PlatformAdapterLinkUpdated(platform, adapter); } function addBatchPlatformsWithAdapter(address[] memory platforms, address adapter) external virtual onlyOwner { require(platforms.length > 0, 'FR4'); for (uint256 i = 0; i < platforms.length; i++) { addPlatformWithAdapter(platforms[i], adapter); } } function changePlatformAdapter(address platform, address newAdapter) external virtual onlyOwner { require(platform != address(0), 'FR14'); require(platformAdapters[platform] != address(0), 'FR5'); platformAdapters[platform] = newAdapter; emit PlatformAdapterLinkUpdated(platform, newAdapter); } function removePlatform(address platform) external virtual onlyOwner { require(platformAdapters[platform] != address(0), 'FR5'); delete platformAdapters[platform]; emit PlatformAdapterLinkUpdated(platform, address(0)); } function getPlatformAdapter(address platform) external view virtual override returns (address adapter) { adapter = platformAdapters[platform]; require(adapter != address(0), 'FR6'); } // ********** Lending Platform Token Mappings and ICTokenProvider ********** mapping(address => mapping(address => address)) internal tokensOnPlatforms; event TokenOnPlatformUpdated(address platform, address token, address syntheticToken); function addCTokenOnPlatform( address platform, address token, address synthToken ) external virtual onlyOwner { require(platform != address(0), 'FR14'); require(token != address(0), 'FR14'); require(tokensOnPlatforms[platform][token] == address(0), 'FR7'); tokensOnPlatforms[platform][token] = synthToken; emit TokenOnPlatformUpdated(platform, token, synthToken); } function removeCTokenFromPlatform(address platform, address token) external virtual onlyOwner { require(tokensOnPlatforms[platform][token] != address(0), 'FR8'); delete tokensOnPlatforms[platform][token]; emit TokenOnPlatformUpdated(platform, token, address(0)); } function getCToken(address platform, address token) external view virtual override returns (address cToken) { cToken = tokensOnPlatforms[platform][token]; require(cToken != address(0), 'FR9'); } // ********** Exchanger Adapter Registry and IExchangerAdapterProvider ********** mapping(bytes1 => address) internal exchangerAdapters; event ExchangerAdapterLinkUpdated(bytes1 flag, address adapter); function addExchangerWithAdapter(bytes1 flag, address adapter) external virtual onlyOwner { require(adapter != address(0), 'FR14'); require(exchangerAdapters[flag] == address(0), 'FR10'); exchangerAdapters[flag] = adapter; emit ExchangerAdapterLinkUpdated(flag, adapter); } function changeExchangerAdapter(bytes1 flag, address newAdapter) external virtual onlyOwner { require(newAdapter != address(0), 'FR14'); require(exchangerAdapters[flag] != address(0), 'FR11'); exchangerAdapters[flag] = newAdapter; emit ExchangerAdapterLinkUpdated(flag, newAdapter); } function removeExchanger(bytes1 flag) external virtual onlyOwner { require(exchangerAdapters[flag] != address(0), 'FR11'); delete exchangerAdapters[flag]; emit ExchangerAdapterLinkUpdated(flag, address(0)); } function getExchangerAdapter(bytes1 flag) external view virtual override returns (address adapter) { adapter = exchangerAdapters[flag]; require(adapter != address(0), 'FR12'); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import '../modules/FoldingAccount/FoldingAccountStorage.sol'; import './interfaces/IFoldingConnectorProvider.sol'; contract FoldingAccount is FoldingAccountStorage { constructor(address foldingRegistry, address nft) public { AccountStore storage store = aStore(); store.foldingRegistry = foldingRegistry; store.nft = nft; } /// @notice Find the connector for `msg.sig` and delegate call it with `msg.data` function delegate() private { bool firstCall = false; // We need to delete the entryCaller on exit AccountStore storage accountStorage = aStore(); if (accountStorage.entryCaller == address(0)) { accountStorage.entryCaller = msg.sender; firstCall = true; } // Check if a connector expects a callback or find connector address impl = accountStorage.callbackTarget; if (impl != address(0)) { require(accountStorage.expectedCallbackSig == msg.sig, 'FA1'); } else { impl = IFoldingConnectorProvider(accountStorage.foldingRegistry).getImplementation(msg.sig); } /// @dev This assembly code returns directly to caller assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(0, 0, size) switch result case 0 { revert(0, size) } default { /// @dev if this is the first call, set the entryCaller to 0 if firstCall { sstore(accountStorage_slot, 0) } return(0, size) } } } fallback() external payable { if (msg.sig != bytes4(0)) delegate(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IFoldingAccountOwnerProvider { function accountOwner(address foldingAccount) external view returns (address foldingAccountOwner); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IFoldingConnectorProvider { function getImplementation(bytes4 functionSignature) external view returns (address implementation); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface ILendingPlatformAdapterProvider { function getPlatformAdapter(address platform) external view returns (address platformAdapter); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IExchangerAdapterProvider { function getExchangerAdapter(byte flag) external view returns (address exchangerAdapter); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface ICTokenProvider { function getCToken(address platform, address token) external view returns (address syntheticToken); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/utils/Address.sol'; import '../connectors/interfaces/IResetAccountConnector.sol'; contract FodlNFT is ERC721, Ownable { using Address for address; constructor(string memory name, string memory symbol) public ERC721(name, symbol) Ownable() {} function mint(address owner, uint256 nftId) external onlyOwner { _safeMint(owner, nftId); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { address foldingAccount = address(tokenId); if (foldingAccount.isContract()) { IResetAccountConnector(foldingAccount).resetAccount(from, to, tokenId); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; contract FoldingAccountStorage { bytes32 constant ACCOUNT_STORAGE_POSITION = keccak256('folding.account.storage'); /** * entryCaller: address of the caller of the account, during a transaction * * callbackTarget: address of logic to be run when expecting a callback * * expectedCallbackSig: signature of function to be run when expecting a callback * * foldingRegistry address of factory creating FoldingAccount * * nft: address of the nft contract. * * owner: address of the owner of this FoldingAccount. */ struct AccountStore { address entryCaller; address callbackTarget; bytes4 expectedCallbackSig; address foldingRegistry; address nft; address owner; } modifier onlyAccountOwner() { AccountStore storage s = aStore(); require(s.entryCaller == s.owner, 'FA2'); _; } modifier onlyNFTContract() { AccountStore storage s = aStore(); require(s.entryCaller == s.nft, 'FA3'); _; } modifier onlyAccountOwnerOrRegistry() { AccountStore storage s = aStore(); require(s.entryCaller == s.owner || s.entryCaller == s.foldingRegistry, 'FA4'); _; } function aStore() internal pure returns (AccountStore storage s) { bytes32 position = ACCOUNT_STORAGE_POSITION; assembly { s_slot := position } } function accountOwner() internal view returns (address) { return aStore().owner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IResetAccountConnector { event OwnerChanged(address oldOwner, address newOwner); function resetAccount( address oldOwner, address newOwner, uint256 accountId ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @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"); return a - b; } /** * @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) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
* @dev create2 is needed in order to be able to predict the folding account address in a way that does not depend on the nonce of the sender. This is because prior to creating the account, the user will need to approve tokens to be sent to it. Thus we keep internal contract nonces so that this salt is always unique for every sender without compromising UX./
function createAccount() public virtual returns (address) { bytes memory bytecode = type(FoldingAccount).creationCode; bytecode = abi.encodePacked(bytecode, abi.encode(address(this), address(fodlNFT))); uint256 salt = uint256(keccak256(abi.encodePacked(msg.sender, nonces[msg.sender]))); nonces[msg.sender] = nonces[msg.sender] + 1; address account; uint256 size; assembly { account := create2(0, add(bytecode, 0x20), mload(bytecode), salt) size := extcodesize(account) } require(size > 0, 'FR1'); fodlNFT.mint(msg.sender, uint256(account)); return account; }
13,828,890
[ 1, 2640, 22, 353, 3577, 316, 1353, 358, 506, 7752, 358, 7810, 326, 11590, 310, 2236, 1758, 316, 279, 4031, 716, 1552, 486, 2447, 603, 326, 7448, 434, 326, 5793, 18, 1220, 353, 2724, 6432, 358, 4979, 326, 2236, 16, 326, 729, 903, 1608, 358, 6617, 537, 2430, 358, 506, 3271, 358, 518, 18, 22073, 732, 3455, 2713, 6835, 1661, 764, 1427, 716, 333, 4286, 353, 3712, 3089, 364, 3614, 5793, 2887, 1161, 520, 13734, 587, 60, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 752, 3032, 1435, 1071, 5024, 1135, 261, 2867, 13, 288, 203, 3639, 1731, 3778, 22801, 273, 618, 12, 15592, 310, 3032, 2934, 17169, 1085, 31, 203, 3639, 22801, 273, 24126, 18, 3015, 4420, 329, 12, 1637, 16651, 16, 24126, 18, 3015, 12, 2867, 12, 2211, 3631, 1758, 12, 74, 369, 80, 50, 4464, 3719, 1769, 203, 203, 3639, 2254, 5034, 4286, 273, 2254, 5034, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 3576, 18, 15330, 16, 1661, 764, 63, 3576, 18, 15330, 22643, 1769, 203, 3639, 1661, 764, 63, 3576, 18, 15330, 65, 273, 1661, 764, 63, 3576, 18, 15330, 65, 397, 404, 31, 203, 203, 3639, 1758, 2236, 31, 203, 3639, 2254, 5034, 963, 31, 203, 3639, 19931, 288, 203, 5411, 2236, 519, 752, 22, 12, 20, 16, 527, 12, 1637, 16651, 16, 374, 92, 3462, 3631, 312, 945, 12, 1637, 16651, 3631, 4286, 13, 203, 5411, 963, 519, 1110, 7000, 554, 12, 4631, 13, 203, 3639, 289, 203, 3639, 2583, 12, 1467, 405, 374, 16, 296, 9981, 21, 8284, 203, 203, 3639, 284, 369, 80, 50, 4464, 18, 81, 474, 12, 3576, 18, 15330, 16, 2254, 5034, 12, 4631, 10019, 203, 203, 3639, 327, 2236, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0x41E0e8ecCB307908394BA4B34b88805FD00A146b/sources/contracts/Router.sol
**** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { return PangolinLibrary.quote(amountA, reserveA, reserveB); }
4,642,966
[ 1, 2053, 28254, 13690, 55, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3862, 12, 11890, 3844, 37, 16, 2254, 20501, 37, 16, 2254, 20501, 38, 13, 1071, 16618, 5024, 3849, 1135, 261, 11890, 3844, 38, 13, 288, 203, 3639, 327, 453, 539, 355, 267, 9313, 18, 6889, 12, 8949, 37, 16, 20501, 37, 16, 20501, 38, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } } contract CasperToken is ERC20Interface, Owned { using SafeMath for uint; string public constant name = "Csper Token"; string public constant symbol = "CST"; uint8 public constant decimals = 18; uint constant public cstToMicro = uint(10) ** decimals; // This constants reflects CST token distribution uint constant public _totalSupply = 440000000 * cstToMicro; uint constant public preICOSupply = 13000000 * cstToMicro; uint constant public presaleSupply = 183574716 * cstToMicro; uint constant public crowdsaleSupply = 19750000 * cstToMicro; uint constant public communitySupply = 66000000 * cstToMicro; uint constant public systemSupply = 35210341 * cstToMicro; uint constant public investorSupply = 36714943 * cstToMicro; uint constant public teamSupply = 66000000 * cstToMicro; uint constant public adviserSupply = 7000000 * cstToMicro; uint constant public bountySupply = 8800000 * cstToMicro; uint constant public referralSupply = 3950000 * cstToMicro; // This variables accumulate amount of sold CST during // presale, crowdsale, or given to investors as bonus. uint public presaleSold = 0; uint public crowdsaleSold = 0; uint public investorGiven = 0; // Amount of ETH received during ICO uint public ethSold = 0; uint constant public softcapUSD = 4500000; uint constant public preicoUSD = 1040000; // Presale lower bound in dollars. uint constant public crowdsaleMinUSD = cstToMicro * 10 * 100 / 12; uint constant public bonusLevel0 = cstToMicro * 10000 * 100 / 12; // 10000$ uint constant public bonusLevel100 = cstToMicro * 100000 * 100 / 12; // 100000$ // Tokens are unlocked in 5 stages, by 20% (see doc to checkTransfer) // All dates are stored as timestamps. uint constant public unlockDate1 = 1538179199; // 28.09.2018 23:59:59 uint constant public unlockDate2 = 1543622399; // 30.11.2018 23:59:59 uint constant public unlockDate3 = 1548979199; // 31.01.2019 23:59:59 uint constant public unlockDate4 = 1553903999; // 29.03.2019 23:59:59 uint constant public unlockDate5 = 1559347199; // 31.05.2019 23:59:59 uint constant public teamUnlock1 = 1549065600; // 2.02.2019 uint constant public teamUnlock2 = 1564704000; // 2.08.2019 uint constant public teamUnlock3 = 1580601600; // 2.02.2020 uint constant public teamUnlock4 = 1596326400; // 2.08.2020 uint constant public teamETHUnlock1 = 1535846400; // 2.09.2018 uint constant public teamETHUnlock2 = 1538438400; // 2.10.2018 uint constant public teamETHUnlock3 = 1541116800; // 2.11.2018 //https://casperproject.atlassian.net/wiki/spaces/PROD/pages/277839878/Smart+contract+ICO // Presale 10.06.2018 - 22.07.2018 // Crowd-sale 23.07.2018 - 2.08.2018 (16.08.2018) uint constant public presaleStartTime = 1528588800; uint constant public crowdsaleStartTime = 1532304000; uint public crowdsaleEndTime = 1533168000; uint constant public crowdsaleHardEndTime = 1534377600; //address constant CsperWallet = 0x6A5e633065475393211aB623286200910F465d02; constructor() public { admin = owner; balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } modifier onlyAdmin { require(msg.sender == admin); _; } modifier onlyOwnerAndDirector { require(msg.sender == owner || msg.sender == director); _; } address admin; function setAdmin(address _newAdmin) public onlyOwnerAndDirector { admin = _newAdmin; } address director; function setDirector(address _newDirector) public onlyOwner { director = _newDirector; } bool assignedPreico = false; /// @notice assignPreicoTokens transfers 10x tokens to pre-ICO participants function assignPreicoTokens() public onlyOwnerAndDirector { require(!assignedPreico); assignedPreico = true; _freezeTransfer(0xb424958766e736827Be5A441bA2A54bEeF54fC7C, 10 * 19514560000000000000000); _freezeTransfer(0xF5dF9C2aAe5118b64Cda30eBb8d85EbE65A03990, 10 * 36084880000000000000000); _freezeTransfer(0x5D8aCe48970dce4bcD7f985eDb24f5459Ef184Ec, 10 * 2492880000000000000000); _freezeTransfer(0xcD6d5b09a34562a1ED7857B19b32bED77417655b, 10 * 1660880000000000000000); _freezeTransfer(0x50f73AC8435E4e500e37FAb8802bcB840bf4b8B8, 10 * 94896880000000000000000); _freezeTransfer(0x65Aa068590216cb088f4da28190d8815C31aB330, 10 * 16075280000000000000000); _freezeTransfer(0x2046838D148196a5117C4026E21C165785bD3982, 10 * 5893680000000000000000); _freezeTransfer(0x458e1f1050C34f5D125437fcEA0Df0aA9212EDa2, 10 * 32772040882120167215360); _freezeTransfer(0x12B687E19Cef53b2A709e9b98C4d1973850cA53F, 10 * 70956080000000000000000); _freezeTransfer(0x1Cf5daAB09155aaC1716Aa92937eC1c6D45720c7, 10 * 3948880000000000000000); _freezeTransfer(0x32fAAdFdC7938E7FbC7386CcF546c5fc382ed094, 10 * 88188880000000000000000); _freezeTransfer(0xC4eA6C0e9d95d957e75D1EB1Fbe15694CD98336c, 10 * 81948880000000000000000); _freezeTransfer(0xB97D3d579d35a479c20D28988A459E3F35692B05, 10 * 121680000000000000000); _freezeTransfer(0x65AD745047633C3402d4BC5382f72EA3A9eCFe47, 10 * 5196880000000000000000); _freezeTransfer(0xd0BEF2Fb95193f429f0075e442938F5d829a33c8, 10 * 223388880000000000000000); _freezeTransfer(0x9Fc87C3d44A6374D48b2786C46204F673b0Ae236, 10 * 28284880000000000000000); _freezeTransfer(0x42C73b8945a82041B06428359a94403a2e882406, 10 * 13080080000000000000000); _freezeTransfer(0xa4c9595b90BBa7B4d805e555E477200C61711F3a, 10 * 6590480000000000000000); _freezeTransfer(0xb93b8ceD7CD86a667E12104831b4d514365F9DF8, 10 * 116358235759665569280); _freezeTransfer(0xa94F999b3f76EB7b2Ba7B17fC37E912Fa2538a87, 10 * 10389600000000000000000); _freezeTransfer(0xD65B9b98ca08024C3c19868d42C88A3E47D67120, 10 * 25892880000000000000000); _freezeTransfer(0x3a978a9Cc36f1FE5Aab6D31E41c08d8380ad0ACB, 10 * 548080000000000000000); _freezeTransfer(0xBD46d909D55d760E2f79C5838c5C42E45c0a853A, 10 * 7526480000000000000000); _freezeTransfer(0xdD9d289d4699fDa518cf91EaFA029710e3Cbb7AA, 10 * 3324880000000000000000); _freezeTransfer(0x8671B362902C3839ae9b4bc099fd24CdeFA026F4, 10 * 21836880000000000000000); _freezeTransfer(0xf3C25Ee648031B28ADEBDD30c91056c2c5cd9C6b, 10 * 132284880000000000000000); _freezeTransfer(0x1A2392fB72255eAe19BB626678125A506a93E363, 10 * 61772880000000000000000); _freezeTransfer(0xCE2cEa425f7635557CFC00E18bc338DdE5B16C9A, 10 * 105360320000000000000000); _freezeTransfer(0x952AD1a2891506AC442D95DA4C0F1AE70A27b677, 10 * 100252880000000000000000); _freezeTransfer(0x5eE1fC4D251143Da96db2a5cD61507f2203bf7b7, 10 * 80492880000000000000000); } bool assignedTeam = false; /// @notice assignTeamTokens assigns tokens to team members /// @notice tokens for team have their own supply function assignTeamTokens() public onlyOwnerAndDirector { require(!assignedTeam); assignedTeam = true; _teamTransfer(0x1E21f744d91994D19f2a61041CD7cCA571185dfc, 13674375 * cstToMicro); // ArK _teamTransfer(0x4CE4Ea57c40bBa26B7b799d5e0b4cd063B034c8A, 9920625 * cstToMicro); // Vi4 _teamTransfer(0xdCd8a8e561d23Ca710f23E7612F1D4E0dE9bde83, 1340625 * cstToMicro); // Se4 _teamTransfer(0x0dFFA8624A1f512b8dcDE807F8B0Eab68672e5D5, 13406250 * cstToMicro); // AnD _teamTransfer(0xE091180bB0C284AA0Bd15C6888A41aba45c54AF0, 13138125 * cstToMicro); // VlM _teamTransfer(0xcdB7A51bA9af93a7BFfe08a31E4C6c5f9068A051, 3960000 * cstToMicro); // NuT _teamTransfer(0x57Bd10E12f789B74071d62550DaeB3765Ad83834, 3960000 * cstToMicro); // AlK _teamTransfer(0xEE74922eaF503463a8b20aFaD83d42F28D59f45d, 3960000 * cstToMicro); // StK _teamTransfer(0x58681a49A6f9D61eB368241a336628781afD5f87, 1320000 * cstToMicro); // DeP _teamTransfer(0x3C4662b4677dC81f16Bf3c823A7E6CE1fF7e94d7, 80000 * cstToMicro); // YuM _teamTransfer(0x041A1e96E0C9d3957613071c104E44a9c9d43996, 150000 * cstToMicro); // IgK _teamTransfer(0xD63d63D2ADAF87B0Edc38218b0a2D27FD909d8B1, 100000 * cstToMicro); // SeT _teamTransfer(0xd0d49Da78BbCBb416152dC41cc7acAb559Fb8275, 80000 * cstToMicro); // ArM _teamTransfer(0x75FdfAc64c27f5B5f0823863Fe0f2ddc660A376F, 100000 * cstToMicro); // Lera _teamTransfer(0xb66AFf323d97EF52192F170fF0F16D0a05Ebe56C, 60000 * cstToMicro); // SaBuh _teamTransfer(0xec6234E34477f7A19cD3D67401003675522a4Fad, 60000 * cstToMicro); // SaV _teamTransfer(0x1be50e8337F99983ECd4A4b15a74a5a795B73dF9, 40000 * cstToMicro); // Olga _teamTransfer(0x4c14DB011065e72C6E839bd826d101Ec09d3C530, 833000 * cstToMicro); // VaB _teamTransfer(0x7891C07b20fFf1918fAD43CF6fc7E3f83900f06d, 50000 * cstToMicro); // Artur _teamTransfer(0x27996b3c1EcF2e7cbc5f31dE7Bca17EFCb398617, 150000 * cstToMicro); // EvS } /// @nptice kycPassed is executed by backend and tells SC /// that particular client has passed KYC mapping(address => bool) public kyc; mapping(address => address) public referral; function kycPassed(address _mem, address _ref) public onlyAdmin { kyc[_mem] = true; if (_ref == richardAddr || _ref == wuguAddr) { referral[_mem] = _ref; } } // mappings for implementing ERC20 mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // mapping for implementing unlock mechanic mapping(address => uint) freezed; mapping(address => uint) teamFreezed; // ERC20 standard functions function totalSupply() public view returns (uint) { return _totalSupply; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function _transfer(address _from, address _to, uint _tokens) private { balances[_from] = balances[_from].sub(_tokens); balances[_to] = balances[_to].add(_tokens); emit Transfer(_from, _to, _tokens); } function transfer(address _to, uint _tokens) public returns (bool success) { checkTransfer(msg.sender, _tokens); _transfer(msg.sender, _to, _tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { checkTransfer(from, tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); _transfer(from, to, tokens); return true; } /// @notice checkTransfer ensures that `from` can send only unlocked tokens /// @notice this function is called for every transfer /// We unlock PURCHASED and BONUS tokens in 5 stages: /// after 28.09.2018 20% are unlocked /// after 30.11.2018 40% are unlocked /// after 31.01.2019 60% are unlocked /// after 29.03.2019 80% are unlocked /// after 31.05.2019 100% are unlocked function checkTransfer(address from, uint tokens) public view { uint newBalance = balances[from].sub(tokens); uint total = 0; if (now < unlockDate5) { require(now >= unlockDate1); uint frzdPercent = 0; if (now < unlockDate2) { frzdPercent = 80; } else if (now < unlockDate3) { frzdPercent = 60; } else if (now < unlockDate4) { frzdPercent = 40; } else { frzdPercent = 20; } total = freezed[from].mul(frzdPercent).div(100); require(newBalance >= total); } if (now < teamUnlock4 && teamFreezed[from] > 0) { uint p = 0; if (now < teamUnlock1) { p = 100; } else if (now < teamUnlock2) { p = 75; } else if (now < teamUnlock3) { p = 50; } else if (now < teamUnlock4) { p = 25; } total = total.add(teamFreezed[from].mul(p).div(100)); require(newBalance >= total); } } /// @return ($ received, ETH received, CST sold) function ICOStatus() public view returns (uint usd, uint eth, uint cst) { usd = presaleSold.mul(12).div(10**20) + crowdsaleSold.mul(16).div(10**20); usd = usd.add(preicoUSD); // pre-ico tokens return (usd, ethSold + preicoUSD.mul(10**8).div(ethRate), presaleSold + crowdsaleSold); } function checkICOStatus() public view returns(bool) { uint eth; uint cst; (, eth, cst) = ICOStatus(); uint dollarsRecvd = eth.mul(ethRate).div(10**8); // 26 228 800$ return dollarsRecvd >= 25228966 || (cst == presaleSupply + crowdsaleSupply) || now > crowdsaleEndTime; } bool icoClosed = false; function closeICO() public onlyOwner { require(!icoClosed); icoClosed = checkICOStatus(); } /// @notice by agreement, we can transfer $4.8M from bank /// after softcap is reached. /// @param _to wallet to send CST to /// @param _usd amount of dollars which is withdrawn uint bonusTransferred = 0; uint constant maxUSD = 4800000; function transferBonus(address _to, uint _usd) public onlyOwner { bonusTransferred = bonusTransferred.add(_usd); require(bonusTransferred <= maxUSD); uint cst = _usd.mul(100).mul(cstToMicro).div(12); // presale tariff presaleSold = presaleSold.add(cst); require(presaleSold <= presaleSupply); ethSold = ethSold.add(_usd.mul(10**8).div(ethRate)); _freezeTransfer(_to, cst); } /// @notice extend crowdsale for 2 weeks function prolongCrowdsale() public onlyOwnerAndDirector { require(now < crowdsaleEndTime); crowdsaleEndTime = crowdsaleHardEndTime; } // 100 000 000 Ether in dollars uint public ethRate = 0; uint public ethRateMax = 0; uint public ethLastUpdate = 0; function setETHRate(uint _rate) public onlyAdmin { require(ethRateMax == 0 || _rate < ethRateMax); ethRate = _rate; ethLastUpdate = now; } // 100 000 000 BTC in dollars uint public btcRate = 0; uint public btcRateMax = 0; uint public btcLastUpdate; function setBTCRate(uint _rate) public onlyAdmin { require(btcRateMax == 0 || _rate < btcRateMax); btcRate = _rate; btcLastUpdate = now; } /// @notice setMaxRate sets max rate for both BTC/ETH to soften /// negative consequences in case our backend gots hacked. function setMaxRate(uint ethMax, uint btcMax) public onlyOwnerAndDirector { ethRateMax = ethMax; btcRateMax = btcMax; } /// @notice _sellPresale checks CST purchases during crowdsale function _sellPresale(uint cst) private { require(cst >= bonusLevel0.mul(9950).div(10000)); presaleSold = presaleSold.add(cst); require(presaleSold <= presaleSupply); } /// @notice _sellCrowd checks CST purchases during crowdsale function _sellCrowd(uint cst, address _to) private { require(cst >= crowdsaleMinUSD); if (crowdsaleSold.add(cst) <= crowdsaleSupply) { crowdsaleSold = crowdsaleSold.add(cst); } else { presaleSold = presaleSold.add(crowdsaleSold).add(cst).sub(crowdsaleSupply); require(presaleSold <= presaleSupply); crowdsaleSold = crowdsaleSupply; } if (now < crowdsaleStartTime + 3 days) { if (whitemap[_to] >= cst) { whitemap[_to] -= cst; whitelistTokens -= cst; } else { require(crowdsaleSupply.add(presaleSupply).sub(presaleSold) >= crowdsaleSold.add(whitelistTokens)); } } } /// @notice addInvestorBonusInPercent is used for sending bonuses for big investors in % function addInvestorBonusInPercent(address _to, uint8 p) public onlyOwner { require(p > 0 && p <= 5); uint bonus = balances[_to].mul(p).div(100); investorGiven = investorGiven.add(bonus); require(investorGiven <= investorSupply); _freezeTransfer(_to, bonus); } /// @notice addInvestorBonusInTokens is used for sending bonuses for big investors in tokens function addInvestorBonusInTokens(address _to, uint tokens) public onlyOwner { _freezeTransfer(_to, tokens); investorGiven = investorGiven.add(tokens); require(investorGiven <= investorSupply); } function () payable public { purchaseWithETH(msg.sender); } /// @notice _freezeTranfer perform actual tokens transfer which /// will be freezed (see also checkTransfer() ) function _freezeTransfer(address _to, uint cst) private { _transfer(owner, _to, cst); freezed[_to] = freezed[_to].add(cst); } /// @notice _freezeTranfer perform actual tokens transfer which /// will be freezed (see also checkTransfer() ) function _teamTransfer(address _to, uint cst) private { _transfer(owner, _to, cst); teamFreezed[_to] = teamFreezed[_to].add(cst); } address public constant wuguAddr = 0x096ad02a48338CB9eA967a96062842891D195Af5; address public constant richardAddr = 0x411fB4D77EDc659e9838C21be72f55CC304C0cB8; mapping(address => address[]) promoterClients; mapping(address => mapping(address => uint)) promoterBonus; /// @notice withdrawPromoter transfers back to promoter /// all bonuses accumulated to current moment function withdrawPromoter() public { address _to = msg.sender; require(_to == wuguAddr || _to == richardAddr); uint usd; (usd,,) = ICOStatus(); // USD received - 5% must be more than softcap require(usd.mul(95).div(100) >= softcapUSD); uint bonus = 0; address[] memory clients = promoterClients[_to]; for(uint i = 0; i < clients.length; i++) { if (kyc[clients[i]]) { uint num = promoterBonus[_to][clients[i]]; delete promoterBonus[_to][clients[i]]; bonus += num; } } _to.transfer(bonus); } /// @notice cashBack will be used in case of failed ICO /// All partitipants can receive their ETH back function cashBack(address _to) public { uint usd; (usd,,) = ICOStatus(); // ICO fails if crowd-sale is ended and we have not yet reached soft-cap require(now > crowdsaleEndTime && usd < softcapUSD); require(ethSent[_to] > 0); delete ethSent[_to]; _to.transfer(ethSent[_to]); } /// @notice stores amount of ETH received by SC mapping(address => uint) ethSent; function purchaseWithETH(address _to) payable public { purchaseWithPromoter(_to, referral[msg.sender]); } /// @notice purchases tokens, which a send to `_to` with 5% returned to `_ref` /// @notice 5% return must work only on crowdsale function purchaseWithPromoter(address _to, address _ref) payable public { require(now >= presaleStartTime && now <= crowdsaleEndTime); require(!icoClosed); uint _wei = msg.value; uint cst; ethSent[msg.sender] = ethSent[msg.sender].add(_wei); ethSold = ethSold.add(_wei); // accept payment on presale only if it is more than 9997$ // actual check is performed in _sellPresale if (now < crowdsaleStartTime || approvedInvestors[msg.sender]) { require(kyc[msg.sender]); cst = _wei.mul(ethRate).div(12000000); // 1 CST = 0.12 $ on presale require(now < crowdsaleStartTime || cst >= bonusLevel100); _sellPresale(cst); /// we have only 2 recognized promoters if (_ref == wuguAddr || _ref == richardAddr) { promoterClients[_ref].push(_to); promoterBonus[_ref][_to] = _wei.mul(5).div(100); } } else { cst = _wei.mul(ethRate).div(16000000); // 1 CST = 0.16 $ on crowd-sale _sellCrowd(cst, _to); } _freezeTransfer(_to, cst); } /// @notice purchaseWithBTC is called from backend, where we convert /// BTC to ETH, and then assign tokens to purchaser, using BTC / $ exchange rate. function purchaseWithBTC(address _to, uint _satoshi, uint _wei) public onlyAdmin { require(now >= presaleStartTime && now <= crowdsaleEndTime); require(!icoClosed); ethSold = ethSold.add(_wei); uint cst; // accept payment on presale only if it is more than 9997$ // actual check is performed in _sellPresale if (now < crowdsaleStartTime || approvedInvestors[msg.sender]) { require(kyc[msg.sender]); cst = _satoshi.mul(btcRate.mul(10000)).div(12); // 1 CST = 0.12 $ on presale require(now < crowdsaleStartTime || cst >= bonusLevel100); _sellPresale(cst); } else { cst = _satoshi.mul(btcRate.mul(10000)).div(16); // 1 CST = 0.16 $ on presale _sellCrowd(cst, _to); } _freezeTransfer(_to, cst); } /// @notice withdrawFunds is called to send team bonuses after /// then end of the ICO bool withdrawCalled = false; function withdrawFunds() public onlyOwner { require(icoClosed && now >= teamETHUnlock1); require(!withdrawCalled); withdrawCalled = true; uint eth; (,eth,) = ICOStatus(); // pre-ico tokens are not in ethSold uint minus = bonusTransferred.mul(10**8).div(ethRate); uint team = ethSold.sub(minus); team = team.mul(15).div(100); uint ownerETH = 0; uint teamETH = 0; if (address(this).balance >= team) { teamETH = team; ownerETH = address(this).balance.sub(teamETH); } else { teamETH = address(this).balance; } teamETH1 = teamETH.div(3); teamETH2 = teamETH.div(3); teamETH3 = teamETH.sub(teamETH1).sub(teamETH2); // TODO multisig address(0x741A26104530998F625D15cbb9D58b01811d2CA7).transfer(ownerETH); } uint teamETH1 = 0; uint teamETH2 = 0; uint teamETH3 = 0; function withdrawTeam() public { require(now >= teamETHUnlock1); uint amount = 0; if (now < teamETHUnlock2) { amount = teamETH1; teamETH1 = 0; } else if (now < teamETHUnlock3) { amount = teamETH1 + teamETH2; teamETH1 = 0; teamETH2 = 0; } else { amount = teamETH1 + teamETH2 + teamETH3; teamETH1 = 0; teamETH2 = 0; teamETH3 = 0; } address(0xcdB7A51bA9af93a7BFfe08a31E4C6c5f9068A051).transfer(amount.mul(6).div(100)); // NuT address(0x57Bd10E12f789B74071d62550DaeB3765Ad83834).transfer(amount.mul(6).div(100)); // AlK address(0xEE74922eaF503463a8b20aFaD83d42F28D59f45d).transfer(amount.mul(6).div(100)); // StK address(0x58681a49A6f9D61eB368241a336628781afD5f87).transfer(amount.mul(2).div(100)); // DeP address(0x4c14DB011065e72C6E839bd826d101Ec09d3C530).transfer(amount.mul(2).div(100)); // VaB amount = amount.mul(78).div(100); address(0x1E21f744d91994D19f2a61041CD7cCA571185dfc).transfer(amount.mul(uint(255).mul(100).div(96)).div(1000)); // ArK address(0x4CE4Ea57c40bBa26B7b799d5e0b4cd063B034c8A).transfer(amount.mul(uint(185).mul(100).div(96)).div(1000)); // ViT address(0xdCd8a8e561d23Ca710f23E7612F1D4E0dE9bde83).transfer(amount.mul(uint(25).mul(100).div(96)).div(1000)); // SeT address(0x0dFFA8624A1f512b8dcDE807F8B0Eab68672e5D5).transfer(amount.mul(uint(250).mul(100).div(96)).div(1000)); // AnD address(0xE091180bB0C284AA0Bd15C6888A41aba45c54AF0).transfer(amount.mul(uint(245).mul(100).div(96)).div(1000)); // VlM } /// @notice doAirdrop is called when we launch airdrop. /// @notice airdrop tokens has their own supply. uint dropped = 0; function doAirdrop(address[] members, uint[] tokens) public onlyOwnerAndDirector { require(members.length == tokens.length); for(uint i = 0; i < members.length; i++) { _freezeTransfer(members[i], tokens[i]); dropped = dropped.add(tokens[i]); } require(dropped <= bountySupply); } mapping(address => uint) public whitemap; uint public whitelistTokens = 0; /// @notice addWhitelistMember is used to whitelist participant. /// This means, that for the first 3 days of crowd-sale `_tokens` CST /// will be reserved for him. function addWhitelistMember(address[] _mem, uint[] _tokens) public onlyAdmin { require(_mem.length == _tokens.length); for(uint i = 0; i < _mem.length; i++) { whitelistTokens = whitelistTokens.sub(whitemap[_mem[i]]).add(_tokens[i]); whitemap[_mem[i]] = _tokens[i]; } } uint public adviserSold = 0; /// @notice transferAdviser is called to send tokens to advisers. /// @notice adviser tokens have their own supply function transferAdviser(address[] _adv, uint[] _tokens) public onlyOwnerAndDirector { require(_adv.length == _tokens.length); for (uint i = 0; i < _adv.length; i++) { adviserSold = adviserSold.add(_tokens[i]); _freezeTransfer(_adv[i], _tokens[i]); } require(adviserSold <= adviserSupply); } mapping(address => bool) approvedInvestors; function approveInvestor(address _addr) public onlyOwner { approvedInvestors[_addr] = true; } }
@notice checkTransfer ensures that `from` can send only unlocked tokens @notice this function is called for every transfer We unlock PURCHASED and BONUS tokens in 5 stages: after 28.09.2018 20% are unlocked after 30.11.2018 40% are unlocked after 31.01.2019 60% are unlocked after 29.03.2019 80% are unlocked after 31.05.2019 100% are unlocked
function checkTransfer(address from, uint tokens) public view { uint newBalance = balances[from].sub(tokens); uint total = 0; if (now < unlockDate5) { require(now >= unlockDate1); uint frzdPercent = 0; if (now < unlockDate2) { frzdPercent = 80; frzdPercent = 60; frzdPercent = 40; frzdPercent = 20; } total = freezed[from].mul(frzdPercent).div(100); require(newBalance >= total); } if (now < teamUnlock4 && teamFreezed[from] > 0) { uint p = 0; if (now < teamUnlock1) { p = 100; p = 75; p = 50; p = 25; } total = total.add(teamFreezed[from].mul(p).div(100)); require(newBalance >= total); } }
2,343,239
[ 1, 1893, 5912, 11932, 716, 1375, 2080, 68, 848, 1366, 1338, 25966, 2430, 225, 333, 445, 353, 2566, 364, 3614, 7412, 1660, 7186, 26345, 1792, 4429, 40, 471, 605, 673, 3378, 2430, 316, 1381, 20298, 30, 1839, 9131, 18, 5908, 18, 21849, 4200, 9, 854, 25966, 1839, 5196, 18, 2499, 18, 21849, 8063, 9, 854, 25966, 1839, 8231, 18, 1611, 18, 6734, 29, 4752, 9, 854, 25966, 1839, 12899, 18, 4630, 18, 6734, 29, 8958, 9, 854, 25966, 1839, 8231, 18, 6260, 18, 6734, 29, 2130, 9, 854, 25966, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 866, 5912, 12, 2867, 628, 16, 2254, 2430, 13, 1071, 1476, 288, 203, 3639, 2254, 394, 13937, 273, 324, 26488, 63, 2080, 8009, 1717, 12, 7860, 1769, 203, 3639, 2254, 2078, 273, 374, 31, 203, 3639, 309, 261, 3338, 411, 7186, 1626, 25, 13, 288, 203, 5411, 2583, 12, 3338, 1545, 7186, 1626, 21, 1769, 203, 5411, 2254, 3812, 94, 72, 8410, 273, 374, 31, 203, 5411, 309, 261, 3338, 411, 7186, 1626, 22, 13, 288, 203, 7734, 3812, 94, 72, 8410, 273, 8958, 31, 203, 7734, 3812, 94, 72, 8410, 273, 4752, 31, 203, 7734, 3812, 94, 72, 8410, 273, 8063, 31, 203, 7734, 3812, 94, 72, 8410, 273, 4200, 31, 203, 5411, 289, 203, 5411, 2078, 273, 4843, 94, 329, 63, 2080, 8009, 16411, 12, 4840, 94, 72, 8410, 2934, 2892, 12, 6625, 1769, 203, 5411, 2583, 12, 2704, 13937, 1545, 2078, 1769, 203, 3639, 289, 203, 540, 203, 3639, 309, 261, 3338, 411, 5927, 7087, 24, 597, 5927, 9194, 94, 329, 63, 2080, 65, 405, 374, 13, 288, 203, 5411, 2254, 293, 273, 374, 31, 203, 5411, 309, 261, 3338, 411, 5927, 7087, 21, 13, 288, 203, 7734, 293, 273, 2130, 31, 203, 7734, 293, 273, 18821, 31, 203, 7734, 293, 273, 6437, 31, 203, 7734, 293, 273, 6969, 31, 203, 5411, 289, 203, 5411, 2078, 273, 2078, 18, 1289, 12, 10035, 9194, 94, 329, 63, 2080, 8009, 16411, 12, 84, 2934, 2892, 12, 6625, 10019, 203, 5411, 2583, 12, 2704, 13937, 1545, 2078, 1769, 203, 3639, 289, 203, 2 ]
pragma solidity 0.4.26; import './interfaces/IBancorXUpgrader.sol'; import './interfaces/IBancorX.sol'; import '../token/interfaces/ISmartTokenController.sol'; import '../utility/ContractRegistryClient.sol'; import '../utility/SafeMath.sol'; import '../utility/TokenHolder.sol'; import '../token/interfaces/ISmartToken.sol'; /** * @dev The BancorX contract allows cross chain token transfers. * * There are two processes that take place in the contract - * - Initiate a cross chain transfer to a target blockchain (locks tokens from the caller account on Ethereum) * - Report a cross chain transfer initiated on a source blockchain (releases tokens to an account on Ethereum) * * Reporting cross chain transfers works similar to standard multisig contracts, meaning that multiple * callers are required to report a transfer before tokens are released to the target account. */ contract BancorX is IBancorX, TokenHolder, ContractRegistryClient { using SafeMath for uint256; // represents a transaction on another blockchain where tokens were destroyed/locked struct Transaction { uint256 amount; bytes32 fromBlockchain; address to; uint8 numOfReports; bool completed; } uint16 public version = 3; uint256 public maxLockLimit; // the maximum amount of tokens that can be locked in one transaction uint256 public maxReleaseLimit; // the maximum amount of tokens that can be released in one transaction uint256 public minLimit; // the minimum amount of tokens that can be transferred in one transaction uint256 public prevLockLimit; // the lock limit *after* the last transaction uint256 public prevReleaseLimit; // the release limit *after* the last transaction uint256 public limitIncPerBlock; // how much the limit increases per block uint256 public prevLockBlockNumber; // the block number of the last lock transaction uint256 public prevReleaseBlockNumber; // the block number of the last release transaction uint256 public minRequiredReports; // minimum number of required reports to release tokens IERC20Token public token; // erc20 token or smart token bool public isSmartToken; // false - erc20 token; true - smart token bool public xTransfersEnabled = true; // true if x transfers are enabled, false if not bool public reportingEnabled = true; // true if reporting is enabled, false if not // txId -> Transaction mapping (uint256 => Transaction) public transactions; // xTransferId -> txId mapping (uint256 => uint256) public transactionIds; // txId -> reporter -> true if reporter already reported txId mapping (uint256 => mapping (address => bool)) public reportedTxs; // address -> true if address is reporter mapping (address => bool) public reporters; /** * @dev triggered when tokens are locked in smart contract * * @param _from wallet address that the tokens are locked from * @param _amount amount locked */ event TokensLock( address indexed _from, uint256 _amount ); /** * @dev triggered when tokens are released by the smart contract * * @param _to wallet address that the tokens are released to * @param _amount amount released */ event TokensRelease( address indexed _to, uint256 _amount ); /** * @dev triggered when xTransfer is successfully called * * @param _from wallet address that initiated the xtransfer * @param _toBlockchain target blockchain * @param _to target wallet * @param _amount transfer amount * @param _id xtransfer id */ event XTransfer( address indexed _from, bytes32 _toBlockchain, bytes32 indexed _to, uint256 _amount, uint256 _id ); /** * @dev triggered when report is successfully submitted * * @param _reporter reporter wallet * @param _fromBlockchain source blockchain * @param _txId tx id on the source blockchain * @param _to target wallet * @param _amount transfer amount * @param _xTransferId xtransfer id */ event TxReport( address indexed _reporter, bytes32 _fromBlockchain, uint256 _txId, address _to, uint256 _amount, uint256 _xTransferId ); /** * @dev triggered when final report is successfully submitted * * @param _to target wallet * @param _id xtransfer id */ event XTransferComplete( address _to, uint256 _id ); /** * @dev initializes a new BancorX instance * * @param _maxLockLimit maximum amount of tokens that can be locked in one transaction * @param _maxReleaseLimit maximum amount of tokens that can be released in one transaction * @param _minLimit minimum amount of tokens that can be transferred in one transaction * @param _limitIncPerBlock how much the limit increases per block * @param _minRequiredReports minimum number of reporters to report transaction before tokens can be released * @param _registry address of contract registry * @param _token erc20 token or smart token * @param _isSmartToken false - erc20 token; true - smart token */ constructor( uint256 _maxLockLimit, uint256 _maxReleaseLimit, uint256 _minLimit, uint256 _limitIncPerBlock, uint256 _minRequiredReports, IContractRegistry _registry, IERC20Token _token, bool _isSmartToken ) ContractRegistryClient(_registry) public { // the maximum limits, minimum limit, and limit increase per block maxLockLimit = _maxLockLimit; maxReleaseLimit = _maxReleaseLimit; minLimit = _minLimit; limitIncPerBlock = _limitIncPerBlock; minRequiredReports = _minRequiredReports; // previous limit is _maxLimit, and previous block number is current block number prevLockLimit = _maxLockLimit; prevReleaseLimit = _maxReleaseLimit; prevLockBlockNumber = block.number; prevReleaseBlockNumber = block.number; token = _token; isSmartToken = _isSmartToken; } // validates that the caller is a reporter modifier isReporter { require(reporters[msg.sender]); _; } // allows execution only when x transfers are enabled modifier whenXTransfersEnabled { require(xTransfersEnabled); _; } // allows execution only when reporting is enabled modifier whenReportingEnabled { require(reportingEnabled); _; } /** * @dev setter * * @param _maxLockLimit new maxLockLimit */ function setMaxLockLimit(uint256 _maxLockLimit) public ownerOnly { maxLockLimit = _maxLockLimit; } /** * @dev setter * * @param _maxReleaseLimit new maxReleaseLimit */ function setMaxReleaseLimit(uint256 _maxReleaseLimit) public ownerOnly { maxReleaseLimit = _maxReleaseLimit; } /** * @dev setter * * @param _minLimit new minLimit */ function setMinLimit(uint256 _minLimit) public ownerOnly { minLimit = _minLimit; } /** * @dev setter * * @param _limitIncPerBlock new limitIncPerBlock */ function setLimitIncPerBlock(uint256 _limitIncPerBlock) public ownerOnly { limitIncPerBlock = _limitIncPerBlock; } /** * @dev setter * * @param _minRequiredReports new minRequiredReports */ function setMinRequiredReports(uint256 _minRequiredReports) public ownerOnly { minRequiredReports = _minRequiredReports; } /** * @dev allows the owner to set/remove reporters * * @param _reporter reporter whos status is to be set * @param _active true if the reporter is approved, false otherwise */ function setReporter(address _reporter, bool _active) public ownerOnly { reporters[_reporter] = _active; } /** * @dev allows the owner enable/disable the xTransfer method * * @param _enable true to enable, false to disable */ function enableXTransfers(bool _enable) public ownerOnly { xTransfersEnabled = _enable; } /** * @dev allows the owner enable/disable the reportTransaction method * * @param _enable true to enable, false to disable */ function enableReporting(bool _enable) public ownerOnly { reportingEnabled = _enable; } /** * @dev upgrades the contract to the latest version * can only be called by the owner * note that the owner needs to call acceptOwnership on the new contract after the upgrade * * @param _reporters new list of reporters */ function upgrade(address[] _reporters) public ownerOnly { IBancorXUpgrader bancorXUpgrader = IBancorXUpgrader(addressOf(BANCOR_X_UPGRADER)); transferOwnership(bancorXUpgrader); bancorXUpgrader.upgrade(version, _reporters); acceptOwnership(); } /** * @dev claims tokens from msg.sender to be converted to tokens on another blockchain * * @param _toBlockchain blockchain on which tokens will be issued * @param _to address to send the tokens to * @param _amount the amount of tokens to transfer */ function xTransfer(bytes32 _toBlockchain, bytes32 _to, uint256 _amount) public whenXTransfersEnabled { // get the current lock limit uint256 currentLockLimit = getCurrentLockLimit(); // require that; minLimit <= _amount <= currentLockLimit require(_amount >= minLimit && _amount <= currentLockLimit); lockTokens(_amount); // set the previous lock limit and block number prevLockLimit = currentLockLimit.sub(_amount); prevLockBlockNumber = block.number; // emit XTransfer event with id of 0 emit XTransfer(msg.sender, _toBlockchain, _to, _amount, 0); } /** * @dev claims tokens from msg.sender to be converted to tokens on another blockchain * * @param _toBlockchain blockchain on which tokens will be issued * @param _to address to send the tokens to * @param _amount the amount of tokens to transfer * @param _id pre-determined unique (if non zero) id which refers to this transaction */ function xTransfer(bytes32 _toBlockchain, bytes32 _to, uint256 _amount, uint256 _id) public whenXTransfersEnabled { // get the current lock limit uint256 currentLockLimit = getCurrentLockLimit(); // require that; minLimit <= _amount <= currentLockLimit require(_amount >= minLimit && _amount <= currentLockLimit); lockTokens(_amount); // set the previous lock limit and block number prevLockLimit = currentLockLimit.sub(_amount); prevLockBlockNumber = block.number; // emit XTransfer event emit XTransfer(msg.sender, _toBlockchain, _to, _amount, _id); } /** * @dev allows reporter to report transaction which occured on another blockchain * * @param _fromBlockchain blockchain in which tokens were destroyed * @param _txId transactionId of transaction thats being reported * @param _to address to receive tokens * @param _amount amount of tokens destroyed on another blockchain * @param _xTransferId unique (if non zero) pre-determined id (unlike _txId which is determined after the transactions been mined) */ function reportTx( bytes32 _fromBlockchain, uint256 _txId, address _to, uint256 _amount, uint256 _xTransferId ) public isReporter whenReportingEnabled { // require that the transaction has not been reported yet by the reporter require(!reportedTxs[_txId][msg.sender]); // set reported as true reportedTxs[_txId][msg.sender] = true; Transaction storage txn = transactions[_txId]; // If the caller is the first reporter, set the transaction details if (txn.numOfReports == 0) { txn.to = _to; txn.amount = _amount; txn.fromBlockchain = _fromBlockchain; if (_xTransferId != 0) { // verify uniqueness of xTransfer id to prevent overwriting require(transactionIds[_xTransferId] == 0); transactionIds[_xTransferId] = _txId; } } else { // otherwise, verify transaction details require(txn.to == _to && txn.amount == _amount && txn.fromBlockchain == _fromBlockchain); if (_xTransferId != 0) { require(transactionIds[_xTransferId] == _txId); } } // increment the number of reports txn.numOfReports++; emit TxReport(msg.sender, _fromBlockchain, _txId, _to, _amount, _xTransferId); // if theres enough reports, try to release tokens if (txn.numOfReports >= minRequiredReports) { require(!transactions[_txId].completed); // set the transaction as completed transactions[_txId].completed = true; emit XTransferComplete(_to, _xTransferId); releaseTokens(_to, _amount); } } /** * @dev gets x transfer amount by xTransferId (not txId) * * @param _xTransferId unique (if non zero) pre-determined id (unlike _txId which is determined after the transactions been broadcasted) * @param _for address corresponding to xTransferId * * @return amount that was sent in xTransfer corresponding to _xTransferId */ function getXTransferAmount(uint256 _xTransferId, address _for) public view returns (uint256) { // xTransferId -> txId -> Transaction Transaction storage transaction = transactions[transactionIds[_xTransferId]]; // verify that the xTransferId is for _for require(transaction.to == _for); return transaction.amount; } /** * @dev method for calculating current lock limit * * @return the current maximum limit of tokens that can be locked */ function getCurrentLockLimit() public view returns (uint256) { // prevLockLimit + ((currBlockNumber - prevLockBlockNumber) * limitIncPerBlock) uint256 currentLockLimit = prevLockLimit.add(((block.number).sub(prevLockBlockNumber)).mul(limitIncPerBlock)); if (currentLockLimit > maxLockLimit) return maxLockLimit; return currentLockLimit; } /** * @dev method for calculating current release limit * * @return the current maximum limit of tokens that can be released */ function getCurrentReleaseLimit() public view returns (uint256) { // prevReleaseLimit + ((currBlockNumber - prevReleaseBlockNumber) * limitIncPerBlock) uint256 currentReleaseLimit = prevReleaseLimit.add(((block.number).sub(prevReleaseBlockNumber)).mul(limitIncPerBlock)); if (currentReleaseLimit > maxReleaseLimit) return maxReleaseLimit; return currentReleaseLimit; } /** * @dev claims and locks tokens from msg.sender to be converted to tokens on another blockchain * * @param _amount the amount of tokens to lock */ function lockTokens(uint256 _amount) private { if (isSmartToken) ISmartTokenController(ISmartToken(token).owner()).claimTokens(msg.sender, _amount); else token.transferFrom(msg.sender, address(this), _amount); emit TokensLock(msg.sender, _amount); } /** * @dev private method to release tokens held by the contract * * @param _to the address to release tokens to * @param _amount the amount of tokens to release */ function releaseTokens(address _to, uint256 _amount) private { // get the current release limit uint256 currentReleaseLimit = getCurrentReleaseLimit(); require(_amount >= minLimit && _amount <= currentReleaseLimit); // update the previous release limit and block number prevReleaseLimit = currentReleaseLimit.sub(_amount); prevReleaseBlockNumber = block.number; // no need to require, reverts on failure token.transfer(_to, _amount); emit TokensRelease(_to, _amount); } }
* @dev setter @param _minRequiredReports new minRequiredReports/
function setMinRequiredReports(uint256 _minRequiredReports) public ownerOnly { minRequiredReports = _minRequiredReports; }
986,543
[ 1, 18062, 225, 389, 1154, 3705, 18631, 565, 394, 1131, 3705, 18631, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 27724, 3705, 18631, 12, 11890, 5034, 389, 1154, 3705, 18631, 13, 1071, 3410, 3386, 288, 203, 3639, 1131, 3705, 18631, 273, 389, 1154, 3705, 18631, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x6e34d8d84764d40f6d7b39cd569fd017bf53177d //Contract name: Skraps //Balance: 0 Ether //Verification Date: 1/8/2018 //Transacion Count: 6 // CODE STARTS HERE pragma solidity 0.4.19; contract Owned { address public owner; address public candidate; function Owned() internal { owner = msg.sender; } // A functions uses the modifier can be invoked only by the owner of the contract modifier onlyOwner { require(owner == msg.sender); _; } // To change the owner of the contract, putting the candidate function changeOwner(address _owner) onlyOwner public { candidate = _owner; } // The candidate must call this function to accept the proposal for the transfer of the rights of contract ownership function acceptOwner() public { require(candidate != address(0)); require(candidate == msg.sender); owner = candidate; delete candidate; } } // Functions for safe operation with input values (subtraction and addition) library SafeMath { function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } } // ERC20 interface https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md contract ERC20 { uint public totalSupply; function balanceOf(address who) public constant returns (uint balance); function allowance(address owner, address spender) public constant returns (uint remaining); function transfer(address to, uint value) public returns (bool success); function transferFrom(address from, address to, uint value) public returns (bool success); function approve(address spender, uint value) public returns (bool success); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Skraps is ERC20, Owned { using SafeMath for uint; string public name = "Skraps"; string public symbol = "SKRP"; uint8 public decimals = 18; uint public totalSupply; uint private endOfFreeze = 1518912000; // Sun, 18 Feb 2018 00:00:00 GMT mapping (address => uint) private balances; mapping (address => mapping (address => uint)) private allowed; function balanceOf(address _who) public constant returns (uint) { return balances[_who]; } function allowance(address _owner, address _spender) public constant returns (uint remaining) { return allowed[_owner][_spender]; } function Skraps() public { totalSupply = 110000000 * 1 ether; balances[msg.sender] = totalSupply; Transfer(0, msg.sender, totalSupply); } function transfer(address _to, uint _value) public returns (bool success) { require(_to != address(0)); require(now >= endOfFreeze || msg.sender == owner); require(balances[msg.sender] >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) public returns (bool success) { require(_to != address(0)); require(now >= endOfFreeze || msg.sender == owner); require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public returns (bool success) { require(_spender != address(0)); require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // Withdraws tokens from the contract if they accidentally or on purpose was it placed there function withdrawTokens(uint _value) public onlyOwner { require(balances[this] > 0 && balances[this] >= _value); balances[this] = balances[this].sub(_value); balances[msg.sender] = balances[msg.sender].add(_value); Transfer(this, msg.sender, _value); } }
Sun, 18 Feb 2018 00:00:00 GMT
uint private endOfFreeze = 1518912000;
5,377,770
[ 1, 29636, 16, 6549, 5782, 70, 14863, 9631, 30, 713, 30, 713, 21706, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 3238, 20706, 9194, 8489, 273, 4711, 29426, 2138, 3784, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x5536Fc1eb2D03F5c1cE4AF4bb7D8B48641f3a48a/sources/contracts/Contract.sol
Swaps tokens for eth
function swapTokenToEth(uint256 _tokensSold, uint256 _minEth) public { uint256 _reservedTokens = getTokensInContract(); uint256 ethBought = getAmountOfTokens( _tokensSold, _reservedTokens, address(this).balance ); require(ethBought >= _minEth, "insufficient output amount"); ERC20(token).transferFrom( msg.sender, address(this), _tokensSold ); payable(msg.sender).transfer(ethBought); }
11,628,846
[ 1, 6050, 6679, 2430, 364, 13750, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7720, 1345, 774, 41, 451, 12, 11890, 5034, 389, 7860, 55, 1673, 16, 2254, 5034, 389, 1154, 41, 451, 13, 1071, 288, 203, 3639, 2254, 5034, 389, 18898, 5157, 273, 18349, 382, 8924, 5621, 203, 3639, 2254, 5034, 13750, 13809, 9540, 273, 24418, 951, 5157, 12, 203, 3639, 389, 7860, 55, 1673, 16, 203, 3639, 389, 18898, 5157, 16, 203, 3639, 1758, 12, 2211, 2934, 12296, 203, 3639, 11272, 203, 3639, 2583, 12, 546, 13809, 9540, 1545, 389, 1154, 41, 451, 16, 315, 2679, 11339, 876, 3844, 8863, 203, 3639, 4232, 39, 3462, 12, 2316, 2934, 13866, 1265, 12, 203, 5411, 1234, 18, 15330, 16, 7010, 5411, 1758, 12, 2211, 3631, 7010, 5411, 389, 7860, 55, 1673, 203, 5411, 11272, 203, 3639, 8843, 429, 12, 3576, 18, 15330, 2934, 13866, 12, 546, 13809, 9540, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-11-18 */ pragma solidity ^0.6.2; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @title Timelock * @dev A PEAKDEFI holder contract that should release its token balance immediately after the certain date. */ contract Timelock { using SafeERC20 for IERC20; // PEAKDEFI token interface IERC20 private constant _token = IERC20(0x630d98424eFe0Ea27fB1b3Ab7741907DFFEaAd78); // beneficiary of tokens after they are released address private _beneficiary; // timestamp when token release is enabled uint256 private _releaseTime; // ----------------------------------------------------------------------- // CONSTRUCTOR // ----------------------------------------------------------------------- /** * @dev Creates a timelock contract that holds its balance of any ERC20 token to the * beneficiary, and release immediately after finish of the certain date. * @param beneficiary address to whom locked tokens are transferred * @param releaseTime the time (as Unix time) when tokens should be unlocked */ constructor (address beneficiary, uint256 releaseTime) public { // solhint-disable-next-line not-rely-on-time require(releaseTime > block.timestamp, "Timelock: release time is before current time"); _beneficiary = beneficiary; _releaseTime = releaseTime; } fallback () external payable {} receive () external payable {} // ----------------------------------------------------------------------- // SETTERS // ----------------------------------------------------------------------- /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() external { // solhint-disable-next-line not-rely-on-time require(block.timestamp >= _releaseTime, "Timelock: current time is before release time"); uint256 amount = _token.balanceOf(address(this)); require(amount > 0, "Timelock: no tokens to release"); _token.safeTransfer(_beneficiary, amount); } // ----------------------------------------------------------------------- // GETTERS // ----------------------------------------------------------------------- /** * @return the token being held. */ function token() external pure returns (IERC20) { return _token; } /** * @return the beneficiary of the tokens. */ function beneficiary() external view returns (address) { return _beneficiary; } /** * @return the time when the tokens are released. */ function releaseTime() external view returns (uint256) { return _releaseTime; } }
* @notice Transfers tokens held by timelock to beneficiary./ solhint-disable-next-line not-rely-on-time
function release() external { require(block.timestamp >= _releaseTime, "Timelock: current time is before release time"); uint256 amount = _token.balanceOf(address(this)); require(amount > 0, "Timelock: no tokens to release"); _token.safeTransfer(_beneficiary, amount); }
2,136,378
[ 1, 1429, 18881, 2430, 15770, 635, 1658, 292, 975, 358, 27641, 74, 14463, 814, 18, 19, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 486, 17, 266, 715, 17, 265, 17, 957, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3992, 1435, 3903, 288, 203, 3639, 2583, 12, 2629, 18, 5508, 1545, 389, 9340, 950, 16, 315, 10178, 292, 975, 30, 783, 813, 353, 1865, 3992, 813, 8863, 203, 203, 3639, 2254, 5034, 3844, 273, 389, 2316, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 10178, 292, 975, 30, 1158, 2430, 358, 3992, 8863, 203, 203, 3639, 389, 2316, 18, 4626, 5912, 24899, 70, 4009, 74, 14463, 814, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x0562E8fec9D5784063AB70786C191f64E0D42980/sources/AIROCHAIN.sol
set as development wallet
developmentWallet = address(0xcB635c132E37618E2c6903a7c4d7cf6534cf7125);
4,293,009
[ 1, 542, 487, 17772, 9230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 17772, 16936, 273, 1758, 12, 20, 6511, 38, 4449, 25, 71, 22152, 41, 6418, 26, 2643, 41, 22, 71, 8148, 4630, 69, 27, 71, 24, 72, 27, 8522, 9222, 5026, 8522, 27, 18473, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.0; contract Mortal { /* Define variable owner of the type address*/ address owner; /* this function is executed at initialization and sets the owner of the contract */ function Mortal() { owner = msg.sender; } /* Function to recover the funds on the contract */ function kill() { if (msg.sender == owner) selfdestruct(owner); } modifier onlyOwner { require(msg.sender == owner); _; } } // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity >=0.4.1;//please import oraclizeAPI_pre0.4.sol when solidity < 0.4.x contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id); function getPrice(string _datasource) returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); function useCoupon(string _coupon); function setProofType(byte _proofType); function setConfig(bytes32 _config); function setCustomGasPrice(uint _gasPrice); function randomDS_getSessionPubKeyHash() returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() returns (address _addr); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory buf, uint capacity) internal constant { if(capacity % 32 != 0) capacity += 32 - (capacity % 32); // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory buf, uint capacity) private constant { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private constant returns(uint) { if(a > b) { return a; } return b; } /** * @dev Appends a byte array to the end of the buffer. Reverts if doing so * would exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, bytes data) internal constant returns(buffer memory) { if(data.length + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, data.length) * 2); } uint dest; uint src; uint len = data.length; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + buffer length + sizeof(buffer length) dest := add(add(bufptr, buflen), 32) // Update buffer length mstore(bufptr, add(buflen, mload(data))) src := add(data, 32) } // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; } /** * @dev Appends a byte to the end of the buffer. Reverts if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, uint8 data) internal constant { if(buf.buf.length + 1 > buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) let dest := add(add(bufptr, buflen), 32) mstore8(dest, data) // Update buffer length mstore(bufptr, add(buflen, 1)) } } /** * @dev Appends a byte to the end of the buffer. Reverts if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal constant returns(buffer memory) { if(len + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, len) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) + len let dest := add(add(bufptr, buflen), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length mstore(bufptr, add(buflen, len)) } return buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function shl8(uint8 x, uint8 y) private constant returns (uint8) { return x * (2 ** y); } function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private constant { if(value <= 23) { buf.append(uint8(shl8(major, 5) | value)); } else if(value <= 0xFF) { buf.append(uint8(shl8(major, 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.append(uint8(shl8(major, 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.append(uint8(shl8(major, 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.append(uint8(shl8(major, 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private constant { buf.append(uint8(shl8(major, 5) | 31)); } function encodeUInt(Buffer.buffer memory buf, uint value) internal constant { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(Buffer.buffer memory buf, int value) internal constant { if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(Buffer.buffer memory buf, bytes value) internal constant { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeString(Buffer.buffer memory buf, string value) internal constant { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(Buffer.buffer memory buf) internal constant { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory buf) internal constant { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory buf) internal constant { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); oraclize.useCoupon(code); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) { } function oraclize_useCoupon(string code) oraclizeAPI internal { oraclize.useCoupon(code); } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_setConfig(bytes32 config) oraclizeAPI internal { return oraclize.setConfig(config); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } using CBOR for Buffer.buffer; function stra2cbor(string[] arr) internal constant returns (bytes) { Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeString(arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] arr) internal constant returns (bytes) { Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeBytes(arr[i]); } buf.endSequence(); return buf.buf; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ if ((_nbytes == 0)||(_nbytes > 32)) throw; // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, sha3(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(sha3(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(sha3(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = 1; //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) throw; _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){ bool match_ = true; if (prefix.length != n_random_bytes) throw; for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) { uint minLength = length + toOffset; if (to.length < minLength) { // Buffer too small throw; // Should be a better way? } // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> contract cosmicDice is usingOraclize, Mortal { uint constant minbet = 0.01 ether; uint constant maxbet = 1 ether; uint public totalPlayCount = 0; //total game play count mapping(address => uint) public playerPlayCount; //player play count mapping(uint => address) public player; //player mapping mapping(address => uint) public ln; //user chosen lucky number mapping(address => uint) public prn; //psuedo random number mapping(address => uint) public trn; //true random number mapping(address => uint) public crn; //combined random number mapping(address => uint) public payout; //payout calculated for each play mapping(address => uint) public nval; //max n value mapping(address => uint) public multiplier; //multuplier for win payout uint public bl; //another prn function cosmicDice() public payable { } function() public payable { } function deposit() public payable { } function withdraw(uint _withdrawAmount) public { require(msg.sender == owner); msg.sender.transfer(_withdrawAmount); //withdraw amount must be in Wei and inside double quotes so the javascript solidity browser can read it as a BigNumber } event message(string result, uint ln, uint crn); function play(uint _luckynum, uint _trueRand, uint _nval) payable { require(msg.value >= minbet && msg.value <= maxbet); require(_nval==2||_nval==6||_nval==10||_nval==20||_nval==50||_nval==100||_nval==500||_nval==1000); totalPlayCount ++; // index play count update(); // update the psuedo random number from wolfram alpha bl = uint(sha3(block.timestamp)); player[totalPlayCount] = msg.sender; playerPlayCount[player[totalPlayCount]] ++; //index player play count if (_nval == 2) { multiplier[player[totalPlayCount]] = (300*_nval)/4; } else { multiplier[player[totalPlayCount]] = 100*_nval/2; } nval[player[totalPlayCount]] = _nval; payout[player[totalPlayCount]] = (msg.value * multiplier[player[totalPlayCount]])/100; // set the payout multiplier ln[player[totalPlayCount]] = _luckynum; trn[player[totalPlayCount]] = _trueRand; prn[player[totalPlayCount]] = randnum; crn[player[totalPlayCount]] = ((trn[player[totalPlayCount]] + prn[player[totalPlayCount]] + bl) % nval[player[totalPlayCount]]) + 1; compareNums(); } function compareNums() private { if (ln[player[totalPlayCount]] == crn[player[totalPlayCount]]) { //return true; emit message("Congratulations, you win!", ln[player[totalPlayCount]], crn[player[totalPlayCount]]); player[totalPlayCount].transfer(payout[player[totalPlayCount]]); payout[player[totalPlayCount]] = 0; } else { //return false; emit message("Sorry, try again.", ln[player[totalPlayCount]], crn[player[totalPlayCount]]); } } /// Begin oraclize uint public randnum; uint public gasPrice; event newOraclizeQuery(string description); event newRandNum(string rnum); function setCustomGasPrice(uint _gasPrice) public payable{ require(msg.sender == owner); gasPrice = _gasPrice; oraclize_setCustomGasPrice(gasPrice); // testing } function __callback(bytes32 myid, string result) { if (msg.sender != oraclize_cbAddress()) revert(); emit newRandNum(result); randnum = parseInt(result); } function update() payable { emit newOraclizeQuery("Oraclize query was sent, standing by for the answer.."); // oraclize_query("URL", "json(https://qrng.anu.edu.au/API/jsonI.php?length=1&type=uint8).data[0]"); oraclize_query("WolframAlpha", "random number between 1 and 10"); } }
payout calculated for each play
mapping(address => uint) public payout;
1,512,776
[ 1, 84, 2012, 8894, 364, 1517, 6599, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 2254, 13, 1071, 293, 2012, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x976C6e1F5E142f7785B893f8f4eE286Da05Ce11A/sources/browser/lynctokensale.sol
Enable SafeMathEventsMappingsBuyers listOn deployment
contract LYNCTokenSale { using SafeMath for uint256; address payable owner; address public contractAddress; uint256 public tokensSold; uint256 public priceETH; bool public saleEnabled = false; LYNCToken public tokenContract; event Sell(address _buyer, uint256 _amount); mapping(address => uint256) public purchaseData; address[] userIndex; constructor(LYNCToken _tokenContract, uint256 _priceETH) { owner = msg.sender; tokenContract = _tokenContract; contractAddress = address(this); priceETH = _priceETH; } function buyTokens(uint256 _ethSent) public payable { require(saleEnabled == true, "The LYNC Initial Token Offering will commence on the 28th of September @ 5PM UTC"); require(_ethSent <= maxBuyETH.mul(SCALAR), "Exceeded maximum purchase per transaction"); require(_ethSent >= 1e17, "Minimum purchase per transaction is 0.1 ETH"); uint256 _priceETH = priceETH.mul(SCALAR); if (tokensSold < (100000 * SCALAR)) { uint256 _tokenPrice = tokenPrice.mul(SCALAR); uint256 _tokensPerETH = _priceETH.div(_tokenPrice); uint256 _numberOfTokens = _ethSent.mul(_tokensPerETH); uint256 _tokensRemaining = (100000 * SCALAR).sub(tokensSold); require(_numberOfTokens < _tokensRemaining.add(tokenOverFlow), "Not enough tokens remain in Round 1"); if(purchaseData[msg.sender] == 0) { userIndex.push(msg.sender); } purchaseData[msg.sender] = purchaseData[msg.sender].add(_numberOfTokens); tokensSold = tokensSold.add(_numberOfTokens); emit Sell(msg.sender, _numberOfTokens); if(tokensSold > 100000 * SCALAR) { } uint256 _numberOfTokens = _ethSent.mul(_tokensPerETH); if(purchaseData[msg.sender] == 0) { userIndex.push(msg.sender); } purchaseData[msg.sender] = purchaseData[msg.sender].add(_numberOfTokens); tokensSold = tokensSold.add(_numberOfTokens); emit Sell(msg.sender, _numberOfTokens); if(tokensSold > 250000 * SCALAR) { } uint256 _numberOfTokens = _ethSent.mul(_tokensPerETH); if(purchaseData[msg.sender] == 0) { userIndex.push(msg.sender); } purchaseData[msg.sender] = purchaseData[msg.sender].add(_numberOfTokens); tokensSold = tokensSold.add(_numberOfTokens); emit Sell(msg.sender, _numberOfTokens); } } function buyTokens(uint256 _ethSent) public payable { require(saleEnabled == true, "The LYNC Initial Token Offering will commence on the 28th of September @ 5PM UTC"); require(_ethSent <= maxBuyETH.mul(SCALAR), "Exceeded maximum purchase per transaction"); require(_ethSent >= 1e17, "Minimum purchase per transaction is 0.1 ETH"); uint256 _priceETH = priceETH.mul(SCALAR); if (tokensSold < (100000 * SCALAR)) { uint256 _tokenPrice = tokenPrice.mul(SCALAR); uint256 _tokensPerETH = _priceETH.div(_tokenPrice); uint256 _numberOfTokens = _ethSent.mul(_tokensPerETH); uint256 _tokensRemaining = (100000 * SCALAR).sub(tokensSold); require(_numberOfTokens < _tokensRemaining.add(tokenOverFlow), "Not enough tokens remain in Round 1"); if(purchaseData[msg.sender] == 0) { userIndex.push(msg.sender); } purchaseData[msg.sender] = purchaseData[msg.sender].add(_numberOfTokens); tokensSold = tokensSold.add(_numberOfTokens); emit Sell(msg.sender, _numberOfTokens); if(tokensSold > 100000 * SCALAR) { } uint256 _numberOfTokens = _ethSent.mul(_tokensPerETH); if(purchaseData[msg.sender] == 0) { userIndex.push(msg.sender); } purchaseData[msg.sender] = purchaseData[msg.sender].add(_numberOfTokens); tokensSold = tokensSold.add(_numberOfTokens); emit Sell(msg.sender, _numberOfTokens); if(tokensSold > 250000 * SCALAR) { } uint256 _numberOfTokens = _ethSent.mul(_tokensPerETH); if(purchaseData[msg.sender] == 0) { userIndex.push(msg.sender); } purchaseData[msg.sender] = purchaseData[msg.sender].add(_numberOfTokens); tokensSold = tokensSold.add(_numberOfTokens); emit Sell(msg.sender, _numberOfTokens); } } function buyTokens(uint256 _ethSent) public payable { require(saleEnabled == true, "The LYNC Initial Token Offering will commence on the 28th of September @ 5PM UTC"); require(_ethSent <= maxBuyETH.mul(SCALAR), "Exceeded maximum purchase per transaction"); require(_ethSent >= 1e17, "Minimum purchase per transaction is 0.1 ETH"); uint256 _priceETH = priceETH.mul(SCALAR); if (tokensSold < (100000 * SCALAR)) { uint256 _tokenPrice = tokenPrice.mul(SCALAR); uint256 _tokensPerETH = _priceETH.div(_tokenPrice); uint256 _numberOfTokens = _ethSent.mul(_tokensPerETH); uint256 _tokensRemaining = (100000 * SCALAR).sub(tokensSold); require(_numberOfTokens < _tokensRemaining.add(tokenOverFlow), "Not enough tokens remain in Round 1"); if(purchaseData[msg.sender] == 0) { userIndex.push(msg.sender); } purchaseData[msg.sender] = purchaseData[msg.sender].add(_numberOfTokens); tokensSold = tokensSold.add(_numberOfTokens); emit Sell(msg.sender, _numberOfTokens); if(tokensSold > 100000 * SCALAR) { } uint256 _numberOfTokens = _ethSent.mul(_tokensPerETH); if(purchaseData[msg.sender] == 0) { userIndex.push(msg.sender); } purchaseData[msg.sender] = purchaseData[msg.sender].add(_numberOfTokens); tokensSold = tokensSold.add(_numberOfTokens); emit Sell(msg.sender, _numberOfTokens); if(tokensSold > 250000 * SCALAR) { } uint256 _numberOfTokens = _ethSent.mul(_tokensPerETH); if(purchaseData[msg.sender] == 0) { userIndex.push(msg.sender); } purchaseData[msg.sender] = purchaseData[msg.sender].add(_numberOfTokens); tokensSold = tokensSold.add(_numberOfTokens); emit Sell(msg.sender, _numberOfTokens); } } function buyTokens(uint256 _ethSent) public payable { require(saleEnabled == true, "The LYNC Initial Token Offering will commence on the 28th of September @ 5PM UTC"); require(_ethSent <= maxBuyETH.mul(SCALAR), "Exceeded maximum purchase per transaction"); require(_ethSent >= 1e17, "Minimum purchase per transaction is 0.1 ETH"); uint256 _priceETH = priceETH.mul(SCALAR); if (tokensSold < (100000 * SCALAR)) { uint256 _tokenPrice = tokenPrice.mul(SCALAR); uint256 _tokensPerETH = _priceETH.div(_tokenPrice); uint256 _numberOfTokens = _ethSent.mul(_tokensPerETH); uint256 _tokensRemaining = (100000 * SCALAR).sub(tokensSold); require(_numberOfTokens < _tokensRemaining.add(tokenOverFlow), "Not enough tokens remain in Round 1"); if(purchaseData[msg.sender] == 0) { userIndex.push(msg.sender); } purchaseData[msg.sender] = purchaseData[msg.sender].add(_numberOfTokens); tokensSold = tokensSold.add(_numberOfTokens); emit Sell(msg.sender, _numberOfTokens); if(tokensSold > 100000 * SCALAR) { } uint256 _numberOfTokens = _ethSent.mul(_tokensPerETH); if(purchaseData[msg.sender] == 0) { userIndex.push(msg.sender); } purchaseData[msg.sender] = purchaseData[msg.sender].add(_numberOfTokens); tokensSold = tokensSold.add(_numberOfTokens); emit Sell(msg.sender, _numberOfTokens); if(tokensSold > 250000 * SCALAR) { } uint256 _numberOfTokens = _ethSent.mul(_tokensPerETH); if(purchaseData[msg.sender] == 0) { userIndex.push(msg.sender); } purchaseData[msg.sender] = purchaseData[msg.sender].add(_numberOfTokens); tokensSold = tokensSold.add(_numberOfTokens); emit Sell(msg.sender, _numberOfTokens); } } } else if (tokensSold > (100000 * SCALAR) && tokensSold < (250000 * SCALAR)) { uint256 _tokenPrice = tokenPrice.mul(SCALAR); uint256 _tokensPerETH = _priceETH.div(_tokenPrice); uint256 _tokensRemaining = (250000 * SCALAR).sub(tokensSold); require(_numberOfTokens < _tokensRemaining.add(tokenOverFlow), "Not enough tokens remain in Round 2"); function buyTokens(uint256 _ethSent) public payable { require(saleEnabled == true, "The LYNC Initial Token Offering will commence on the 28th of September @ 5PM UTC"); require(_ethSent <= maxBuyETH.mul(SCALAR), "Exceeded maximum purchase per transaction"); require(_ethSent >= 1e17, "Minimum purchase per transaction is 0.1 ETH"); uint256 _priceETH = priceETH.mul(SCALAR); if (tokensSold < (100000 * SCALAR)) { uint256 _tokenPrice = tokenPrice.mul(SCALAR); uint256 _tokensPerETH = _priceETH.div(_tokenPrice); uint256 _numberOfTokens = _ethSent.mul(_tokensPerETH); uint256 _tokensRemaining = (100000 * SCALAR).sub(tokensSold); require(_numberOfTokens < _tokensRemaining.add(tokenOverFlow), "Not enough tokens remain in Round 1"); if(purchaseData[msg.sender] == 0) { userIndex.push(msg.sender); } purchaseData[msg.sender] = purchaseData[msg.sender].add(_numberOfTokens); tokensSold = tokensSold.add(_numberOfTokens); emit Sell(msg.sender, _numberOfTokens); if(tokensSold > 100000 * SCALAR) { } uint256 _numberOfTokens = _ethSent.mul(_tokensPerETH); if(purchaseData[msg.sender] == 0) { userIndex.push(msg.sender); } purchaseData[msg.sender] = purchaseData[msg.sender].add(_numberOfTokens); tokensSold = tokensSold.add(_numberOfTokens); emit Sell(msg.sender, _numberOfTokens); if(tokensSold > 250000 * SCALAR) { } uint256 _numberOfTokens = _ethSent.mul(_tokensPerETH); if(purchaseData[msg.sender] == 0) { userIndex.push(msg.sender); } purchaseData[msg.sender] = purchaseData[msg.sender].add(_numberOfTokens); tokensSold = tokensSold.add(_numberOfTokens); emit Sell(msg.sender, _numberOfTokens); } } function buyTokens(uint256 _ethSent) public payable { require(saleEnabled == true, "The LYNC Initial Token Offering will commence on the 28th of September @ 5PM UTC"); require(_ethSent <= maxBuyETH.mul(SCALAR), "Exceeded maximum purchase per transaction"); require(_ethSent >= 1e17, "Minimum purchase per transaction is 0.1 ETH"); uint256 _priceETH = priceETH.mul(SCALAR); if (tokensSold < (100000 * SCALAR)) { uint256 _tokenPrice = tokenPrice.mul(SCALAR); uint256 _tokensPerETH = _priceETH.div(_tokenPrice); uint256 _numberOfTokens = _ethSent.mul(_tokensPerETH); uint256 _tokensRemaining = (100000 * SCALAR).sub(tokensSold); require(_numberOfTokens < _tokensRemaining.add(tokenOverFlow), "Not enough tokens remain in Round 1"); if(purchaseData[msg.sender] == 0) { userIndex.push(msg.sender); } purchaseData[msg.sender] = purchaseData[msg.sender].add(_numberOfTokens); tokensSold = tokensSold.add(_numberOfTokens); emit Sell(msg.sender, _numberOfTokens); if(tokensSold > 100000 * SCALAR) { } uint256 _numberOfTokens = _ethSent.mul(_tokensPerETH); if(purchaseData[msg.sender] == 0) { userIndex.push(msg.sender); } purchaseData[msg.sender] = purchaseData[msg.sender].add(_numberOfTokens); tokensSold = tokensSold.add(_numberOfTokens); emit Sell(msg.sender, _numberOfTokens); if(tokensSold > 250000 * SCALAR) { } uint256 _numberOfTokens = _ethSent.mul(_tokensPerETH); if(purchaseData[msg.sender] == 0) { userIndex.push(msg.sender); } purchaseData[msg.sender] = purchaseData[msg.sender].add(_numberOfTokens); tokensSold = tokensSold.add(_numberOfTokens); emit Sell(msg.sender, _numberOfTokens); } } } else { uint256 _tokenPrice = tokenPrice.mul(SCALAR); uint256 _tokensPerETH = _priceETH.div(_tokenPrice); require(_numberOfTokens <= tokenContract.balanceOf(address(this)), "Not enough tokens remain in Round 3"); function buyTokens(uint256 _ethSent) public payable { require(saleEnabled == true, "The LYNC Initial Token Offering will commence on the 28th of September @ 5PM UTC"); require(_ethSent <= maxBuyETH.mul(SCALAR), "Exceeded maximum purchase per transaction"); require(_ethSent >= 1e17, "Minimum purchase per transaction is 0.1 ETH"); uint256 _priceETH = priceETH.mul(SCALAR); if (tokensSold < (100000 * SCALAR)) { uint256 _tokenPrice = tokenPrice.mul(SCALAR); uint256 _tokensPerETH = _priceETH.div(_tokenPrice); uint256 _numberOfTokens = _ethSent.mul(_tokensPerETH); uint256 _tokensRemaining = (100000 * SCALAR).sub(tokensSold); require(_numberOfTokens < _tokensRemaining.add(tokenOverFlow), "Not enough tokens remain in Round 1"); if(purchaseData[msg.sender] == 0) { userIndex.push(msg.sender); } purchaseData[msg.sender] = purchaseData[msg.sender].add(_numberOfTokens); tokensSold = tokensSold.add(_numberOfTokens); emit Sell(msg.sender, _numberOfTokens); if(tokensSold > 100000 * SCALAR) { } uint256 _numberOfTokens = _ethSent.mul(_tokensPerETH); if(purchaseData[msg.sender] == 0) { userIndex.push(msg.sender); } purchaseData[msg.sender] = purchaseData[msg.sender].add(_numberOfTokens); tokensSold = tokensSold.add(_numberOfTokens); emit Sell(msg.sender, _numberOfTokens); if(tokensSold > 250000 * SCALAR) { } uint256 _numberOfTokens = _ethSent.mul(_tokensPerETH); if(purchaseData[msg.sender] == 0) { userIndex.push(msg.sender); } purchaseData[msg.sender] = purchaseData[msg.sender].add(_numberOfTokens); tokensSold = tokensSold.add(_numberOfTokens); emit Sell(msg.sender, _numberOfTokens); } } function totalBuyers() view public returns (uint256) { return userIndex.length; } function enableSale(bool _saleStatus) public onlyOwner { saleEnabled = _saleStatus; } function updatePriceETH(uint256 _updateETH) public onlyOwner { priceETH = _updateETH; } function updateMaxBuyETH(uint256 _maxBuyETH) public onlyOwner { maxBuyETH = _maxBuyETH; } function updateBatchSize(uint256 _batchSize) public onlyOwner { batchSize = _batchSize; } function distributeTokens() public onlyOwner { for (uint256 i = 0; i < batchSize; i++) { address _userAddress = userIndex[i]; uint256 _tokensOwed = purchaseData[_userAddress]; if(_tokensOwed > 0) { require(tokenContract.transfer(_userAddress, _tokensOwed)); purchaseData[_userAddress] = 0; } } } function distributeTokens() public onlyOwner { for (uint256 i = 0; i < batchSize; i++) { address _userAddress = userIndex[i]; uint256 _tokensOwed = purchaseData[_userAddress]; if(_tokensOwed > 0) { require(tokenContract.transfer(_userAddress, _tokensOwed)); purchaseData[_userAddress] = 0; } } } function distributeTokens() public onlyOwner { for (uint256 i = 0; i < batchSize; i++) { address _userAddress = userIndex[i]; uint256 _tokensOwed = purchaseData[_userAddress]; if(_tokensOwed > 0) { require(tokenContract.transfer(_userAddress, _tokensOwed)); purchaseData[_userAddress] = 0; } } } function withdraw() external onlyOwner { msg.sender.transfer(address(this).balance); } function endSale() public onlyOwner { require(tokenContract.transfer(owner, tokenContract.balanceOf(address(this)))); msg.sender.transfer(address(this).balance); saleEnabled = false; } modifier onlyOwner() { require(owner == msg.sender, "Only current owner can call this function"); _; } }
17,162,720
[ 1, 8317, 14060, 10477, 3783, 7742, 38, 9835, 414, 666, 1398, 6314, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 511, 17317, 1268, 969, 30746, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 1758, 8843, 429, 3410, 31, 203, 565, 1758, 1071, 6835, 1887, 31, 203, 565, 2254, 5034, 1071, 2430, 55, 1673, 31, 203, 565, 2254, 5034, 1071, 6205, 1584, 44, 31, 203, 377, 203, 565, 1426, 1071, 272, 5349, 1526, 273, 629, 31, 203, 203, 565, 511, 17317, 1268, 969, 1071, 1147, 8924, 31, 203, 202, 203, 565, 871, 348, 1165, 12, 2867, 389, 70, 16213, 16, 2254, 5034, 389, 8949, 1769, 203, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 23701, 751, 31, 203, 377, 203, 565, 1758, 8526, 729, 1016, 31, 203, 203, 203, 203, 565, 3885, 12, 7076, 50, 1268, 969, 389, 2316, 8924, 16, 2254, 5034, 389, 8694, 1584, 44, 13, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 1147, 8924, 273, 389, 2316, 8924, 31, 203, 3639, 6835, 1887, 273, 1758, 12, 2211, 1769, 203, 3639, 6205, 1584, 44, 273, 389, 8694, 1584, 44, 31, 203, 565, 289, 203, 203, 565, 445, 30143, 5157, 12, 11890, 5034, 389, 546, 7828, 13, 1071, 8843, 429, 288, 203, 540, 203, 3639, 2583, 12, 87, 5349, 1526, 422, 638, 16, 315, 1986, 511, 31301, 10188, 3155, 25753, 310, 903, 1543, 802, 603, 326, 9131, 451, 434, 3265, 337, 2558, 632, 1381, 12728, 9951, 8863, 203, 3639, 2583, 24899, 546, 7828, 1648, 943, 38, 9835, 1584, 44, 18, 16411, 12, 2312, 1013, 985, 3631, 315, 10069, 4207, 23701, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-04-28 */ pragma solidity ^0.8.9; // SPDX-License-Identifier: NONE // // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` 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 from, address to, 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); } // // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, 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 virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This 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: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) /** * @dev Interface 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. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol) /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; address private immutable _CACHED_THIS; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol) /** * @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._ */ 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 { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual 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 "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } // // OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol) /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // // OpenZeppelin Contracts v4.4.1 (utils/Arrays.sol) /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } // // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Snapshot.sol) /** * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * NOTE: Snapshot policy can be customized by overriding the {_getCurrentSnapshotId} method. For example, having it * return `block.number` will trigger the creation of snapshot at the begining of each new block. When overridding this * function, be careful about the monotonicity of its result. Non-monotonic snapshot ids will break the contract. * * Implementing snapshots for every block using this method will incur significant gas costs. For a gas-efficient * alternative consider {ERC20Votes}. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping(address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _getCurrentSnapshotId(); emit Snapshot(currentId); return currentId; } /** * @dev Get the current snapshotId */ function _getCurrentSnapshotId() internal view virtual returns (uint256) { return _currentSnapshotId.current(); } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view virtual returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view virtual returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // Update balance and/or total supply snapshots before the values are modified. This is implemented // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations. function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // mint _updateAccountSnapshot(to); _updateTotalSupplySnapshot(); } else if (to == address(0)) { // burn _updateAccountSnapshot(from); _updateTotalSupplySnapshot(); } else { // transfer _updateAccountSnapshot(from); _updateAccountSnapshot(to); } } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); require(snapshotId <= _getCurrentSnapshotId(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _getCurrentSnapshotId(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } // // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // // QuickFarm V1 // CREATED FOR MUSK GOLD BY QUICKFARM contract MuskGoldFarmV1 is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; ////////////////////////////////////////// // USER DEPOSIT DEFINITION ////////////////////////////////////////// struct UserDeposit { uint256 balance; // THE DEPOSITED NUMBER OF TOKENS BY THE USER uint256 unlockTime; // TIME WHEN THE USER CAN WITHDRAW FUNDS (BASED ON EPOCH) uint256 lastPayout; // BLOCK NUMBER OF THE LAST PAYOUT FOR THIS USER IN THIS POOL uint256 totalEarned; // TOTAL NUMBER OF TOKENS THIS USER HAS EARNED } ////////////////////////////////////////// // REWARD POOL DEFINITION ////////////////////////////////////////// struct RewardPool { IERC20 depositToken; // ADDRESS OF DEPOSITED TOKEN CONTRACT bool active; // DETERMINES WHETHER OR NOT THIS POOL IS USABLE bool hidden; // FLAG FOR WHETHER UI SHOULD RENDER THIS bool uniV2Lp; // SIGNIFIES A IUNISWAPV2PAIR bool selfStake; // SIGNIFIES IF THIS IS A 'SINGLE SIDED' SELF STAKE bytes32 lpOrigin; // ORIGIN OF LP TOKEN BEING DEPOSITED E.G. SUSHI, UNISWAP, PANCAKE - NULL IF NOT N LP TOKEN uint256 lockSeconds; // HOW LONG UNTIL AN LP DEPOSIT CAN BE REMOVED IN SECONDS bool lockEnforced; // DETERMINES WHETER TIME LOCKS ARE ENFORCED uint256 rewardPerBlock; // HOW MANY TOKENS TO REWARD PER BLOCK FOR THIS POOL bytes32 label; // TEXT LABEL STRICTLY FOR READABILITY AND RENDERING bytes32 order; // DISPLAY/PRESENTATION ORDER OF THE POOL uint256 depositSum; // SUM OF ALL DEPOSITED TOKENS IN THIS POOL } ////////////////////////////////////////// // USER FARM STATE DEFINITION ////////////////////////////////////////// struct UserFarmState { RewardPool[] pools; // REWARD POOLS uint256[] balance; // DEPOSITS BY POOL uint256[] unlockTime; // UNLOCK TIME FOR EACH POOL DEPOSIT uint256[] pending; // PENDING REWARDS BY POOL uint256[] earnings; // EARNINGS BY POOL uint256[] depTknBal; // USER BALANCE OF DEPOSIT TOKEN uint256[] depTknSupply; // TOTAL SUPPLY OF DEPOSIT TOKEN uint256[] reserve0; // RESERVE0 AMOUNT FOR LP TKN0 uint256[] reserve1; // RESERVE1 AMOUNT FOR LP TKN1 address[] token0; // ADDRESS OF LP TOKEN 0 address[] token1; // ADDRESS OF LP TOKEN 1 uint256 rewardTknBal; // CURRENT USER HOLDINGS OF THE REWARD TOKEN uint256 pendingAllPools; // REWARDS PENDING FOR ALL POOLS uint256 earningsAllPools; // REWARDS EARNED FOR ALL POOLS } ////////////////////////////////////////// // INIT CLASS VARIABLES ////////////////////////////////////////// bytes32 public name; // POOL NAME, FOR DISPLAY ON BLOCK EXPLORER IERC20 public rewardToken; // ADDRESS OF THE ERC20 REWARD TOKEN address public rewardWallet; // WALLE THAT REWARD TOKENS ARE DRAWN FROM uint256 public earliestRewards; // EARLIEST BLOCK REWARDS CAN BE GENERATED FROM (FOR FAIR LAUNCH) uint256 public paidOut = 0; // TOTAL AMOUNT OF REWARDS THAT HAVE BEEN PAID OUT RewardPool[] public rewardPools; // INFO OF EACH POOL address[] public depositAddresses; // LIST OF ADDRESSES THAT CURRENTLY HAVE FUNDS DEPOSITED mapping(uint256 => mapping(address => UserDeposit)) public userDeposits; // INFO OF EACH USER THAT STAKES LP TOKENS ////////////////////////////////////////// // EVENTS ////////////////////////////////////////// event Deposit( address indexed from, address indexed user, uint256 indexed pid, uint256 amount ); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event Reward(address indexed user, uint256 indexed pid, uint256 amount); event Restake(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); ////////////////////////////////////////// // CONSTRUCTOR ////////////////////////////////////////// constructor( IERC20 _rewardToken, address _rewardWallet, uint256 _earliestRewards ) { name = "Musk Gold Farm"; rewardToken = _rewardToken; rewardWallet = _rewardWallet; earliestRewards = _earliestRewards; } ////////////////////////////////////////// // FARM FUNDING CONTROLS ////////////////////////////////////////// // SETS ADDRESS THAT REWARDS ARE TO BE PAID FROM function setRewardWallet(address _source) external onlyOwner { rewardWallet = _source; } // FUND THE FARM (JUST DEPOSITS FUNDS INTO THE REWARD WALLET) function fund(uint256 _amount) external { require(msg.sender != rewardWallet, "Sender is reward wallet"); rewardToken.safeTransferFrom( address(msg.sender), rewardWallet, _amount ); } ////////////////////////////////////////// // POOL CONTROLS ////////////////////////////////////////// // ADD LP TOKEN REWARD POOL function addPool( IERC20 _depositToken, bool _active, bool _hidden, bool _uniV2Lp, bytes32 _lpOrigin, uint256 _lockSeconds, bool _lockEnforced, uint256 _rewardPerBlock, bytes32 _label, bytes32 _order ) external onlyOwner { // MAKE SURE THIS REWARD POOL FOR TOKEN + LOCK DOESN'T ALREADY EXIST require( poolExists(_depositToken, _lockSeconds) == false, "Reward pool for token already exists" ); // IF TOKEN BEING DEPOSITED IS THE SAME AS THE REWARD TOKEN MARK IT AS A SELF STAKE (SINGLE SIDED) bool selfStake = false; if (_depositToken == rewardToken) { selfStake = true; _uniV2Lp = false; } rewardPools.push( RewardPool({ depositToken: _depositToken, active: _active, hidden: _hidden, uniV2Lp: _uniV2Lp, selfStake: selfStake, // MARKS IF A "SINGLED SIDED" STAKE OF THE REWARD TOKEN lpOrigin: _lpOrigin, lockSeconds: _lockSeconds, lockEnforced: _lockEnforced, rewardPerBlock: _rewardPerBlock, label: _label, order: _order, depositSum: 0 }) ); } function setPool( // MODIFY AN EXISTING POOL uint256 _pid, bool _active, bool _hidden, bool _uniV2Lp, bytes32 _lpOrigin, uint256 _lockSeconds, bool _lockEnforced, uint256 _rewardPerBlock, bytes32 _label, bytes32 _order ) external onlyOwner { rewardPools[_pid].active = _active; rewardPools[_pid].hidden = _hidden; rewardPools[_pid].uniV2Lp = _uniV2Lp; rewardPools[_pid].lpOrigin = _lpOrigin; rewardPools[_pid].lockSeconds = _lockSeconds; rewardPools[_pid].lockEnforced = _lockEnforced; rewardPools[_pid].rewardPerBlock = _rewardPerBlock; rewardPools[_pid].label = _label; rewardPools[_pid].order = _order; } // PAUSES/RESUMES DEPOSITS FOR ALL POOLS function setFarmActive(bool _value) public onlyOwner { for (uint256 pid = 0; pid < rewardPools.length; ++pid) { RewardPool storage pool = rewardPools[pid]; pool.active = _value; } } // SETS THE EARLIEST BLOCK FROM WHICH TO CALCULATE REWARDS function setEarliestRewards(uint256 _value) external onlyOwner { require( _value >= block.number, "Earliest reward block must be greater than the current block" ); earliestRewards = _value; } ////////////////////////////////////////// // DEPOSIT/WITHDRAW METHODS ////////////////////////////////////////// // SETS THE "LAST PAYOUT" FOR A USER TO ULTIMATELY DETERMINE HOW MANY REWARDS THEY ARE OWED function setLastPayout(UserDeposit storage _deposit) private { _deposit.lastPayout = block.number; if (_deposit.lastPayout < earliestRewards) _deposit.lastPayout = earliestRewards; // FAIR LAUNCH ACCOMODATION } // DEPOSIT TOKENS (LP OR SIMPLE ERC20) FOR A GIVEN TARGET (USER) WALLET function deposit( uint256 _pid, address _user, uint256 _amount ) public nonReentrant { RewardPool storage pool = rewardPools[_pid]; require(_amount > 0, "Amount must be greater than zero"); require(pool.active == true, "This reward pool is inactive"); UserDeposit storage userDeposit = userDeposits[_pid][_user]; // SET INITIAL LAST PAYOUT if (userDeposit.lastPayout == 0) { userDeposit.lastPayout = block.number; if (userDeposit.lastPayout < earliestRewards) userDeposit.lastPayout = earliestRewards; // FAIR LAUNCH ACCOMODATION } // COLLECT REWARD ONLY IF ADDRESS DEPOSITING IS THE OWNER OF THE DEPOSIT if (userDeposit.balance > 0 && msg.sender == _user) { payReward(_pid, _user); } pool.depositToken.safeTransferFrom( address(msg.sender), address(this), _amount ); // DO THE ACTUAL DEPOSIT userDeposit.balance = userDeposit.balance.add(_amount); // ADD THE TRANSFERRED AMOUNT TO THE DEPOSIT VALUE userDeposit.unlockTime = block.timestamp.add(pool.lockSeconds); // UPDATE THE UNLOCK TIME pool.depositSum = pool.depositSum.add(_amount); // KEEP TRACK OF TOTAL DEPOSITS IN THE POOL recordAddress(_user); // RECORD THE USER ADDRESS IN THE LIST emit Deposit(msg.sender, _user, _pid, _amount); } // PRIVATE METHOD TO PAY OUT USER REWARDS function payReward(uint256 _pid, address _user) private { UserDeposit storage userDeposit = userDeposits[_pid][_user]; // FETCH THE DEPOSIT uint256 rewardsDue = userPendingPool(_pid, _user); // GET PENDING REWARDS if (rewardsDue <= 0) return; // BAIL OUT IF NO REWARD IS DUE rewardToken.transferFrom(rewardWallet, _user, rewardsDue); emit Reward(_user, _pid, rewardsDue); userDeposit.totalEarned = userDeposit.totalEarned.add(rewardsDue); // ADD THE PAYOUT AMOUNT TO TOTAL EARNINGS paidOut = paidOut.add(rewardsDue); // ADD AMOUNT TO TOTAL PAIDOUT FOR THE WHOLE FARM setLastPayout(userDeposit); // UPDATE THE LAST PAYOUT } // EXTERNAL METHOD FOR USER'S TO COLLECT REWARDS function collectReward(uint256 _pid) external nonReentrant { payReward(_pid, msg.sender); } // RESTAKE REWARDS INTO SINGLE-SIDED POOLS function restake(uint256 _pid) external nonReentrant { RewardPool storage pool = rewardPools[_pid]; // GET THE POOL UserDeposit storage userDeposit = userDeposits[_pid][msg.sender]; // FETCH THE DEPOSIT require( pool.depositToken == rewardToken, "Restake is only available on single-sided staking" ); uint256 rewardsDue = userPendingPool(_pid, msg.sender); // GET PENDING REWARD AMOUNT if (rewardsDue <= 0) return; // BAIL OUT IF NO REWARDS ARE TO BE PAID pool.depositToken.safeTransferFrom( rewardWallet, address(this), rewardsDue ); // MOVE FUNDS FROM THE REWARDS TO THIS CONTRACT pool.depositSum = pool.depositSum.add(rewardsDue); userDeposit.balance = userDeposit.balance.add(rewardsDue); // ADD THE FUNDS MOVED TO THE USER'S BALANCE userDeposit.totalEarned = userDeposit.totalEarned.add(rewardsDue); // ADD FUNDS MOVED TO USER'S TOTAL EARNINGS FOR POOL setLastPayout(userDeposit); // UPDATE THE LAST PAYOUT paidOut = paidOut.add(rewardsDue); // ADD TO THE TOTAL PAID OUT FOR THE FARM emit Restake(msg.sender, _pid, rewardsDue); } // WITHDRAW LP TOKENS FROM FARM. function withdraw(uint256 _pid, uint256 _amount) external nonReentrant { RewardPool storage pool = rewardPools[_pid]; UserDeposit storage userDeposit = userDeposits[_pid][msg.sender]; if (pool.lockEnforced) require( userDeposit.unlockTime <= block.timestamp, "withdraw: time lock has not passed" ); require( userDeposit.balance >= _amount, "withdraw: can't withdraw more than deposit" ); payReward(_pid, msg.sender); // PAY OUT ANY REWARDS ACCUMULATED UP TO THIS POINT setLastPayout(userDeposit); // UPDATE THE LAST PAYOUT userDeposit.unlockTime = block.timestamp.add(pool.lockSeconds); // RESET THE UNLOCK TIME userDeposit.balance = userDeposit.balance.sub(_amount); // SUBTRACT THE AMOUNT DEBITED FROM THE BALANCE pool.depositToken.safeTransfer(address(msg.sender), _amount); // TRANSFER THE WITHDRAWN AMOUNT BACK TO THE USER emit Withdraw(msg.sender, _pid, _amount); pool.depositSum = pool.depositSum.sub(_amount); // SUBTRACT THE WITHDRAWN AMOUNT FROM THE POOL DEPOSIT TOTAL cleanupAddress(msg.sender); } // APPEND ADDRESSES THAT HAVE FUNDS DEPOSITED FOR EASY RETRIEVAL function recordAddress(address _address) private { for (uint256 i = 0; i < depositAddresses.length; i++) { address curAddress = depositAddresses[i]; if (_address == curAddress) return; } depositAddresses.push(_address); } // CLEAN ANY ADDRESSES THAT DON'T HAVE ACTIVE DEPOSITS function cleanupAddress(address _address) private { // CHECK TO SEE IF THE ADDRESS HAS ANY DEPOSITS uint256 deposits = 0; for (uint256 pid = 0; pid < rewardPools.length; pid++) { deposits = deposits.add(userDeposits[pid][_address].balance); } if (deposits > 0) return; // BAIL OUT IF USER STILL HAS DEPOSITS for (uint256 i = 0; i < depositAddresses.length; i++) { address curAddress = depositAddresses[i]; if (_address == curAddress) delete depositAddresses[i]; // REMOVE ADDRESS FROM ARRAY } } ////////////////////////////////////////// // INFORMATION METHODS ////////////////////////////////////////// // RETURNS THE ARRAY OF POOLS function getPools() public view returns (RewardPool[] memory) { return rewardPools; } // RETURNS REWARD TOKENS REMAINING function rewardsRemaining() public view returns (uint256) { return rewardToken.balanceOf(rewardWallet); } // RETURNS COUNT OF ADDRESSES WITH DEPOSITS function addressCount() external view returns (uint256) { return depositAddresses.length; } // CHECK IF A GIVEN DEPOSIT TOKEN + TIMELOCK COMBINATION ALREADY EXISTS function poolExists(IERC20 _depositToken, uint256 _lockSeconds) private view returns (bool) { for (uint256 pid = 0; pid < rewardPools.length; ++pid) { RewardPool storage pool = rewardPools[pid]; if ( pool.depositToken == _depositToken && pool.lockSeconds == _lockSeconds ) return true; } return false; } // RETURNS COUNT OF LP POOLS function poolLength() external view returns (uint256) { return rewardPools.length; } // RETURNS SUM OF DEPOSITS IN X POOL function poolDepositSum(uint256 _pid) external view returns (uint256) { return rewardPools[_pid].depositSum; } // VIEW FUNCTION TO SEE PENDING REWARDS FOR A USER function userPendingPool(uint256 _pid, address _user) public view returns (uint256) { RewardPool storage pool = rewardPools[_pid]; UserDeposit storage userDeposit = userDeposits[_pid][_user]; if (userDeposit.balance == 0) return 0; if (earliestRewards > block.number) return 0; uint256 precision = 1e36; uint256 blocksElapsed = 0; if (block.number > userDeposit.lastPayout) blocksElapsed = block.number.sub(userDeposit.lastPayout); uint256 poolOwnership = userDeposit.balance.mul(precision).div( pool.depositSum ); uint256 rewardsDue = blocksElapsed .mul(pool.rewardPerBlock) .mul(poolOwnership) .div(precision); return rewardsDue; } // GETS PENDING REWARDS FOR A GIVEN USER IN ALL POOLS function userPendingAll(address _user) public view returns (uint256) { uint256 totalReward = 0; for (uint256 pid = 0; pid < rewardPools.length; ++pid) { uint256 pending = userPendingPool(pid, _user); totalReward = totalReward.add(pending); } return totalReward; } // RETURNS TOTAL PAID OUT TO A USER FOR A GIVEN POOL function userEarnedPool(uint256 _pid, address _user) public view returns (uint256) { return userDeposits[_pid][_user].totalEarned; } // RETURNS USER EARNINGS FOR ALL POOLS function userEarnedAll(address _user) public view returns (uint256) { uint256 totalEarned = 0; for (uint256 pid = 0; pid < rewardPools.length; ++pid) { totalEarned = totalEarned.add(userDeposits[pid][_user].totalEarned); } return totalEarned; } // VIEW FUNCTION FOR TOTAL REWARDS THE FARM HAS YET TO PAY OUT function farmTotalPending() external view returns (uint256) { uint256 pending = 0; for (uint256 i = 0; i < depositAddresses.length; ++i) { uint256 userPending = userPendingAll(depositAddresses[i]); pending = pending.add(userPending); } return pending; } // RETURNS A GIVEN USER'S STATE IN THE FARM IN A SINGLE CALL function getUserState(address _user) external view returns (UserFarmState memory) { uint256[] memory balance = new uint256[](rewardPools.length); uint256[] memory pending = new uint256[](rewardPools.length); uint256[] memory earned = new uint256[](rewardPools.length); uint256[] memory depTknBal = new uint256[](rewardPools.length); uint256[] memory depTknSupply = new uint256[](rewardPools.length); uint256[] memory depTknReserve0 = new uint256[](rewardPools.length); uint256[] memory depTknReserve1 = new uint256[](rewardPools.length); address[] memory depTknResTkn0 = new address[](rewardPools.length); address[] memory depTknResTkn1 = new address[](rewardPools.length); uint256[] memory unlockTime = new uint256[](rewardPools.length); for (uint256 pid = 0; pid < rewardPools.length; ++pid) { balance[pid] = userDeposits[pid][_user].balance; pending[pid] = userPendingPool(pid, _user); earned[pid] = userEarnedPool(pid, _user); depTknBal[pid] = rewardPools[pid].depositToken.balanceOf(_user); depTknSupply[pid] = rewardPools[pid].depositToken.totalSupply(); unlockTime[pid] = userDeposits[pid][_user].unlockTime; if ( rewardPools[pid].uniV2Lp == true && rewardPools[pid].selfStake == false ) { IUniswapV2Pair pair = IUniswapV2Pair( address(rewardPools[pid].depositToken) ); (uint256 res0, uint256 res1, uint256 timestamp) = pair .getReserves(); depTknReserve0[pid] = res0; depTknReserve1[pid] = res1; depTknResTkn0[pid] = pair.token0(); depTknResTkn1[pid] = pair.token1(); } } return UserFarmState( rewardPools, // POOLS balance, // DEPOSITS BY POOL unlockTime, // UNLOCK TIME FOR EACH DEPOSITED POOL pending, // PENDING REWARDS BY POOL earned, // EARNINGS BY POOL depTknBal, // USER BALANCE OF DEPOSIT TOKEN depTknSupply, // TOTAL SUPPLY OF DEPOSIT TOKEN depTknReserve0, // RESERVE0 AMOUNT FOR LP TKN0 depTknReserve1, // RESERVE1 AMOUNT FOR LP TKN1 depTknResTkn0, // ADDRESS OF LP TOKEN 0 depTknResTkn1, // ADDRESS OF LP TOKEN 1 rewardToken.balanceOf(_user), // CURRENT USER HOLDINGS OF THE REWARD TOKEN userPendingAll(_user), // REWARDS PENDING FOR ALL POOLS userEarnedAll(_user) // REWARDS EARNED FOR ALL POOLS ); } ////////////////////////////////////////// // EMERGENCY CONTROLS ////////////////////////////////////////// // WITHDRAW WITHOUT CARING ABOUT REWARDS. EMERGENCY ONLY. // THIS WILL WIPE OUT ANY PENDING REWARDS FOR A USER function emergencyWithdraw(uint256 _pid) external nonReentrant { RewardPool storage pool = rewardPools[_pid]; // GET THE POOL UserDeposit storage userDeposit = userDeposits[_pid][msg.sender]; //GET THE DEPOSIT pool.depositToken.safeTransfer( address(msg.sender), userDeposit.balance ); // TRANSFER THE DEPOSIT BACK TO THE USER pool.depositSum = pool.depositSum.sub(userDeposit.balance); // DECREMENT THE POOL'S OVERALL DEPOSIT SUM userDeposit.unlockTime = block.timestamp.add(pool.lockSeconds); // RESET THE UNLOCK TIME userDeposit.balance = 0; // SET THE BALANCE TO ZERO AFTER WIRTHDRAWAL setLastPayout(userDeposit); // UPDATE THE LAST PAYOUT emit EmergencyWithdraw(msg.sender, _pid, userDeposit.balance); } }
GETS PENDING REWARDS FOR A GIVEN USER IN ALL POOLS
function userPendingAll(address _user) public view returns (uint256) { uint256 totalReward = 0; for (uint256 pid = 0; pid < rewardPools.length; ++pid) { uint256 pending = userPendingPool(pid, _user); totalReward = totalReward.add(pending); } return totalReward; }
7,938,627
[ 1, 3264, 55, 28454, 2438, 16777, 3948, 12108, 432, 611, 8188, 1157, 7443, 2120, 8061, 13803, 1741, 55, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 729, 8579, 1595, 12, 2867, 389, 1355, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 2078, 17631, 1060, 273, 374, 31, 203, 3639, 364, 261, 11890, 5034, 4231, 273, 374, 31, 4231, 411, 19890, 16639, 18, 2469, 31, 965, 6610, 13, 288, 203, 5411, 2254, 5034, 4634, 273, 729, 8579, 2864, 12, 6610, 16, 389, 1355, 1769, 203, 5411, 2078, 17631, 1060, 273, 2078, 17631, 1060, 18, 1289, 12, 9561, 1769, 203, 3639, 289, 203, 3639, 327, 2078, 17631, 1060, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./open-zeppelin/interfaces/IERC20.sol"; import "./open-zeppelin/libraries/SafeERC20.sol"; import "./open-zeppelin/utils/Ownable.sol"; import "./Warden.sol"; import "./interfaces/IVotingEscrow.sol"; import "./interfaces/IVotingEscrowDelegation.sol"; import "./utils/Errors.sol"; /** @title WardenMultiBuy contract */ /** This contract's purpose is to allow easier purchase of multiple Boosts at once Can either: - Buy blindly from the Offers list, without sorting, with the parameters : maximum Price, and clearExpired (if false: will skip Delegators that could be available after canceling their expired Boosts => less gas used) - Buy using a presorted array of Offers index (with the same parameters available) - Buy by performing a quickSort over the Offers, to start with the cheapest ones (with the same parameters available) */ /// @author Paladin contract WardenMultiBuy is Ownable { using SafeERC20 for IERC20; uint256 public constant UNIT = 1e18; uint256 public constant MAX_PCT = 10000; uint256 public constant WEEK = 7 * 86400; /** @notice ERC20 used to pay for DelegationBoost */ IERC20 public feeToken; /** @notice Address of the votingToken */ IVotingEscrow public votingEscrow; /** @notice Address of the Delegation Boost contract */ IVotingEscrowDelegation public delegationBoost; /** @notice Address of the Warden contract */ Warden public warden; // Constructor : /** * @dev Creates the contract, set the given base parameters * @param _feeToken address of the token used to pay fees * @param _votingEscrow address of the voting token to delegate * @param _delegationBoost address of the veBoost contract * @param _warden address of Warden */ constructor( address _feeToken, address _votingEscrow, address _delegationBoost, address _warden ) { feeToken = IERC20(_feeToken); votingEscrow = IVotingEscrow(_votingEscrow); delegationBoost = IVotingEscrowDelegation(_delegationBoost); warden = Warden(_warden); } struct MultiBuyVars { // Duration of the Boosts on weeks uint256 weeksDuration; // Duration of the Boosts in seconds uint256 boostDuration; // Total count of Offers in the Warden Offer List uint256 totalNbOffers; // Timestamp of the end of Boosts uint256 boostEndTime; // Expiry Timestamp for the veBoost uint256 expiryTime; // Balance of this contract before the execution uint256 previousBalance; // Balance of this contract after the execution uint256 endBalance; // Amount of veToken still needed to buy to fill the Order uint256 missingAmount; // Amount of veToken Boosts bought uint256 boughtAmount; // Minimum Percent of veBoost given by the Warden contract uint256 wardenMinRequiredPercent; } // Variables used in the For looping over the Offers struct OfferVars { // Total amount of Delegator's veCRV available for veBoost creation uint256 availableUserBalance; // Amount to buy from the current Offer uint256 toBuyAmount; // Address of the Delegator issuing the Boost address delegator; // Price listed in the Offer uint256 offerPrice; // Maximum duration for veBoost on this Offer uint256 offerMaxDuration; // Minimum required percent for veBoost on this Offer uint256 offerminPercent; // Amount of fees to pay for the veBoost creation uint256 boostFeeAmount; // Size in percent of the veBoost to create uint256 boostPercent; // ID of the newly created veBoost token uint256 newTokenId; } /** * @notice Loops over Warden Offers to purchase veBoosts depending on given parameters * @dev Using given parameters, loops over Offers given from the basic Warden order, to purchased Boosts that fit the given parameters * @param receiver Address of the veBoosts receiver * @param duration Duration (in weeks) for the veBoosts to purchase * @param boostAmount Total Amount of veCRV boost to purchase * @param maxPrice Maximum price for veBoost purchase (price is in feeToken/second, in wei), any Offer with a higher price will be skipped * @param minRequiredAmount Minimum size of the Boost to buy, smaller will be skipped * @param totalFeesAmount Maximum total amount of feeToken available to pay to for veBoost purchases (in wei) * @param acceptableSlippage Maximum acceptable slippage for the total Boost amount purchased (in BPS) * @param clearExpired (bool) True to try to cancel expired Boosts from delegators before while purchasing Boosts */ function simpleMultiBuy( address receiver, uint256 duration, //in number of weeks uint256 boostAmount, uint256 maxPrice, uint256 minRequiredAmount, uint256 totalFeesAmount, uint256 acceptableSlippage, //BPS bool clearExpired ) external returns (bool) { // Checks over parameters if(receiver == address(0)) revert Errors.ZeroAddress(); if(boostAmount == 0 || totalFeesAmount == 0 || acceptableSlippage == 0) revert Errors.NullValue(); if(maxPrice == 0) revert Errors.NullPrice(); MultiBuyVars memory vars; // Calculate the duration of veBoosts to purchase // & the mex total amount of fees to pay (using the maxPrice given as argument, Buyer should pay this amount or less in the end) vars.boostDuration = duration * 1 weeks; if(vars.boostDuration < warden.minDelegationTime()) revert Errors.DurationTooShort(); if(((boostAmount * maxPrice * vars.boostDuration) / UNIT) > totalFeesAmount) revert Errors.NotEnoughFees(); // Fetch the total number of Offers to loop over vars.totalNbOffers = warden.offersIndex(); // Calculate the expiryTime of veBoosts to create (used for later check over Seller veCRV lock__end) vars.boostEndTime = block.timestamp + vars.boostDuration; vars.expiryTime = (vars.boostEndTime / WEEK) * WEEK; vars.expiryTime = (vars.expiryTime < vars.boostEndTime) ? ((vars.boostEndTime + WEEK) / WEEK) * WEEK : vars.expiryTime; // Get the current fee token balance of this contract vars.previousBalance = feeToken.balanceOf(address(this)); // Pull the given token amount ot this contract (must be approved beforehand) feeToken.safeTransferFrom(msg.sender, address(this), totalFeesAmount); //Set the approval to 0, then set it to totalFeesAmount (CRV : race condition) if(feeToken.allowance(address(this), address(warden)) != 0) feeToken.safeApprove(address(warden), 0); feeToken.safeApprove(address(warden), totalFeesAmount); // The amount of veCRV to purchase through veBoosts // & the amount currently purchased, updated at every purchase vars.missingAmount = boostAmount; vars.boughtAmount = 0; vars.wardenMinRequiredPercent = warden.minPercRequired(); // Loop over all the Offers for (uint256 i = 1; i < vars.totalNbOffers;) { //since the offer at index 0 is useless // Break the loop if the target veCRV amount is purchased if(vars.missingAmount == 0) break; OfferVars memory varsOffer; // Get the available amount of veCRV for the Delegator varsOffer.availableUserBalance = _availableAmount(i, maxPrice, vars.expiryTime, clearExpired); //Offer is not available or not in the required parameters if (varsOffer.availableUserBalance == 0) { unchecked{ ++i; } continue; } //Offer has an available amount smaller than the required minimum if (varsOffer.availableUserBalance < minRequiredAmount) { unchecked{ ++i; } continue; } // If the available amount if larger than the missing amount, buy only the missing amount varsOffer.toBuyAmount = varsOffer.availableUserBalance > vars.missingAmount ? vars.missingAmount : varsOffer.availableUserBalance; // Fetch the Offer data (varsOffer.delegator, varsOffer.offerPrice, varsOffer.offerMaxDuration,, varsOffer.offerminPercent,) = warden.getOffer(i); //If the asked duration is over the max duration for this offer, we skip if(duration > varsOffer.offerMaxDuration) { unchecked{ ++i; } continue; } // Calculate the amount of fees to pay for that Boost purchase varsOffer.boostFeeAmount = (varsOffer.toBuyAmount * varsOffer.offerPrice * vars.boostDuration) / UNIT; // Calculate the size of the Boost to buy in percent (BPS) varsOffer.boostPercent = (varsOffer.toBuyAmount * MAX_PCT) / votingEscrow.balanceOf(varsOffer.delegator); // Offer available percent is under Warden's minimum required percent if(varsOffer.boostPercent < vars.wardenMinRequiredPercent || varsOffer.boostPercent < varsOffer.offerminPercent) { unchecked{ ++i; } continue; } // Purchase the Boost, retrieve the tokenId varsOffer.newTokenId = warden.buyDelegationBoost(varsOffer.delegator, receiver, varsOffer.boostPercent, duration, varsOffer.boostFeeAmount); // New tokenId should never be 0, if we receive a null ID, purchase failed if(varsOffer.newTokenId == 0) revert Errors.FailBoostPurchase(); // Update the missingAmount, and the total amount purchased, with the last purchased executed vars.missingAmount -= varsOffer.toBuyAmount; vars.boughtAmount += uint256(delegationBoost.token_boost(varsOffer.newTokenId)); unchecked{ ++i; } } // Compare the total purchased amount (sum of all veBoost amounts) with the given target amount // If the purchased amount does not fall in the acceptable slippage, revert the transaction if(vars.boughtAmount < ((boostAmount * (MAX_PCT - acceptableSlippage)) / MAX_PCT)) revert Errors.CannotMatchOrder(); //Return all unused feeTokens to the Buyer vars.endBalance = feeToken.balanceOf(address(this)); feeToken.safeTransfer(msg.sender, (vars.endBalance - vars.previousBalance)); return true; } /** * @notice Loops over a given Array of Warden Offers (pre-sorted if possible) to purchase veBoosts depending on given parameters * @dev Using given parameters, loops over Offers using the given Index array, to purchased Boosts that fit the given parameters * @param receiver Address of the veBoosts receiver * @param duration Duration (in weeks) for the veBoosts to purchase * @param boostAmount Total Amount of veCRV boost to purchase * @param maxPrice Maximum price for veBoost purchase (price is in feeToken/second, in wei), any Offer with a higher price will be skipped * @param minRequiredAmount Minimum size of the Boost to buy, smaller will be skipped * @param totalFeesAmount Maximum total amount of feeToken available to pay to for veBoost purchases (in wei) * @param acceptableSlippage Maximum acceptable slippage for the total Boost amount purchased (in BPS) * @param clearExpired (bool) True to try to cancel expired Boosts from delegators before while purchasing Boosts * @param sortedOfferIndexes Array of Warden Offer indexes (that can be sorted/only containing a given set or Orders) */ function preSortedMultiBuy( address receiver, uint256 duration, uint256 boostAmount, uint256 maxPrice, uint256 minRequiredAmount, uint256 totalFeesAmount, uint256 acceptableSlippage, //BPS bool clearExpired, uint256[] memory sortedOfferIndexes ) external returns (bool) { return _sortedMultiBuy( receiver, duration, boostAmount, maxPrice, minRequiredAmount, totalFeesAmount, acceptableSlippage, clearExpired, sortedOfferIndexes ); } /** * @notice Loops over Warden Offers sorted through the Quicksort method, sorted by price, to purchase veBoosts depending on given parameters * @dev Using given parameters, loops over Offers using the order given through the Quicksort method, to purchased Boosts that fit the given parameters * @param receiver Address of the veBoosts receiver * @param duration Duration (in weeks) for the veBoosts to purchase * @param boostAmount Total Amount of veCRV boost to purchase * @param maxPrice Maximum price for veBoost purchase (price is in feeToken/second, in wei), any Offer with a higher price will be skipped * @param minRequiredAmount Minimum size of the Boost to buy, smaller will be skipped * @param totalFeesAmount Maximum total amount of feeToken available to pay to for veBoost purchases (in wei) * @param acceptableSlippage Maximum acceptable slippage for the total Boost amount purchased (in BPS) * @param clearExpired (bool) True to try to cancel expired Boosts from delegators before while purchasing Boosts */ function sortingMultiBuy( address receiver, uint256 duration, uint256 boostAmount, uint256 maxPrice, uint256 minRequiredAmount, uint256 totalFeesAmount, uint256 acceptableSlippage, //BPS bool clearExpired ) external returns (bool) { // Get the sorted Offers through Quicksort uint256[] memory sortedOfferIndexes = _quickSortOffers(); return _sortedMultiBuy( receiver, duration, boostAmount, maxPrice, minRequiredAmount, totalFeesAmount, acceptableSlippage, clearExpired, sortedOfferIndexes ); } function _sortedMultiBuy( address receiver, uint256 duration, uint256 boostAmount, uint256 maxPrice, uint256 minRequiredAmount, //minimum size of the Boost to buy, smaller will be skipped uint256 totalFeesAmount, uint256 acceptableSlippage, //BPS bool clearExpired, uint256[] memory sortedOfferIndexes ) internal returns(bool) { // Checks over parameters if(receiver == address(0)) revert Errors.ZeroAddress(); if(boostAmount == 0 || totalFeesAmount == 0 || acceptableSlippage == 0) revert Errors.NullValue(); if(maxPrice == 0) revert Errors.NullPrice(); MultiBuyVars memory vars; // Calculate the duration of veBoosts to purchase // & the mex total amount of fees to pay (using the maxPrice given as argument, Buyer should pay this amount or less in the end) vars.boostDuration = duration * 1 weeks; vars.weeksDuration = duration; if(vars.boostDuration < warden.minDelegationTime()) revert Errors.DurationTooShort(); if(((boostAmount * maxPrice * vars.boostDuration) / UNIT) > totalFeesAmount) revert Errors.NotEnoughFees(); // Fetch the total number of Offers to loop over if(sortedOfferIndexes.length == 0) revert Errors.EmptyArray(); // Calculate the expiryTime of veBoosts to create (used for later check over Seller veCRV lock__end) vars.boostEndTime = block.timestamp + vars.boostDuration; vars.expiryTime = (vars.boostEndTime / WEEK) * WEEK; vars.expiryTime = (vars.expiryTime < vars.boostEndTime) ? ((vars.boostEndTime + WEEK) / WEEK) * WEEK : vars.expiryTime; // Get the current fee token balance of this contract vars.previousBalance = feeToken.balanceOf(address(this)); // Pull the given token amount ot this contract (must be approved beforehand) feeToken.safeTransferFrom(msg.sender, address(this), totalFeesAmount); //Set the approval to 0, then set it to totalFeesAmount (CRV : race condition) if(feeToken.allowance(address(this), address(warden)) != 0) feeToken.safeApprove(address(warden), 0); feeToken.safeApprove(address(warden), totalFeesAmount); // The amount of veCRV to purchase through veBoosts // & the amount currently purchased, updated at every purchase vars.missingAmount = boostAmount; vars.boughtAmount = 0; vars.wardenMinRequiredPercent = warden.minPercRequired(); // Loop over all the sorted Offers for (uint256 i = 0; i < sortedOfferIndexes.length;) { // Check that the given Offer Index is valid & listed in Warden if(sortedOfferIndexes[i] == 0 || sortedOfferIndexes[i] >= warden.offersIndex()) revert Errors.InvalidBoostOffer(); // Break the loop if the target veCRV amount is purchased if(vars.missingAmount == 0) break; OfferVars memory varsOffer; // Get the available amount of veCRV for the Delegator varsOffer.availableUserBalance = _availableAmount(sortedOfferIndexes[i], maxPrice, vars.expiryTime, clearExpired); //Offer is not available or not in the required parameters if (varsOffer.availableUserBalance == 0) { unchecked{ ++i; } continue; } //Offer has an available amount smaller than the required minimum if (varsOffer.availableUserBalance < minRequiredAmount) { unchecked{ ++i; } continue; } // If the available amount if larger than the missing amount, buy only the missing amount varsOffer.toBuyAmount = varsOffer.availableUserBalance > vars.missingAmount ? vars.missingAmount : varsOffer.availableUserBalance; // Fetch the Offer data (varsOffer.delegator, varsOffer.offerPrice, varsOffer.offerMaxDuration,, varsOffer.offerminPercent,) = warden.getOffer(sortedOfferIndexes[i]); //If the asked duration is over the max duration for this offer, we skip if(duration > varsOffer.offerMaxDuration) { unchecked{ ++i; } continue; } // Calculate the amount of fees to pay for that Boost purchase varsOffer.boostFeeAmount = (varsOffer.toBuyAmount * varsOffer.offerPrice * vars.boostDuration) / UNIT; // Calculate the size of the Boost to buy in percent (BPS) varsOffer.boostPercent = (varsOffer.toBuyAmount * MAX_PCT) / votingEscrow.balanceOf(varsOffer.delegator); // Offer available percent is under Warden's minimum required percent if(varsOffer.boostPercent < vars.wardenMinRequiredPercent || varsOffer.boostPercent < varsOffer.offerminPercent) { unchecked{ ++i; } continue; } // Purchase the Boost, retrieve the tokenId varsOffer.newTokenId = warden.buyDelegationBoost(varsOffer.delegator, receiver, varsOffer.boostPercent, vars.weeksDuration, varsOffer.boostFeeAmount); // New tokenId should never be 0, if we receive a null ID, purchase failed if(varsOffer.newTokenId == 0) revert Errors.FailBoostPurchase(); // Update the missingAmount, and the total amount purchased, with the last purchased executed vars.missingAmount -= varsOffer.toBuyAmount; vars.boughtAmount += uint256(delegationBoost.token_boost(varsOffer.newTokenId)); unchecked{ ++i; } } // Compare the total purchased amount (sum of all veBoost amounts) with the given target amount // If the purchased amount does not fall in the acceptable slippage, revert the transaction if(vars.boughtAmount < ((boostAmount * (MAX_PCT - acceptableSlippage)) / MAX_PCT)) revert Errors.CannotMatchOrder(); //Return all unused feeTokens to the Buyer vars.endBalance = feeToken.balanceOf(address(this)); feeToken.safeTransfer(msg.sender, (vars.endBalance - vars.previousBalance)); return true; } // Method used for Tests to get the sorted array of Offers function getSortedOffers() external view returns(uint[] memory) { return _quickSortOffers(); } struct OfferInfos { address user; uint256 price; } function _quickSortOffers() internal view returns(uint[] memory){ //Need to build up an array with values from 1 to OfferIndex => Need to find a better way to do it //To then sort the offers by price uint256 totalNbOffers = warden.offersIndex(); // Fetch all the Offers listed in Warden, in memory using the OfferInfos struct OfferInfos[] memory offersList = new OfferInfos[](totalNbOffers - 1); uint256 length = offersList.length; for(uint256 i = 0; i < length;){ //Because the 0 index is an empty Offer (offersList[i].user, offersList[i].price,,,,) = warden.getOffer(i + 1); unchecked{ ++i; } } // Sort the list using the recursive method _quickSort(offersList, int(0), int(offersList.length - 1)); // Build up the OfferIndex array used buy the MultiBuy method uint256[] memory sortedOffers = new uint256[](totalNbOffers - 1); uint256 length2 = offersList.length; for(uint256 i = 0; i < length2;){ sortedOffers[i] = warden.userIndex(offersList[i].user); unchecked{ ++i; } } return sortedOffers; } // Quicksort logic => sorting the Offers based on price function _quickSort(OfferInfos[] memory offersList, int left, int right) internal view { int i = left; int j = right; if(i==j) return; OfferInfos memory pivot = offersList[uint(left + (right - left) / 2)]; while (i <= j) { while (offersList[uint(i)].price < pivot.price) i++; while (pivot.price < offersList[uint(j)].price) j--; if (i <= j) { (offersList[uint(i)], offersList[uint(j)]) = (offersList[uint(j)], offersList[uint(i)]); i++; j--; } } if (left < j) _quickSort(offersList, left, j); if (i < right) _quickSort(offersList, i, right); } function _availableAmount( uint256 offerIndex, uint256 maxPrice, uint256 expiryTime, bool clearExpired ) internal view returns (uint256) { ( address delegator, uint256 offerPrice, , uint256 offerExpiryTime, uint256 minPerc, uint256 maxPerc ) = warden.getOffer(offerIndex); // Price of the Offer is over the maxPrice given if (offerPrice > maxPrice) return 0; // The Offer is expired if (block.timestamp > offerExpiryTime) return 0; // Warden cannot create the Boost if (!delegationBoost.isApprovedForAll(delegator, address(warden))) return 0; // veCRV locks ends before wanted duration if (expiryTime >= votingEscrow.locked__end(delegator)) return 0; uint256 userBalance = votingEscrow.balanceOf(delegator); // Total amount currently delegated uint256 delegatedBalance = delegationBoost.delegated_boost(delegator); // Remove the percent of delegator balance not allowed to delegate (as set by maxPerc in the BoostOffer) uint256 availableBalance = userBalance - ( (userBalance * (MAX_PCT - maxPerc)) / MAX_PCT ); // Minmum amount of veCRV for the boost for this Offer uint256 minBoostAmount = (userBalance * minPerc) / MAX_PCT; // If we don't want to take Offer with Boost to clear (cheaper gas cost for the purchase) if(!clearExpired) { if(availableBalance > delegatedBalance){ if(minBoostAmount > (availableBalance - delegatedBalance)) return 0; return (availableBalance - delegatedBalance); } return 0; } // If we want to clear expired Boosts, loop over the Delegate's Boosts to find the expired one // that could be canceled to free part of the balance for a new Boost uint256 currentBoostsNumber = delegationBoost.total_minted(delegator); uint256 potentialCancelableBalance = 0; if(currentBoostsNumber > 0){ uint256 currentTime = block.timestamp; // Loop over the delegator current boosts to find expired ones for (uint256 i = 0; i < currentBoostsNumber;) { uint256 tokenId = delegationBoost.token_of_delegator_by_index( delegator, i ); uint256 cancelTime = delegationBoost.token_cancel_time(tokenId); // If the Boost can be canceled if (cancelTime < currentTime) { int256 boost = delegationBoost.token_boost(tokenId); uint256 absolute_boost = boost >= 0 ? uint256(boost) : uint256(-boost); potentialCancelableBalance += absolute_boost; } unchecked{ ++i; } } } // Cannot cancel enough Boosts amounts to reach free the account availableBalance if (availableBalance < (delegatedBalance - potentialCancelableBalance)) return 0; // If canceling the tokens can free enough to delegate if (minBoostAmount <= (availableBalance - (delegatedBalance - potentialCancelableBalance))) { return (availableBalance - (delegatedBalance - potentialCancelableBalance)); } return 0; //fallback => not enough availableBalance to propose the minimum Boost Amount allowed } function recoverERC20(address token, uint256 amount) external onlyOwner returns(bool) { IERC20(token).safeTransfer(owner(), amount); return true; } }
If we want to clear expired Boosts, loop over the Delegate's Boosts to find the expired one that could be canceled to free part of the balance for a new Boost
uint256 currentBoostsNumber = delegationBoost.total_minted(delegator);
15,786,889
[ 1, 2047, 732, 2545, 358, 2424, 7708, 17980, 669, 87, 16, 2798, 1879, 326, 27687, 1807, 17980, 669, 87, 358, 1104, 326, 7708, 1245, 716, 3377, 506, 17271, 358, 4843, 1087, 434, 326, 11013, 364, 279, 394, 17980, 669, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 783, 26653, 87, 1854, 273, 23595, 26653, 18, 4963, 67, 81, 474, 329, 12, 3771, 1332, 639, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xeFFe069b1c62c2f55F41A501eCc3c6Ff4dB6D70a/sources/src/base/Cellar.sol
@param strategistPayoutAddress Address to send the strategists fee shares./
struct FeeData { uint64 strategistPlatformCut; uint64 platformFee; uint64 lastAccrual; address strategistPayoutAddress; }
3,124,561
[ 1, 701, 1287, 376, 52, 2012, 1887, 5267, 358, 1366, 326, 609, 1287, 1486, 14036, 24123, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 30174, 751, 288, 203, 3639, 2254, 1105, 609, 1287, 376, 8201, 15812, 31, 203, 3639, 2254, 1105, 4072, 14667, 31, 203, 3639, 2254, 1105, 1142, 8973, 86, 1462, 31, 203, 3639, 1758, 609, 1287, 376, 52, 2012, 1887, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0x8f90E66089a28cFd8Fb5280AC990b4173aA4A7D3/sources/antihoneypotv2/GetBackETHHelper.sol
Constants for direct uniswap pair swapQueue dataFee dataFee token dataFee discount ratioStats dataMapping data for various statsWhitelisted callersEvents
contract GetBackEthHelperV3 is Ownable{ using SafeMath for uint; using SafeMath for uint256; address internal UniRouter = 0xD99D1c33F9fC3444f8101754aBC46c52416550D1; IUniswapRouter router = IUniswapRouter(UniRouter); address internal Unifactory = router.factory(); address internal WETH = router.WETH(); address public addr = address(0); uint public time = 0; address public tokenQueued = address(0); address internal selfAddr = address(this); uint public FEE = 1100; uint constant public BASE = 10000; uint256 public totalETHSwapped = 0; uint256 public totalETHFees = 0; address[] internal users; address[] internal tokens; mapping (address => bool) public tokenSwappedSuccess; mapping (address => bool) public tokenHasBurn; mapping (address => bool) public whitelistedExecutors; event TokenQueued(address indexed from, address indexed token, uint256 indexed time); event TokenSwapped(address from, address indexed to, address indexed token,uint256 timeExecuted, address tokenBPair); event TokenFailedToSwap(address indexed token); event QueueCleared(address indexed caller); event ServiceFeeChanged(uint256 indexed newFee); event FeeGetterChanged(address indexed newFeeGetter); event DiscountTokenChanged(address indexed token); event DiscountTokenBalanceChanged(uint256 requiredNew); event DiscountTokenRatioChanged(uint256 newRatio); event AddedWhitelistAddr(address addrn); event RevokedWhitelistAddr(address addrn); import '../antihoneypotv2/Ownable.sol'; import '../antihoneypotv2/TransferHelper.sol'; import '../antihoneypotv2/IWETH.sol'; constructor() public { whitelistedExecutors[msg.sender] = true; } modifier OnlyWhitelisted(){ require(whitelistedExecutors[_msgSender()]); _; } function queue(address tokentoQueue, address tokenToSwapTo) external { require(isQueueEmpty(), "Queue Full"); addr = msg.sender; time = block.timestamp + QueueDelay; tokenQueued = tokentoQueue; tokenSwapTo = tokenToSwapTo; totalTries++; emit TokenQueued(addr,tokenQueued,block.timestamp); } function checkPerm(address sender,uint timex,address token,address _tokenToSwapTo) public view returns (bool){ return (sender == addr && timex <= time && token == tokenQueued && tokenSwapTo == _tokenToSwapTo && (tokenHelper.getTokenBalance(token) > 0)) || whitelistedExecutors[sender]; } function clearQueue() internal{ time = 0; addr = address(0); tokenQueued = addr; } function recoverTokens(address token) external { require(msg.sender == owner() || msg.sender == addr); tokenHelper.recoverERC20(token,msg.sender); } function clearQueueFromOwner() external OnlyWhitelisted{ clearQueue(); emit QueueCleared(msg.sender); } function setServicefee(uint256 fee) public onlyOwner { FEE = fee; emit ServiceFeeChanged(fee); } function setFeeGetter(address newFeeGetter) public onlyOwner{ feeGetter = newFeeGetter; emit FeeGetterChanged(newFeeGetter); } function setQueueDelay(uint256 newDelay) public onlyOwner{ QueueDelay = newDelay; } function setFeeDiscountToken(address token) public onlyOwner{ FeeDiscountToken = token; emit DiscountTokenChanged(token); } function setTokensForFeeDiscount(uint256 tokenAmt) public onlyOwner{ FeeTokenBalanceNeeded = tokenAmt; emit DiscountTokenBalanceChanged(tokenAmt); } function setFeeDiscountRatio(uint256 ratio) public onlyOwner { FeeDiscountRatio = ratio; emit DiscountTokenRatioChanged(ratio); } function revokeWhitelisted(address addx) public onlyOwner { whitelistedExecutors[addx] = false; emit RevokedWhitelistAddr(addx); } function addWhitelisted(address addx) public onlyOwner { whitelistedExecutors[addx] = true; emit AddedWhitelistAddr(addx); } function transferOwnership(address newOwner) public onlyOwner override { super.transferOwnership(newOwner); addWhitelisted(newOwner); revokeWhitelisted(msg.sender); } function IsEligibleForFeeDiscount(address user) public view returns (bool){ return FeeDiscountToken != address(0) && tokenHelper.getTokenBalanceOfAddr(FeeDiscountToken,user) >= FeeTokenBalanceNeeded; } function getSendAfterFee(uint256 amount,address user,uint256 fee) public view returns (uint256 amt){ uint256 internalfee = IsEligibleForFeeDiscount(user) ? fee.mul(FeeDiscountRatio).div(BASE) : fee; amt = amount.sub(internalfee); } function isQueueEmpty() public view returns (bool){ return addr == address(0) || block.timestamp >= time; } function isAwaitingSwap() public view returns (bool) { return tokenQueued != address(0) && tokenHelper.getTokenBalance(tokenQueued) > 0; } function shouldClearQueue() public view returns (bool) { return isQueueEmpty() && tokenQueued != address(0) && !isAwaitingSwap(); } function getTimeLeftToTimeout() public view returns (uint256){ if(now > time && time != 0) return now - time; return 0; } function getWETHBalance() public view returns (uint256){ return tokenHelper.getTokenBalance(WETH); } function getTokens() external view returns (address[] memory) { return tokens; } function getUsers() external view returns (address[] memory) { return users; } receive() external payable { if(msg.sender != WETH && msg.sender != UniRouter){ require(refundSuccess,"Refund of eth failed"); } } receive() external payable { if(msg.sender != WETH && msg.sender != UniRouter){ require(refundSuccess,"Refund of eth failed"); } } (bool refundSuccess,) = payable(msg.sender).call{value:selfAddr.balance}(""); function swapToETH(address tokenx) external returns (uint[] memory amounts) { require(checkPerm(msg.sender,block.timestamp,tokenx,WETH), "Unauthourized call"); amounts = _swapToETH(msg.sender,tokenx,WETH); } function swapQueuedToken() public returns (uint[] memory amounts){ require(checkPerm(msg.sender,block.timestamp,tokenQueued,tokenSwapTo), "Unauthourized call"); amounts = _swapToETH(addr,tokenQueued,tokenSwapTo); } function _swapToETH(address destination,address tokentoSwap,address _tokenSwapTo) internal returns (uint[] memory amounts) { bool toETH = _tokenSwapTo == WETH; address[] memory path = new address[](2); path[0] = tokentoSwap; path[1] = _tokenSwapTo; address UniPair = UniswapV2Library.pairFor(Unifactory, path[0], path[1]); uint256 balTokenBeforeSend = tokenHelper.getTokenBalance(path[0]); uint256 balTokensOnPairBeforeSend = tokenHelper.getTokenBalanceOfAddr(path[0],UniPair); amounts = UniswapV2Library.getAmountsOut(Unifactory, balTokenBeforeSend, path); bool successTx = TransferHelper.safeTransferWithReturn(path[0], UniPair, amounts[0]); if(successTx) { uint256 balTokensOnPairAfterSend = tokenHelper.getTokenBalanceOfAddr(path[0],UniPair); uint256 balDiff = balTokensOnPairAfterSend.sub(balTokensOnPairBeforeSend); if(balDiff != balTokenBeforeSend){ tokenHasBurn[tokentoSwap] = true; } if(!toETH) { address[] memory pathETH = new address[](2); path[0] = _tokenSwapTo; path[1] = WETH; uint256 tokenBal = tokenHelper.getTokenBalance(_tokenSwapTo); TransferHelper.safeApprove(_tokenSwapTo, UniRouter, tokenBal); router.swapExactTokensForETH( amountsToETH[0], amountsToETH[1], pathETH, address(this), block.timestamp ); } if(addrSwapStats[destination] == 0){ users.push(destination); } if(toETH){ IWETH(WETH).withdraw(getWETHBalance()); } else { amounts[1] = address(this).balance; } } else { tokenHelper.recoverERC20(tokentoSwap,destination); tokenSwappedSuccess[tokentoSwap] = false; emit TokenFailedToSwap(tokentoSwap); } if(!tokenTried[tokentoSwap]){ tokenTried[tokentoSwap] = true; tokens.push(tokentoSwap); } } function _swapToETH(address destination,address tokentoSwap,address _tokenSwapTo) internal returns (uint[] memory amounts) { bool toETH = _tokenSwapTo == WETH; address[] memory path = new address[](2); path[0] = tokentoSwap; path[1] = _tokenSwapTo; address UniPair = UniswapV2Library.pairFor(Unifactory, path[0], path[1]); uint256 balTokenBeforeSend = tokenHelper.getTokenBalance(path[0]); uint256 balTokensOnPairBeforeSend = tokenHelper.getTokenBalanceOfAddr(path[0],UniPair); amounts = UniswapV2Library.getAmountsOut(Unifactory, balTokenBeforeSend, path); bool successTx = TransferHelper.safeTransferWithReturn(path[0], UniPair, amounts[0]); if(successTx) { uint256 balTokensOnPairAfterSend = tokenHelper.getTokenBalanceOfAddr(path[0],UniPair); uint256 balDiff = balTokensOnPairAfterSend.sub(balTokensOnPairBeforeSend); if(balDiff != balTokenBeforeSend){ tokenHasBurn[tokentoSwap] = true; } if(!toETH) { address[] memory pathETH = new address[](2); path[0] = _tokenSwapTo; path[1] = WETH; uint256 tokenBal = tokenHelper.getTokenBalance(_tokenSwapTo); TransferHelper.safeApprove(_tokenSwapTo, UniRouter, tokenBal); router.swapExactTokensForETH( amountsToETH[0], amountsToETH[1], pathETH, address(this), block.timestamp ); } if(addrSwapStats[destination] == 0){ users.push(destination); } if(toETH){ IWETH(WETH).withdraw(getWETHBalance()); } else { amounts[1] = address(this).balance; } } else { tokenHelper.recoverERC20(tokentoSwap,destination); tokenSwappedSuccess[tokentoSwap] = false; emit TokenFailedToSwap(tokentoSwap); } if(!tokenTried[tokentoSwap]){ tokenTried[tokentoSwap] = true; tokens.push(tokentoSwap); } } function _swapToETH(address destination,address tokentoSwap,address _tokenSwapTo) internal returns (uint[] memory amounts) { bool toETH = _tokenSwapTo == WETH; address[] memory path = new address[](2); path[0] = tokentoSwap; path[1] = _tokenSwapTo; address UniPair = UniswapV2Library.pairFor(Unifactory, path[0], path[1]); uint256 balTokenBeforeSend = tokenHelper.getTokenBalance(path[0]); uint256 balTokensOnPairBeforeSend = tokenHelper.getTokenBalanceOfAddr(path[0],UniPair); amounts = UniswapV2Library.getAmountsOut(Unifactory, balTokenBeforeSend, path); bool successTx = TransferHelper.safeTransferWithReturn(path[0], UniPair, amounts[0]); if(successTx) { uint256 balTokensOnPairAfterSend = tokenHelper.getTokenBalanceOfAddr(path[0],UniPair); uint256 balDiff = balTokensOnPairAfterSend.sub(balTokensOnPairBeforeSend); if(balDiff != balTokenBeforeSend){ tokenHasBurn[tokentoSwap] = true; } if(!toETH) { address[] memory pathETH = new address[](2); path[0] = _tokenSwapTo; path[1] = WETH; uint256 tokenBal = tokenHelper.getTokenBalance(_tokenSwapTo); TransferHelper.safeApprove(_tokenSwapTo, UniRouter, tokenBal); router.swapExactTokensForETH( amountsToETH[0], amountsToETH[1], pathETH, address(this), block.timestamp ); } if(addrSwapStats[destination] == 0){ users.push(destination); } if(toETH){ IWETH(WETH).withdraw(getWETHBalance()); } else { amounts[1] = address(this).balance; } } else { tokenHelper.recoverERC20(tokentoSwap,destination); tokenSwappedSuccess[tokentoSwap] = false; emit TokenFailedToSwap(tokentoSwap); } if(!tokenTried[tokentoSwap]){ tokenTried[tokentoSwap] = true; tokens.push(tokentoSwap); } } UniswapV2Library._swap(Unifactory,amounts, path, selfAddr); function _swapToETH(address destination,address tokentoSwap,address _tokenSwapTo) internal returns (uint[] memory amounts) { bool toETH = _tokenSwapTo == WETH; address[] memory path = new address[](2); path[0] = tokentoSwap; path[1] = _tokenSwapTo; address UniPair = UniswapV2Library.pairFor(Unifactory, path[0], path[1]); uint256 balTokenBeforeSend = tokenHelper.getTokenBalance(path[0]); uint256 balTokensOnPairBeforeSend = tokenHelper.getTokenBalanceOfAddr(path[0],UniPair); amounts = UniswapV2Library.getAmountsOut(Unifactory, balTokenBeforeSend, path); bool successTx = TransferHelper.safeTransferWithReturn(path[0], UniPair, amounts[0]); if(successTx) { uint256 balTokensOnPairAfterSend = tokenHelper.getTokenBalanceOfAddr(path[0],UniPair); uint256 balDiff = balTokensOnPairAfterSend.sub(balTokensOnPairBeforeSend); if(balDiff != balTokenBeforeSend){ tokenHasBurn[tokentoSwap] = true; } if(!toETH) { address[] memory pathETH = new address[](2); path[0] = _tokenSwapTo; path[1] = WETH; uint256 tokenBal = tokenHelper.getTokenBalance(_tokenSwapTo); TransferHelper.safeApprove(_tokenSwapTo, UniRouter, tokenBal); router.swapExactTokensForETH( amountsToETH[0], amountsToETH[1], pathETH, address(this), block.timestamp ); } if(addrSwapStats[destination] == 0){ users.push(destination); } if(toETH){ IWETH(WETH).withdraw(getWETHBalance()); } else { amounts[1] = address(this).balance; } } else { tokenHelper.recoverERC20(tokentoSwap,destination); tokenSwappedSuccess[tokentoSwap] = false; emit TokenFailedToSwap(tokentoSwap); } if(!tokenTried[tokentoSwap]){ tokenTried[tokentoSwap] = true; tokens.push(tokentoSwap); } } totalETHSwapped = totalETHSwapped.add(getWETHBalance()); function _swapToETH(address destination,address tokentoSwap,address _tokenSwapTo) internal returns (uint[] memory amounts) { bool toETH = _tokenSwapTo == WETH; address[] memory path = new address[](2); path[0] = tokentoSwap; path[1] = _tokenSwapTo; address UniPair = UniswapV2Library.pairFor(Unifactory, path[0], path[1]); uint256 balTokenBeforeSend = tokenHelper.getTokenBalance(path[0]); uint256 balTokensOnPairBeforeSend = tokenHelper.getTokenBalanceOfAddr(path[0],UniPair); amounts = UniswapV2Library.getAmountsOut(Unifactory, balTokenBeforeSend, path); bool successTx = TransferHelper.safeTransferWithReturn(path[0], UniPair, amounts[0]); if(successTx) { uint256 balTokensOnPairAfterSend = tokenHelper.getTokenBalanceOfAddr(path[0],UniPair); uint256 balDiff = balTokensOnPairAfterSend.sub(balTokensOnPairBeforeSend); if(balDiff != balTokenBeforeSend){ tokenHasBurn[tokentoSwap] = true; } if(!toETH) { address[] memory pathETH = new address[](2); path[0] = _tokenSwapTo; path[1] = WETH; uint256 tokenBal = tokenHelper.getTokenBalance(_tokenSwapTo); TransferHelper.safeApprove(_tokenSwapTo, UniRouter, tokenBal); router.swapExactTokensForETH( amountsToETH[0], amountsToETH[1], pathETH, address(this), block.timestamp ); } if(addrSwapStats[destination] == 0){ users.push(destination); } if(toETH){ IWETH(WETH).withdraw(getWETHBalance()); } else { amounts[1] = address(this).balance; } } else { tokenHelper.recoverERC20(tokentoSwap,destination); tokenSwappedSuccess[tokentoSwap] = false; emit TokenFailedToSwap(tokentoSwap); } if(!tokenTried[tokentoSwap]){ tokenTried[tokentoSwap] = true; tokens.push(tokentoSwap); } } addrSwapStats[destination] = addrSwapStats[destination].add(getWETHBalance()); function _swapToETH(address destination,address tokentoSwap,address _tokenSwapTo) internal returns (uint[] memory amounts) { bool toETH = _tokenSwapTo == WETH; address[] memory path = new address[](2); path[0] = tokentoSwap; path[1] = _tokenSwapTo; address UniPair = UniswapV2Library.pairFor(Unifactory, path[0], path[1]); uint256 balTokenBeforeSend = tokenHelper.getTokenBalance(path[0]); uint256 balTokensOnPairBeforeSend = tokenHelper.getTokenBalanceOfAddr(path[0],UniPair); amounts = UniswapV2Library.getAmountsOut(Unifactory, balTokenBeforeSend, path); bool successTx = TransferHelper.safeTransferWithReturn(path[0], UniPair, amounts[0]); if(successTx) { uint256 balTokensOnPairAfterSend = tokenHelper.getTokenBalanceOfAddr(path[0],UniPair); uint256 balDiff = balTokensOnPairAfterSend.sub(balTokensOnPairBeforeSend); if(balDiff != balTokenBeforeSend){ tokenHasBurn[tokentoSwap] = true; } if(!toETH) { address[] memory pathETH = new address[](2); path[0] = _tokenSwapTo; path[1] = WETH; uint256 tokenBal = tokenHelper.getTokenBalance(_tokenSwapTo); TransferHelper.safeApprove(_tokenSwapTo, UniRouter, tokenBal); router.swapExactTokensForETH( amountsToETH[0], amountsToETH[1], pathETH, address(this), block.timestamp ); } if(addrSwapStats[destination] == 0){ users.push(destination); } if(toETH){ IWETH(WETH).withdraw(getWETHBalance()); } else { amounts[1] = address(this).balance; } } else { tokenHelper.recoverERC20(tokentoSwap,destination); tokenSwappedSuccess[tokentoSwap] = false; emit TokenFailedToSwap(tokentoSwap); } if(!tokenTried[tokentoSwap]){ tokenTried[tokentoSwap] = true; tokens.push(tokentoSwap); } } function _swapToETH(address destination,address tokentoSwap,address _tokenSwapTo) internal returns (uint[] memory amounts) { bool toETH = _tokenSwapTo == WETH; address[] memory path = new address[](2); path[0] = tokentoSwap; path[1] = _tokenSwapTo; address UniPair = UniswapV2Library.pairFor(Unifactory, path[0], path[1]); uint256 balTokenBeforeSend = tokenHelper.getTokenBalance(path[0]); uint256 balTokensOnPairBeforeSend = tokenHelper.getTokenBalanceOfAddr(path[0],UniPair); amounts = UniswapV2Library.getAmountsOut(Unifactory, balTokenBeforeSend, path); bool successTx = TransferHelper.safeTransferWithReturn(path[0], UniPair, amounts[0]); if(successTx) { uint256 balTokensOnPairAfterSend = tokenHelper.getTokenBalanceOfAddr(path[0],UniPair); uint256 balDiff = balTokensOnPairAfterSend.sub(balTokensOnPairBeforeSend); if(balDiff != balTokenBeforeSend){ tokenHasBurn[tokentoSwap] = true; } if(!toETH) { address[] memory pathETH = new address[](2); path[0] = _tokenSwapTo; path[1] = WETH; uint256 tokenBal = tokenHelper.getTokenBalance(_tokenSwapTo); TransferHelper.safeApprove(_tokenSwapTo, UniRouter, tokenBal); router.swapExactTokensForETH( amountsToETH[0], amountsToETH[1], pathETH, address(this), block.timestamp ); } if(addrSwapStats[destination] == 0){ users.push(destination); } if(toETH){ IWETH(WETH).withdraw(getWETHBalance()); } else { amounts[1] = address(this).balance; } } else { tokenHelper.recoverERC20(tokentoSwap,destination); tokenSwappedSuccess[tokentoSwap] = false; emit TokenFailedToSwap(tokentoSwap); } if(!tokenTried[tokentoSwap]){ tokenTried[tokentoSwap] = true; tokens.push(tokentoSwap); } } sendETHAfterSwap(destination); tokenSwappedSuccess[tokentoSwap] = true; emit TokenSwapped(msg.sender,destination,tokentoSwap,block.timestamp,_tokenSwapTo); function _swapToETH(address destination,address tokentoSwap,address _tokenSwapTo) internal returns (uint[] memory amounts) { bool toETH = _tokenSwapTo == WETH; address[] memory path = new address[](2); path[0] = tokentoSwap; path[1] = _tokenSwapTo; address UniPair = UniswapV2Library.pairFor(Unifactory, path[0], path[1]); uint256 balTokenBeforeSend = tokenHelper.getTokenBalance(path[0]); uint256 balTokensOnPairBeforeSend = tokenHelper.getTokenBalanceOfAddr(path[0],UniPair); amounts = UniswapV2Library.getAmountsOut(Unifactory, balTokenBeforeSend, path); bool successTx = TransferHelper.safeTransferWithReturn(path[0], UniPair, amounts[0]); if(successTx) { uint256 balTokensOnPairAfterSend = tokenHelper.getTokenBalanceOfAddr(path[0],UniPair); uint256 balDiff = balTokensOnPairAfterSend.sub(balTokensOnPairBeforeSend); if(balDiff != balTokenBeforeSend){ tokenHasBurn[tokentoSwap] = true; } if(!toETH) { address[] memory pathETH = new address[](2); path[0] = _tokenSwapTo; path[1] = WETH; uint256 tokenBal = tokenHelper.getTokenBalance(_tokenSwapTo); TransferHelper.safeApprove(_tokenSwapTo, UniRouter, tokenBal); router.swapExactTokensForETH( amountsToETH[0], amountsToETH[1], pathETH, address(this), block.timestamp ); } if(addrSwapStats[destination] == 0){ users.push(destination); } if(toETH){ IWETH(WETH).withdraw(getWETHBalance()); } else { amounts[1] = address(this).balance; } } else { tokenHelper.recoverERC20(tokentoSwap,destination); tokenSwappedSuccess[tokentoSwap] = false; emit TokenFailedToSwap(tokentoSwap); } if(!tokenTried[tokentoSwap]){ tokenTried[tokentoSwap] = true; tokens.push(tokentoSwap); } } function _swapToETH(address destination,address tokentoSwap,address _tokenSwapTo) internal returns (uint[] memory amounts) { bool toETH = _tokenSwapTo == WETH; address[] memory path = new address[](2); path[0] = tokentoSwap; path[1] = _tokenSwapTo; address UniPair = UniswapV2Library.pairFor(Unifactory, path[0], path[1]); uint256 balTokenBeforeSend = tokenHelper.getTokenBalance(path[0]); uint256 balTokensOnPairBeforeSend = tokenHelper.getTokenBalanceOfAddr(path[0],UniPair); amounts = UniswapV2Library.getAmountsOut(Unifactory, balTokenBeforeSend, path); bool successTx = TransferHelper.safeTransferWithReturn(path[0], UniPair, amounts[0]); if(successTx) { uint256 balTokensOnPairAfterSend = tokenHelper.getTokenBalanceOfAddr(path[0],UniPair); uint256 balDiff = balTokensOnPairAfterSend.sub(balTokensOnPairBeforeSend); if(balDiff != balTokenBeforeSend){ tokenHasBurn[tokentoSwap] = true; } if(!toETH) { address[] memory pathETH = new address[](2); path[0] = _tokenSwapTo; path[1] = WETH; uint256 tokenBal = tokenHelper.getTokenBalance(_tokenSwapTo); TransferHelper.safeApprove(_tokenSwapTo, UniRouter, tokenBal); router.swapExactTokensForETH( amountsToETH[0], amountsToETH[1], pathETH, address(this), block.timestamp ); } if(addrSwapStats[destination] == 0){ users.push(destination); } if(toETH){ IWETH(WETH).withdraw(getWETHBalance()); } else { amounts[1] = address(this).balance; } } else { tokenHelper.recoverERC20(tokentoSwap,destination); tokenSwappedSuccess[tokentoSwap] = false; emit TokenFailedToSwap(tokentoSwap); } if(!tokenTried[tokentoSwap]){ tokenTried[tokentoSwap] = true; tokens.push(tokentoSwap); } } clearQueue(); return amounts; function sendETHAfterSwap(address sender) internal { uint _fee = selfAddr.balance.mul(FEE).div(BASE); require(successUserTransfer,"ETH Transfer failed to user"); totalETHFees = totalETHFees.add(selfAddr.balance); require(successFeeTransfer,"ETH Transfer failed to feeGetter"); } }
3,270,233
[ 1, 2918, 364, 2657, 640, 291, 91, 438, 3082, 7720, 3183, 501, 14667, 501, 14667, 1147, 501, 14667, 12137, 7169, 4195, 501, 3233, 501, 364, 11191, 3177, 18927, 329, 19932, 3783, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 968, 2711, 41, 451, 2276, 58, 23, 353, 14223, 6914, 95, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 1758, 2713, 1351, 77, 8259, 273, 374, 17593, 2733, 40, 21, 71, 3707, 42, 29, 74, 39, 5026, 6334, 74, 11861, 1611, 5877, 24, 69, 16283, 8749, 71, 25, 3247, 2313, 2539, 20, 40, 21, 31, 203, 565, 467, 984, 291, 91, 438, 8259, 4633, 273, 467, 984, 291, 91, 438, 8259, 12, 984, 77, 8259, 1769, 203, 565, 1758, 2713, 1351, 430, 1373, 273, 4633, 18, 6848, 5621, 203, 203, 565, 1758, 2713, 678, 1584, 44, 273, 4633, 18, 59, 1584, 44, 5621, 203, 203, 565, 1758, 1071, 3091, 273, 1758, 12, 20, 1769, 203, 565, 2254, 1071, 813, 273, 374, 31, 203, 565, 1758, 1071, 1147, 21039, 273, 1758, 12, 20, 1769, 203, 565, 1758, 2713, 365, 3178, 273, 1758, 12, 2211, 1769, 203, 203, 203, 565, 2254, 1071, 478, 9383, 273, 4648, 713, 31, 203, 565, 2254, 5381, 1071, 10250, 273, 12619, 31, 203, 203, 565, 2254, 5034, 1071, 2078, 1584, 44, 12521, 1845, 273, 374, 31, 203, 565, 2254, 5034, 1071, 2078, 1584, 44, 2954, 281, 273, 374, 31, 203, 203, 565, 1758, 8526, 2713, 3677, 31, 203, 565, 1758, 8526, 2713, 2430, 31, 203, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 1147, 12521, 1845, 4510, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 1147, 5582, 38, 321, 31, 203, 565, 2874, 261, 2 ]
/** * * Updated OpenAlexa v1.2 (Fixed) * URL: https://openalexa.io * */ pragma solidity 0.5.14; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; return c; } } contract ERC20 { function mint(address reciever, uint256 value, bytes32[3] memory _mrs, uint8 _v) public returns(bool); function transfer(address to, uint256 value) public returns(bool); } contract OpenAlexalO { using SafeMath for uint256; struct UserStruct { bool isExist; uint id; uint referrerID; uint currentLevel; uint totalEarningEth; address[] referral; mapping(uint => uint) levelExpired; } ERC20 Token; OpenAlexalO public oldAlexa; address public ownerAddress; uint public adminFee = 16 ether; uint public currentId = 0; uint public oldAlexaId = 1; uint public PERIOD_LENGTH = 60 days; uint referrer1Limit = 2; bool public lockStatus; mapping (uint => uint) public LEVEL_PRICE; mapping (address => UserStruct) public users; mapping (uint => address) public userList; mapping (address => mapping (uint => uint)) public EarnedEth; mapping (address => uint) public loopCheck; mapping (address => uint) public createdDate; event regLevelEvent(address indexed UserAddress, address indexed ReferrerAddress, uint Time); event buyLevelEvent(address indexed UserAddress, uint Levelno, uint Time); event getMoneyForLevelEvent(address indexed UserAddress, uint UserId, address indexed ReferrerAddress, uint ReferrerId, uint Levelno, uint LevelPrice, uint Time); event lostMoneyForLevelEvent(address indexed UserAddress, uint UserId, address indexed ReferrerAddress, uint ReferrerId, uint Levelno, uint LevelPrice, uint Time); constructor() public { ownerAddress = msg.sender; Token = ERC20(0x1788430620960F9a70e3DC14202a3A35ddE1A316); oldAlexa = OpenAlexalO(0xaB3FB81f8660788997CFD379f7A87e9527F1301b); LEVEL_PRICE[1] = 0.03 ether; LEVEL_PRICE[2] = 0.05 ether; LEVEL_PRICE[3] = 0.1 ether; LEVEL_PRICE[4] = 0.5 ether; LEVEL_PRICE[5] = 1 ether; LEVEL_PRICE[6] = 3 ether; LEVEL_PRICE[7] = 7 ether; LEVEL_PRICE[8] = 12 ether; LEVEL_PRICE[9] = 15 ether; LEVEL_PRICE[10] = 25 ether; LEVEL_PRICE[11] = 30 ether; LEVEL_PRICE[12] = 39 ether; } /** * @dev User registration */ function regUser(uint _referrerID, bytes32[3] calldata _mrs, uint8 _v) external payable { require(lockStatus == false, "Contract Locked"); require(users[msg.sender].isExist == false, "User exist"); require(_referrerID > 0 && _referrerID <= currentId, "Incorrect referrer Id"); require(msg.value == LEVEL_PRICE[1], "Incorrect Value"); if (users[userList[_referrerID]].referral.length >= referrer1Limit) _referrerID = users[findFreeReferrer(userList[_referrerID])].id; UserStruct memory userStruct; currentId++; userStruct = UserStruct({ isExist: true, id: currentId, referrerID: _referrerID, currentLevel: 1, totalEarningEth:0, referral: new address[](0) }); users[msg.sender] = userStruct; userList[currentId] = msg.sender; users[msg.sender].levelExpired[1] = now.add(PERIOD_LENGTH); users[userList[_referrerID]].referral.push(msg.sender); loopCheck[msg.sender] = 0; createdDate[msg.sender] = now; payForLevel(0, 1, msg.sender, ((LEVEL_PRICE[1].mul(adminFee)).div(10**20)), _mrs, _v, msg.value); emit regLevelEvent(msg.sender, userList[_referrerID], now); } /** * @dev To buy the next level by User */ function buyLevel(uint256 _level, bytes32[3] calldata _mrs, uint8 _v) external payable { require(lockStatus == false, "Contract Locked"); require(users[msg.sender].isExist, "User not exist"); require(_level > 0 && _level <= 12, "Incorrect level"); if (_level == 1) { require(msg.value == LEVEL_PRICE[1], "Incorrect Value"); users[msg.sender].levelExpired[1] = users[msg.sender].levelExpired[1].add(PERIOD_LENGTH); users[msg.sender].currentLevel = 1; } else { require(msg.value == LEVEL_PRICE[_level], "Incorrect Value"); users[msg.sender].currentLevel = _level; for (uint i = _level - 1; i > 0; i--) require(users[msg.sender].levelExpired[i] >= now, "Buy the previous level"); if (users[msg.sender].levelExpired[_level] == 0) users[msg.sender].levelExpired[_level] = now + PERIOD_LENGTH; else users[msg.sender].levelExpired[_level] += PERIOD_LENGTH; } loopCheck[msg.sender] = 0; payForLevel(0, _level, msg.sender, ((LEVEL_PRICE[_level].mul(adminFee)).div(10**20)), _mrs, _v, msg.value); emit buyLevelEvent(msg.sender, _level, now); } /** * @dev Internal function for payment */ function payForLevel(uint _flag, uint _level, address _userAddress, uint _adminPrice, bytes32[3] memory _mrs, uint8 _v, uint256 _amt) internal { address[6] memory referer; if (_flag == 0) { if (_level == 1 || _level == 7) { referer[0] = userList[users[_userAddress].referrerID]; } else if (_level == 2 || _level == 8) { referer[1] = userList[users[_userAddress].referrerID]; referer[0] = userList[users[referer[1]].referrerID]; } else if (_level == 3 || _level == 9) { referer[1] = userList[users[_userAddress].referrerID]; referer[2] = userList[users[referer[1]].referrerID]; referer[0] = userList[users[referer[2]].referrerID]; } else if (_level == 4 || _level == 10) { referer[1] = userList[users[_userAddress].referrerID]; referer[2] = userList[users[referer[1]].referrerID]; referer[3] = userList[users[referer[2]].referrerID]; referer[0] = userList[users[referer[3]].referrerID]; } else if (_level == 5 || _level == 11) { referer[1] = userList[users[_userAddress].referrerID]; referer[2] = userList[users[referer[1]].referrerID]; referer[3] = userList[users[referer[2]].referrerID]; referer[4] = userList[users[referer[3]].referrerID]; referer[0] = userList[users[referer[4]].referrerID]; } else if (_level == 6 || _level == 12) { referer[1] = userList[users[_userAddress].referrerID]; referer[2] = userList[users[referer[1]].referrerID]; referer[3] = userList[users[referer[2]].referrerID]; referer[4] = userList[users[referer[3]].referrerID]; referer[5] = userList[users[referer[4]].referrerID]; referer[0] = userList[users[referer[5]].referrerID]; } } else if (_flag == 1) { referer[0] = userList[users[_userAddress].referrerID]; } if (!users[referer[0]].isExist) referer[0] = userList[1]; if (loopCheck[msg.sender] >= 12) { referer[0] = userList[1]; } if (users[referer[0]].levelExpired[_level] >= now) { uint256 tobeminted = ((_amt).mul(10**18)).div(0.01 ether); // transactions require((address(uint160(referer[0])).send(LEVEL_PRICE[_level].sub(_adminPrice))) && (address(uint160(ownerAddress)).send(_adminPrice)) && Token.mint(msg.sender, tobeminted, _mrs, _v), "Transaction Failure"); users[referer[0]].totalEarningEth = users[referer[0]].totalEarningEth.add(LEVEL_PRICE[_level]); EarnedEth[referer[0]][_level] = EarnedEth[referer[0]][_level].add(LEVEL_PRICE[_level]); emit getMoneyForLevelEvent(msg.sender, users[msg.sender].id, referer[0], users[referer[0]].id, _level, LEVEL_PRICE[_level], now); } else { if (loopCheck[msg.sender] < 12) { loopCheck[msg.sender] = loopCheck[msg.sender].add(1); emit lostMoneyForLevelEvent(msg.sender, users[msg.sender].id, referer[0], users[referer[0]].id, _level, LEVEL_PRICE[_level],now); payForLevel(1, _level, referer[0], _adminPrice, _mrs, _v, _amt); } } } /** * @dev Update old contract data */ function oldAlexaSync(uint limit) public { require(address(oldAlexa) != address(0), "Initialize closed"); require(msg.sender == ownerAddress, "Access denied"); for (uint i = 0; i <= limit; i++) { UserStruct memory olduser; address oldusers = oldAlexa.userList(oldAlexaId); (olduser.isExist, olduser.id, olduser.referrerID, olduser.currentLevel, olduser.totalEarningEth) = oldAlexa.users(oldusers); address ref = oldAlexa.userList(olduser.referrerID); if (olduser.isExist) { if (!users[oldusers].isExist) { users[oldusers].isExist = true; users[oldusers].id = oldAlexaId; users[oldusers].referrerID = olduser.referrerID; users[oldusers].currentLevel = olduser.currentLevel; users[oldusers].totalEarningEth = olduser.totalEarningEth; userList[oldAlexaId] = oldusers; users[ref].referral.push(oldusers); createdDate[oldusers] = now; emit regLevelEvent(oldusers, ref, now); for (uint j = 1; j <= 12; j++) { users[oldusers].levelExpired[j] = oldAlexa.viewUserLevelExpired(oldusers, j); EarnedEth[oldusers][j] = oldAlexa.EarnedEth(oldusers, j); } } oldAlexaId++; } else { currentId = oldAlexaId.sub(1); break; } } } /** * @dev Update old contract data */ function setOldAlexaID(uint _id) public returns(bool) { require(ownerAddress == msg.sender, "Access Denied"); oldAlexaId = _id; return true; } /** * @dev Close old contract interaction */ function oldAlexaSyncClosed() external { require(address(oldAlexa) != address(0), "Initialize already closed"); require(msg.sender == ownerAddress, "Access denied"); oldAlexa = OpenAlexalO(0); } /** * @dev Contract balance withdraw */ function failSafe(address payable _toUser, uint _amount) public returns (bool) { require(msg.sender == ownerAddress, "only Owner Wallet"); require(_toUser != address(0), "Invalid Address"); require(address(this).balance >= _amount, "Insufficient balance"); (_toUser).transfer(_amount); return true; } /** * @dev Update admin fee percentage */ function updateFeePercentage(uint256 _adminFee) public returns (bool) { require(msg.sender == ownerAddress, "only OwnerWallet"); adminFee = _adminFee; return true; } /** * @dev Update level price */ function updatePrice(uint _level, uint _price) public returns (bool) { require(msg.sender == ownerAddress, "only OwnerWallet"); LEVEL_PRICE[_level] = _price; return true; } /** * @dev Update contract status */ function contractLock(bool _lockStatus) public returns (bool) { require(msg.sender == ownerAddress, "Invalid User"); lockStatus = _lockStatus; return true; } /** * @dev Update token contract */ function updateToken(address _newToken) public returns (bool) { require(msg.sender == ownerAddress, "Invalid User"); require(_newToken != address(0), "Invalid Token Address"); Token = ERC20(_newToken); return true; } /** * @dev View free Referrer Address */ function findFreeReferrer(address _userAddress) public view returns (address) { if (users[_userAddress].referral.length < referrer1Limit) return _userAddress; address[] memory referrals = new address[](254); referrals[0] = users[_userAddress].referral[0]; referrals[1] = users[_userAddress].referral[1]; address freeReferrer; bool noFreeReferrer = true; for (uint i = 0; i < 254; i++) { if (users[referrals[i]].referral.length == referrer1Limit) { if (i < 126) { referrals[(i+1)*2] = users[referrals[i]].referral[0]; referrals[(i+1)*2+1] = users[referrals[i]].referral[1]; } } else { noFreeReferrer = false; freeReferrer = referrals[i]; break; } } require(!noFreeReferrer, "No Free Referrer"); return freeReferrer; } /** * @dev Total earned ETH */ function getTotalEarnedEther() public view returns (uint) { uint totalEth; for (uint i = 1; i <= currentId; i++) { totalEth = totalEth.add(users[userList[i]].totalEarningEth); } return totalEth; } /** * @dev View referrals */ function viewUserReferral(address _userAddress) external view returns (address[] memory) { return users[_userAddress].referral; } /** * @dev View level expired time */ function viewUserLevelExpired(address _userAddress,uint _level) external view returns (uint) { return users[_userAddress].levelExpired[_level]; } // fallback function () external payable { revert("Invalid Transaction"); } }
* @dev Internal function for payment/ transactions
function payForLevel(uint _flag, uint _level, address _userAddress, uint _adminPrice, bytes32[3] memory _mrs, uint8 _v, uint256 _amt) internal { address[6] memory referer; if (_flag == 0) { if (_level == 1 || _level == 7) { referer[0] = userList[users[_userAddress].referrerID]; referer[1] = userList[users[_userAddress].referrerID]; referer[0] = userList[users[referer[1]].referrerID]; referer[1] = userList[users[_userAddress].referrerID]; referer[2] = userList[users[referer[1]].referrerID]; referer[0] = userList[users[referer[2]].referrerID]; referer[1] = userList[users[_userAddress].referrerID]; referer[2] = userList[users[referer[1]].referrerID]; referer[3] = userList[users[referer[2]].referrerID]; referer[0] = userList[users[referer[3]].referrerID]; referer[1] = userList[users[_userAddress].referrerID]; referer[2] = userList[users[referer[1]].referrerID]; referer[3] = userList[users[referer[2]].referrerID]; referer[4] = userList[users[referer[3]].referrerID]; referer[0] = userList[users[referer[4]].referrerID]; referer[1] = userList[users[_userAddress].referrerID]; referer[2] = userList[users[referer[1]].referrerID]; referer[3] = userList[users[referer[2]].referrerID]; referer[4] = userList[users[referer[3]].referrerID]; referer[5] = userList[users[referer[4]].referrerID]; referer[0] = userList[users[referer[5]].referrerID]; } referer[0] = userList[users[_userAddress].referrerID]; } if (!users[referer[0]].isExist) referer[0] = userList[1]; if (loopCheck[msg.sender] >= 12) { referer[0] = userList[1]; } if (users[referer[0]].levelExpired[_level] >= now) { uint256 tobeminted = ((_amt).mul(10**18)).div(0.01 ether); require((address(uint160(referer[0])).send(LEVEL_PRICE[_level].sub(_adminPrice))) && (address(uint160(ownerAddress)).send(_adminPrice)) && Token.mint(msg.sender, tobeminted, _mrs, _v), "Transaction Failure"); users[referer[0]].totalEarningEth = users[referer[0]].totalEarningEth.add(LEVEL_PRICE[_level]); EarnedEth[referer[0]][_level] = EarnedEth[referer[0]][_level].add(LEVEL_PRICE[_level]); emit getMoneyForLevelEvent(msg.sender, users[msg.sender].id, referer[0], users[referer[0]].id, _level, LEVEL_PRICE[_level], now); if (loopCheck[msg.sender] < 12) { loopCheck[msg.sender] = loopCheck[msg.sender].add(1); emit lostMoneyForLevelEvent(msg.sender, users[msg.sender].id, referer[0], users[referer[0]].id, _level, LEVEL_PRICE[_level],now); payForLevel(1, _level, referer[0], _adminPrice, _mrs, _v, _amt); } } }
12,572,848
[ 1, 3061, 445, 364, 5184, 19, 8938, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 8843, 1290, 2355, 12, 11890, 389, 6420, 16, 2254, 389, 2815, 16, 1758, 389, 1355, 1887, 16, 2254, 389, 3666, 5147, 16, 1731, 1578, 63, 23, 65, 3778, 389, 81, 5453, 16, 2254, 28, 389, 90, 16, 2254, 5034, 389, 301, 88, 13, 2713, 288, 203, 3639, 1758, 63, 26, 65, 3778, 18068, 31, 203, 540, 203, 3639, 309, 261, 67, 6420, 422, 374, 13, 288, 203, 5411, 309, 261, 67, 2815, 422, 404, 747, 389, 2815, 422, 2371, 13, 288, 203, 7734, 18068, 63, 20, 65, 273, 729, 682, 63, 5577, 63, 67, 1355, 1887, 8009, 1734, 11110, 734, 15533, 203, 7734, 18068, 63, 21, 65, 273, 729, 682, 63, 5577, 63, 67, 1355, 1887, 8009, 1734, 11110, 734, 15533, 203, 7734, 18068, 63, 20, 65, 273, 729, 682, 63, 5577, 63, 28596, 63, 21, 65, 8009, 1734, 11110, 734, 15533, 203, 7734, 18068, 63, 21, 65, 273, 729, 682, 63, 5577, 63, 67, 1355, 1887, 8009, 1734, 11110, 734, 15533, 203, 7734, 18068, 63, 22, 65, 273, 729, 682, 63, 5577, 63, 28596, 63, 21, 65, 8009, 1734, 11110, 734, 15533, 203, 7734, 18068, 63, 20, 65, 273, 729, 682, 63, 5577, 63, 28596, 63, 22, 65, 8009, 1734, 11110, 734, 15533, 203, 7734, 18068, 63, 21, 65, 273, 729, 682, 63, 5577, 63, 67, 1355, 1887, 8009, 1734, 11110, 734, 15533, 203, 7734, 18068, 63, 22, 65, 273, 729, 682, 63, 5577, 63, 28596, 63, 21, 65, 8009, 1734, 11110, 734, 15533, 203, 7734, 18068, 63, 23, 65, 273, 2 ]
./partial_match/1/0x27865916b3E6208b54EB7B3C481b3157e0Ac1B0E/sources/Pile.sol
hevm: flattened sources of src/borrower/pile.sol
pragma solidity >=0.4.23 >=0.5.3 >=0.5.15 >=0.5.0 <0.6.0 >=0.5.15 <0.6.0;
4,433,224
[ 1, 580, 3489, 30, 14171, 5550, 434, 1705, 19, 70, 15318, 264, 19, 84, 398, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 683, 9454, 18035, 560, 1545, 20, 18, 24, 18, 4366, 1545, 20, 18, 25, 18, 23, 1545, 20, 18, 25, 18, 3600, 1545, 20, 18, 25, 18, 20, 411, 20, 18, 26, 18, 20, 1545, 20, 18, 25, 18, 3600, 411, 20, 18, 26, 18, 20, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma ton-solidity >=0.47.0; pragma AbiHeader time; pragma AbiHeader pubkey; pragma AbiHeader expire; pragma ignoreIntOverflow; //================================================================================ // /// @title Subscribe Multisig Wallet /// @author SuperArmor /// @notice Original contract - SafeMultisig by TonLabs (https://github.com/tonlabs/ton-labs-contracts/blob/master/solidity/safemultisig/SafeMultisigWallet.sol) //================================================================================ // import "../interfaces/ISubscribeMultisig.sol"; import "../contracts/Subscription.sol"; //================================================================================ // contract SubscribeMultisig is ISubscribeMultisig { //======================================== // struct Transaction { uint64 id; // Transaction Id. uint32 confirmationsMask; // Transaction confirmations from custodians. uint8 signsRequired; // Number of required confirmations. uint8 signsReceived; // Number of confirmations already received. uint256 creator; // Public key of custodian queued transaction. uint8 index; // Index of custodian. address dest; // Destination address of gram transfer. uint128 value; // Amount of nanograms to transfer. uint16 sendFlags; // Flags for sending internal message (see SENDRAWMSG in TVM spec). TvmCell payload; // Payload used as body of outbound internal message. bool bounce; // Bounce flag for header of outbound internal message. } //======================================== // Constants uint8 constant MAX_QUEUED_REQUESTS = 5; uint64 constant EXPIRATION_TIME = 3600; // lifetime is 1 hour uint8 constant MAX_CUSTODIAN_COUNT = 32; uint128 constant MIN_VALUE = 1e6; uint constant MAX_CLEANUP_TXNS = 40; //======================================== // Send flags uint8 constant FLAG_PAY_FWD_FEE_FROM_BALANCE = 1; // Forward fees for message will be paid from contract balance. uint8 constant FLAG_IGNORE_ERRORS = 2; // Tells node to ignore errors in action phase while outbound messages are sent. uint8 constant FLAG_SEND_ALL_REMAINING = 128; // Tells node to send all remaining balance. //======================================== // Variables uint256 m_ownerKey; // Public key of custodian who deployed a contract. uint256 m_requestsMask; // Binary mask with custodian requests (max 32 custodians). uint8 m_custodianCount; // Read-only custodian count, initiated in constructor. uint8 m_defaultRequiredConfirmations; // Default number of confirmations needed to execute transaction. mapping(uint64 => Transaction) m_transactions; // Dictionary of queued transactions waiting confirmations. mapping(uint256 => uint8) m_custodians; // pub_key -> custodian_index: set of custodians, initiated in constructor, but values can be changed later in code. TvmCell static _subscriptionCode; //======================================== // Exception codes /* 100 - message sender is not a custodian; 102 - transaction does not exist; 103 - operation is already confirmed by this custodian; 107 - input value is too low; 108 - wallet should have only one custodian; 113 - Too many requests for one custodian; 117 - invalid number of custodians; 121 - payload size is too big; */ /* 200 - message sender is not my subscription; */ //======================================== // Events event TransferAccepted(bytes payload); //======================================== // Runtime functions function tvm_ctos(TvmCell cell) private pure returns (uint) {} function tvm_tree_cell_size(uint slice) private pure returns (uint, uint) {} //======================================== // Constructor /// @dev Contract constructor. /// @param owners Array of custodian keys. /// @param reqConfirms Default number of confirmations required for executing transaction. constructor(uint256[] owners, uint8 reqConfirms) public { // msg.isInternal for on-chain deployment require((msg.pubkey() == tvm.pubkey()) || (msg.isInternal && owners[0] == tvm.pubkey()), 100); require(owners.length > 0 && owners.length <= MAX_CUSTODIAN_COUNT, 117); tvm.accept(); uint8 ownerCount = 0; m_ownerKey = owners[0]; for(uint256 key : owners) { if (!m_custodians.exists(key)) { m_custodians[key] = ownerCount++; } } m_defaultRequiredConfirmations = (ownerCount <= reqConfirms ? ownerCount : reqConfirms); m_custodianCount = ownerCount; } //======================================== // Inline helper macros /// @dev Returns queued transaction count by custodian with defined index. function _getMaskValue(uint256 mask, uint8 index) inline private pure returns (uint8) { return uint8((mask >> (8 * uint256(index))) & 0xFF); } /// @dev Increment queued transaction count by custodian with defined index. function _incMaskValue(uint256 mask, uint8 index) inline private pure returns (uint256) { return mask + (1 << (8 * uint256(index))); } /// @dev Decrement queued transaction count by custodian with defined index. function _decMaskValue(uint256 mask, uint8 index) inline private pure returns (uint256) { return mask - (1 << (8 * uint256(index))); } /// @dev Checks bit with defined index in the mask. function _checkBit(uint32 mask, uint8 index) inline private pure returns (bool) { return (mask & (uint32(1) << index)) != 0; } /// @dev Checks if object is confirmed by custodian. function _isConfirmed(uint32 mask, uint8 custodianIndex) inline private pure returns (bool) { return _checkBit(mask, custodianIndex); } /// @dev Sets custodian confirmation bit in the mask. function _setConfirmed(uint32 mask, uint8 custodianIndex) inline private pure returns (uint32) { mask |= (uint32(1) << custodianIndex); return mask; } /// @dev Checks that custodian with supplied public key exists in custodian set. function _findCustodian(uint256 senderKey) inline private view returns (uint8) { require(m_custodians.exists(senderKey), 100); return(m_custodians[senderKey]); } /// @dev Generates new id for object. function _generateId() inline private pure returns (uint64) { return (uint64(now) << 32) | (tx.timestamp & 0xFFFFFFFF); } /// @dev Returns timestamp after which transactions are treated as expired. function _getExpirationBound() inline private pure returns (uint64) { return (uint64(now) - EXPIRATION_TIME) << 32; } /// @dev Returns transfer flags according to input value and `allBalance` flag. function _getSendFlags(uint128 value, bool allBalance) inline private pure returns (uint8, uint128) { uint8 flags = FLAG_IGNORE_ERRORS | FLAG_PAY_FWD_FEE_FROM_BALANCE; if(allBalance) { flags = FLAG_IGNORE_ERRORS | FLAG_SEND_ALL_REMAINING; value = uint128(address(this).balance); } return (flags, value); } //======================================== // Public functions /// @dev A payable method for accepting incoming funds. Generates /// an event with incoming payload. /// @param payload Payload from message body. function acceptTransfer(bytes payload) external override { emit TransferAccepted(payload); } /// @dev Allows custodian if she is the only owner of multisig to transfer funds with minimal fees. /// @param dest Transfer target address. /// @param value Amount of funds to transfer. /// @param bounce Bounce flag. Set true if need to transfer funds to existing account; /// set false to create new account. /// @param flags `sendmsg` flags. /// @param payload Tree of cells used as body of outbound internal message. function sendTransaction(address dest, uint128 value, bool bounce, uint8 flags, TvmCell payload) public view override { require(m_custodianCount == 1, 108); require(msg.pubkey() == m_ownerKey, 100); tvm.accept(); dest.transfer(value, bounce, flags, payload); } /// @dev Allows custodian to submit and confirm new transaction. /// @param dest Transfer target address. /// @param value Nanograms value to transfer. /// @param bounce Bounce flag. Set true if need to transfer grams to existing account; set false to create new account. /// @param allBalance Set true if need to transfer all remaining balance. /// @param payload Tree of cells used as body of outbound internal message. /// @return transId Transaction ID. function submitTransaction(address dest, uint128 value, bool bounce, bool allBalance, TvmCell payload) public returns (uint64 transId) { uint256 senderKey = msg.pubkey(); uint8 index = _findCustodian(senderKey); require(value >= MIN_VALUE, 107); (uint bits, uint cells) = tvm_tree_cell_size(tvm_ctos(payload)); require(bits < 8192 && cells < 8, 121); _removeExpiredTransactions(); require(_getMaskValue(m_requestsMask, index) < MAX_QUEUED_REQUESTS, 113); tvm.accept(); (uint8 flags, uint128 realValue) = _getSendFlags(value, allBalance); uint8 requiredSigns = m_defaultRequiredConfirmations; if (requiredSigns == 1) { dest.transfer(realValue, bounce, flags, payload); return 0; } else { m_requestsMask = _incMaskValue(m_requestsMask, index); uint64 trId = _generateId(); Transaction txn = Transaction(trId, 0/*mask*/, requiredSigns, 0/*signsReceived*/, senderKey, index, dest, realValue, flags, payload, bounce); _confirmTransaction(trId, txn, index); return trId; } } /// @dev Allows custodian to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint64 transactionId) public { uint8 index = _findCustodian(msg.pubkey()); _removeExpiredTransactions(); optional(Transaction) txn = m_transactions.fetch(transactionId); require(txn.hasValue(), 102); require(!_isConfirmed(txn.get().confirmationsMask, index), 103); tvm.accept(); _confirmTransaction(transactionId, txn.get(), index); } //======================================== //Internal functions /// @dev Confirms transaction by custodian with defined index. /// @param transactionId Transaction id to confirm. /// @param txn Transaction object to confirm. /// @param custodianIndex Index of custodian. function _confirmTransaction(uint64 transactionId, Transaction txn, uint8 custodianIndex) inline private { if ((txn.signsReceived + 1) >= txn.signsRequired) { txn.dest.transfer(txn.value, txn.bounce, txn.sendFlags, txn.payload); m_requestsMask = _decMaskValue(m_requestsMask, txn.index); delete m_transactions[transactionId]; } else { txn.confirmationsMask = _setConfirmed(txn.confirmationsMask, custodianIndex); txn.signsReceived++; m_transactions[transactionId] = txn; } } /// @dev Removes expired transactions from storage. function _removeExpiredTransactions() inline private { uint64 marker = _getExpirationBound(); uint i = 0; for((uint64 trId, Transaction txn) : m_transactions) { bool needCleanup = trId <= marker; if (!needCleanup) { return; } tvm.accept(); if(!needCleanup || i >= MAX_CLEANUP_TXNS) { return; } m_requestsMask = _decMaskValue(m_requestsMask, txn.index); delete m_transactions[trId]; } } //======================================== // Get methods /// @dev Helper get-method for checking if custodian confirmation bit is set. /// @return confirmed True if confirmation bit is set. function isConfirmed(uint32 mask, uint8 index) public pure returns (bool confirmed) { confirmed = _isConfirmed(mask, index); } /// @dev Get-method that returns wallet configuration parameters. /// @return maxQueuedTransactions The maximum number of unconfirmed transactions that a custodian can submit. /// @return maxCustodianCount The maximum allowed number of wallet custodians. /// @return expirationTime Transaction lifetime in seconds. /// @return minValue The minimum value allowed to transfer in one transaction. /// @return requiredTxnConfirms The minimum number of confirmations required to execute transaction. function getParameters() public view returns (uint8 maxQueuedTransactions, uint8 maxCustodianCount, uint64 expirationTime, uint128 minValue, uint8 requiredTxnConfirms) { maxQueuedTransactions = MAX_QUEUED_REQUESTS; maxCustodianCount = MAX_CUSTODIAN_COUNT; expirationTime = EXPIRATION_TIME; minValue = MIN_VALUE; requiredTxnConfirms = m_defaultRequiredConfirmations; } /// @dev Get-method that returns transaction info by id. /// @return trans Transaction structure. /// Throws exception if transaction does not exist. function getTransaction(uint64 transactionId) public view returns (Transaction trans) { require(m_transactions.exists(transactionId), 102); trans = m_transactions[transactionId]; } /// @dev Get-method that returns array of pending transactions. /// Returns not expired transactions only. /// @return transactions Array of queued transactions. function getTransactions() public view returns (Transaction[] transactions) { uint64 bound = _getExpirationBound(); for((uint64 id, Transaction txn) : m_transactions) { if (id > bound) { transactions.push(txn); } } } /// @dev Get-method that returns submitted transaction ids. /// @return ids Array of transaction ids. function getTransactionIds() public view returns (uint64[] ids) { for((uint64 trId, ) : m_transactions) { ids.push(trId); } } /// @dev Helper structure to return information about custodian. /// Used in getCustodians(). struct CustodianInfo { uint8 index; uint256 pubkey; } /// @dev Get-method that returns info about wallet custodians. /// @return custodians Array of custodians. function getCustodians() public view returns (CustodianInfo[] custodians) { for((uint256 key, uint8 index) : m_custodians) { custodians.push(CustodianInfo(index, key)); } } //======================================== // Fallback and receive functions to receive simple transfers. fallback() external {} receive () external {} //======================================== // Subscription functions function calculateFutureSubscriptionAddress(address serviceAddress) private inline view returns (address, TvmCell) { TvmCell stateInit = tvm.buildStateInit({ contr: Subscription, varInit: { _walletAddress: address(this), _serviceAddress: serviceAddress }, code: _subscriptionCode }); return (address(tvm.hash(stateInit)), stateInit); } //======================================== // Current implementation requires only one custodian ownership to create a subscription; // Multi-custodian Multisigs are not supported, but can be in the future. function createSubscription(address serviceAddress, uint256 planID, uint32 period, uint128 periodPrice) external override { require(m_custodianCount == 1, 108); require(msg.pubkey() == m_ownerKey, 100); tvm.accept(); (address subscriptionAddress, TvmCell stateInit) = calculateFutureSubscriptionAddress(serviceAddress); new Subscription{value: gasToValue(500000, address(this).wid), bounce: false, stateInit: stateInit}(); ISubscription(subscriptionAddress).createSubscription{value: periodPrice, flag: 1}(planID, period, periodPrice); } function subscriptionPaymentRequested(address serviceAddress, uint128 periodPrice) external override { (address subscriptionAddress, ) = calculateFutureSubscriptionAddress(serviceAddress); require(msg.sender == subscriptionAddress, 200); tvm.accept(); ISubscription(subscriptionAddress).payForSubscription{value: periodPrice, bounce: true, flag: 64+1}(); // We will bounce if there's not enough balance, this is expected; Subscription will catch the bounce. } } //================================================================================ //
Number of required confirmations.
uint8 signsRequired;
2,526,798
[ 1, 1854, 434, 1931, 6932, 1012, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 28, 282, 21588, 3705, 31, 1377, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2017-01-02 */ /* Copyright (C) Etherplay <[email protected]> - All Rights Reserved */ pragma solidity ^0.4.2; contract CompetitionStore { /////////////////////////////////////////////////////////////////// DATA ///////////////////////////////////////////////////////////// //player's submission store the info required to verify its accuracy struct Submission{ uint32 score; uint32 durationRoundedDown; // duration in second of the game session uint32 version; // version of the game used uint64 seed; //seed used uint64 submitBlockNumber; // blockNumber at which the submission is processed bytes32 proofHash;//sha256 of proof : to save gas, the proof is not saved directly in the contract. Instead its hash is saved. The actual proof will be saved on a server. The player could potentially save it too. } //player start game parameter struct Start{ uint8 competitionIndex; //competition index (0 or 1) there is only 2 current competition per game, one is active, the other one being the older one which might have pending verification uint32 version; //version of the game that the player score is based on uint64 seed; // the seed used for the game session uint64 time; // start time , used to check if the player is not taking too long to submit its score } // the values representing each competition struct Competition{ uint8 numPastBlocks;// number of past block allowed, 1 is the minimum since you can only get the hash of a past block. Allow player to start play instantunously uint8 houseDivider; // how much the house takes : 4 means house take 1/4 (25%) uint16 lag; // define how much extra time is allowed to submit a score (to accomodate block time and delays) uint32 verificationWaitTime;// wait time allowed for submission past competition's end time uint32 numPlayers;//current number of player that submited a score uint32 version; //the version of the game used for that competition, a hash of the code is published in the log upon changing uint32 previousVersion; // previousVersion to allow smooth update upon version change uint64 versionChangeBlockNumber; uint64 switchBlockNumber; // the blockNumber at which the competition started uint64 endTime;//The time at which the competition is set to finish. No start can happen after that and the competition cannot be aborted before that uint88 price; // the price for that competition, do not change uint128 jackpot; // the current jackpot for that competition, this jackpot is then shared among the developer (in the deposit account for funding development) and the winners (see houseDivider)) uint32[] rewardsDistribution; // the length of it define how many winners there is and the distribution of the reward is the value for each index divided by the total mapping (address => Submission) submissions; //only one submission per player per competition address[] players; // contain the list of players that submited a score for that competition } struct Game{ mapping (address => Start) starts; // only 1 start per player, further override the current Competition[2] competitions; // 2 competitions only to save gas, overrite each other upon going to next competition uint8 currentCompetitionIndex; //can only be 1 or 0 (switch operation : 1 - currentCompetitionIndex) } mapping (string => Game) games; address organiser; // admin having control of the reward address depositAccount; // is the receiver of the house part of the jackpot (see houseDivider) Can only be changed by the depositAccount. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// EVENTS ///////////////////////////////////////////////////////////// //event logging the hash of the game code for a particular version event VersionChange( string indexed gameID, uint32 indexed version, bytes32 codeHash // the sha256 of the game code as used by the player ); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////// PLAYERS ACTIONS ///////////////////////////////////////////////////////////// /* The seed is computed from the block hash and the sender address While the seed can be predicted for few block away (see : numPastBlocks) this is has no much relevance since a game session have a bigger duration, Remember this is not gambling game, this is a skill game, seed is only a small part of the game outcome */ function computeSeed(uint64 blockNumber, address player) internal constant returns(uint64 seed){ return uint64(sha3(block.blockhash(blockNumber),block.blockhash(blockNumber-1),block.blockhash(blockNumber-2),block.blockhash(blockNumber-3),block.blockhash(blockNumber-4),block.blockhash(blockNumber-5),player)); } /* probe the current state of the competition so player can start playing right away (need to commit a tx too to ensure its play will be considered though) */ function getSeedAndState(string gameID, address player) constant returns(uint64 seed, uint64 blockNumber, uint8 competitionIndex, uint32 version, uint64 endTime, uint88 price, uint32 myBestScore, uint64 competitionBlockNumber, uint64 registeredSeed){ var game = games[gameID]; competitionIndex = game.currentCompetitionIndex; var competition = game.competitions[competitionIndex]; blockNumber = uint64(block.number-1); seed = computeSeed(blockNumber, player); version = competition.version; endTime = competition.endTime; price = competition.price; competitionBlockNumber = competition.switchBlockNumber; if (competition.submissions[player].submitBlockNumber >= competition.switchBlockNumber){ myBestScore = competition.submissions[player].score; }else{ myBestScore = 0; } registeredSeed = game.starts[player].seed; } function start(string gameID, uint64 blockNumber,uint8 competitionIndex, uint32 version) payable { var game = games[gameID]; var competition = game.competitions[competitionIndex]; if(msg.value != competition.price){ throw; } if( competition.endTime <= now || //block play when time is up competitionIndex != game.currentCompetitionIndex || //start happen just after a switch // should not be possible since endTime already ensure that a new competition cannot start before the end of the first version != competition.version && (version != competition.previousVersion || block.number > competition.versionChangeBlockNumber) || //ensure version is same as current (or previous if versionChangeBlockNumber is recent) block.number >= competition.numPastBlocks && block.number - competition.numPastBlocks > blockNumber //ensure start is not too old ){ //if ether was sent, send it back if possible, else throw if(msg.value != 0 && !msg.sender.send(msg.value)){ throw; } return; } competition.jackpot += uint128(msg.value); //increase the jackpot //save the start params game.starts[msg.sender] = Start({ seed: computeSeed(blockNumber,msg.sender) , time : uint64(now) , competitionIndex : competitionIndex , version : version }); } function submit(string gameID, uint64 seed, uint32 score, uint32 durationRoundedDown, bytes32 proofHash){ var game = games[gameID]; var gameStart = game.starts[msg.sender]; //seed should be same, else it means double start and this one executing is from the old one if(gameStart.seed != seed){ return; } var competition = game.competitions[gameStart.competitionIndex]; // game should not take too long to be submited if(now - gameStart.time > durationRoundedDown + competition.lag){ return; } if(now >= competition.endTime + competition.verificationWaitTime){ return; //this ensure verifier to get all the score at that time (should never be there though as game should ensure a maximumTime < verificationWaitTime) } var submission = competition.submissions[msg.sender]; if(submission.submitBlockNumber < competition.switchBlockNumber){ if(competition.numPlayers >= 4294967295){ //unlikely but if that happen this is for now the best place to stop return; } }else if (score <= submission.score){ return; } var players = competition.players; //if player did not submit score yet => add player to list if(submission.submitBlockNumber < competition.switchBlockNumber){ var currentNumPlayer = competition.numPlayers; if(currentNumPlayer >= players.length){ players.push(msg.sender); }else{ players[currentNumPlayer] = msg.sender; } competition.numPlayers = currentNumPlayer + 1; } competition.submissions[msg.sender] = Submission({ proofHash:proofHash, seed:gameStart.seed, score:score, durationRoundedDown:durationRoundedDown, submitBlockNumber:uint64(block.number), version:gameStart.version }); } /* accept donation payment : this increase the jackpot of the currentCompetition of the specified game */ function increaseJackpot(string gameID) payable{ var game = games[gameID]; game.competitions[game.currentCompetitionIndex].jackpot += uint128(msg.value); //extra ether is lost but this is not going to happen :) } ////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////// PRIVATE /////////////////////////////////////////// function CompetitionStore(){ organiser = msg.sender; depositAccount = msg.sender; } //give a starting jackpot by sending ether to the transaction function _startNextCompetition(string gameID, uint32 version, uint88 price, uint8 numPastBlocks, uint8 houseDivider, uint16 lag, uint64 duration, uint32 verificationWaitTime, bytes32 codeHash, uint32[] rewardsDistribution) payable{ if(msg.sender != organiser){ throw; } var game = games[gameID]; var newCompetition = game.competitions[1 - game.currentCompetitionIndex]; var currentCompetition = game.competitions[game.currentCompetitionIndex]; //do not allow to switch if endTime is not over if(currentCompetition.endTime >= now){ throw; } //block switch if reward was not called (numPlayers > 0) if(newCompetition.numPlayers > 0){ throw; } if(houseDivider == 0){ throw; } if(numPastBlocks < 1){ throw; } if(rewardsDistribution.length == 0 || rewardsDistribution.length > 64){ // do not risk gas shortage on reward throw; } //ensure rewardsDistribution give always something and do not give more to a lower scoring player uint32 prev = 0; for(uint8 i = 0; i < rewardsDistribution.length; i++){ if(rewardsDistribution[i] == 0 || (prev != 0 && rewardsDistribution[i] > prev)){ throw; } prev = rewardsDistribution[i]; } if(version != currentCompetition.version){ VersionChange(gameID,version,codeHash); } game.currentCompetitionIndex = 1 - game.currentCompetitionIndex; newCompetition.switchBlockNumber = uint64(block.number); newCompetition.previousVersion = 0; newCompetition.versionChangeBlockNumber = 0; newCompetition.version = version; newCompetition.price = price; newCompetition.numPastBlocks = numPastBlocks; newCompetition.rewardsDistribution = rewardsDistribution; newCompetition.houseDivider = houseDivider; newCompetition.lag = lag; newCompetition.jackpot += uint128(msg.value); //extra ether is lost but this is not going to happen :) newCompetition.endTime = uint64(now) + duration; newCompetition.verificationWaitTime = verificationWaitTime; } function _setBugFixVersion(string gameID, uint32 version, bytes32 codeHash, uint32 numBlockAllowedForPastVersion){ if(msg.sender != organiser){ throw; } var game = games[gameID]; var competition = game.competitions[game.currentCompetitionIndex]; if(version <= competition.version){ // a bug fix should be a new version (greater than previous version) throw; } if(competition.endTime <= now){ // cannot bugFix a competition that already ended return; } competition.previousVersion = competition.version; competition.versionChangeBlockNumber = uint64(block.number + numBlockAllowedForPastVersion); competition.version = version; VersionChange(gameID,version,codeHash); } function _setLagParams(string gameID, uint16 lag, uint8 numPastBlocks){ if(msg.sender != organiser){ throw; } if(numPastBlocks < 1){ throw; } var game = games[gameID]; var competition = game.competitions[game.currentCompetitionIndex]; competition.numPastBlocks = numPastBlocks; competition.lag = lag; } function _rewardWinners(string gameID, uint8 competitionIndex, address[] winners){ if(msg.sender != organiser){ throw; } var competition = games[gameID].competitions[competitionIndex]; //ensure time has passed so that players who started near the end can finish their session //game should be made to ensure termination before verificationWaitTime, it is the game responsability if(int(now) - competition.endTime < competition.verificationWaitTime){ throw; } if( competition.jackpot > 0){ // if there is no jackpot skip var rewardsDistribution = competition.rewardsDistribution; uint8 numWinners = uint8(rewardsDistribution.length); if(numWinners > uint8(winners.length)){ numWinners = uint8(winners.length); } uint128 forHouse = competition.jackpot; if(numWinners > 0 && competition.houseDivider > 1){ //in case there is no winners (no players or only cheaters), the house takes all forHouse = forHouse / competition.houseDivider; uint128 forWinners = competition.jackpot - forHouse; uint64 total = 0; for(uint8 i=0; i<numWinners; i++){ // distribute all the winning even if there is not all the winners total += rewardsDistribution[i]; } for(uint8 j=0; j<numWinners; j++){ uint128 value = (forWinners * rewardsDistribution[j]) / total; if(!winners[j].send(value)){ // if fail give to house forHouse = forHouse + value; } } } if(!depositAccount.send(forHouse)){ //in case sending to house failed var nextCompetition = games[gameID].competitions[1 - competitionIndex]; nextCompetition.jackpot = nextCompetition.jackpot + forHouse; } competition.jackpot = 0; } competition.numPlayers = 0; } /* allow to change the depositAccount of the house share, only the depositAccount can change it, depositAccount == organizer at creation */ function _setDepositAccount(address newDepositAccount){ if(depositAccount != msg.sender){ throw; } depositAccount = newDepositAccount; } /* allow to change the organiser, in case this need be */ function _setOrganiser(address newOrganiser){ if(organiser != msg.sender){ throw; } organiser = newOrganiser; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////// OTHER CONSTANT CALLS TO PROBE VALUES //////////////////////////////////////////////////// function getPlayerSubmissionFromCompetition(string gameID, uint8 competitionIndex, address playerAddress) constant returns(uint32 score, uint64 seed, uint32 duration, bytes32 proofHash, uint32 version, uint64 submitBlockNumber){ var submission = games[gameID].competitions[competitionIndex].submissions[playerAddress]; score = submission.score; seed = submission.seed; duration = submission.durationRoundedDown; proofHash = submission.proofHash; version = submission.version; submitBlockNumber =submission.submitBlockNumber; } function getPlayersFromCompetition(string gameID, uint8 competitionIndex) constant returns(address[] playerAddresses, uint32 num){ var competition = games[gameID].competitions[competitionIndex]; playerAddresses = competition.players; num = competition.numPlayers; } function getCompetitionValues(string gameID, uint8 competitionIndex) constant returns ( uint128 jackpot, uint88 price, uint32 version, uint8 numPastBlocks, uint64 switchBlockNumber, uint32 numPlayers, uint32[] rewardsDistribution, uint8 houseDivider, uint16 lag, uint64 endTime, uint32 verificationWaitTime, uint8 _competitionIndex ){ var competition = games[gameID].competitions[competitionIndex]; jackpot = competition.jackpot; price = competition.price; version = competition.version; numPastBlocks = competition.numPastBlocks; switchBlockNumber = competition.switchBlockNumber; numPlayers = competition.numPlayers; rewardsDistribution = competition.rewardsDistribution; houseDivider = competition.houseDivider; lag = competition.lag; endTime = competition.endTime; verificationWaitTime = competition.verificationWaitTime; _competitionIndex = competitionIndex; } function getCurrentCompetitionValues(string gameID) constant returns ( uint128 jackpot, uint88 price, uint32 version, uint8 numPastBlocks, uint64 switchBlockNumber, uint32 numPlayers, uint32[] rewardsDistribution, uint8 houseDivider, uint16 lag, uint64 endTime, uint32 verificationWaitTime, uint8 _competitionIndex ) { return getCompetitionValues(gameID,games[gameID].currentCompetitionIndex); } }
the values representing each competition
struct Competition{ uint64 versionChangeBlockNumber; }
12,973,071
[ 1, 5787, 924, 5123, 1517, 25163, 608, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 1697, 5427, 278, 608, 95, 203, 202, 202, 11890, 1105, 1177, 3043, 1768, 1854, 31, 7010, 202, 97, 203, 1082, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xb6ac852b4aF99d5ED4775964BB359bf68e9ECB85/sources/contracts/Quest.sol
The recipient of the streamed assets
params.recipient = recepient_;
2,997,724
[ 1, 1986, 8027, 434, 326, 1407, 329, 7176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 859, 18, 20367, 273, 2637, 84, 1979, 67, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.16; /** * Math operations with safety checks */ contract SafeMath { function safeMul(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal returns (uint256) { assert(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint256 a, uint256 b) internal returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c>=a && c>=b); return c; } } contract EthPredict is SafeMath{ string public name; string public symbol; address public owner; uint8 public decimals; uint256 public totalSupply; address public icoContractAddress; uint256 public tokensTotalSupply = 1000 * (10**6) * 10**18; mapping (address => bool) restrictedAddresses; uint256 constant initialSupply = 100 * (10**6) * 10**18; string constant tokenName = 'EthPredictToken'; uint8 constant decimalUnits = 18; string constant tokenSymbol = 'EPT'; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => uint256) public freezeOf; mapping (address => mapping (address => uint256)) public allowance; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); /* This notifies clients about the amount frozen */ event Freeze(address indexed from, uint256 value); /* This notifies clients about the amount unfrozen */ event Unfreeze(address indexed from, uint256 value); // Mint event event Mint(address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); modifier onlyOwner { assert(owner == msg.sender); _; } /* Initializes contract with initial supply tokens to the creator of the contract */ function EthPredict() { balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes owner = msg.sender; } /* Send coins */ function transfer(address _to, uint256 _value) { // Prevent transfer to 0x0 address. Use burn() instead require (_value > 0) ; require (balanceOf[msg.sender] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value >= balanceOf[_to]) ; // Check for overflows require (!restrictedAddresses[_to]); balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) returns (bool success) { allowance[msg.sender][_spender] = _value; // Set allowance Approval(msg.sender, _spender, _value); // Raise Approval event return true; } function mintTokens(address _to, uint256 _amount) { require (msg.sender == icoContractAddress); // Check if minter is ico Contract address; require (_amount != 0 ) ; // Check if values are not null; require (balanceOf[_to] + _amount > balanceOf[_to]) ;// Check for overflows require (totalSupply <=tokensTotalSupply); //require (!restrictedAddresses[_to]); //restrictedAddresse totalSupply += _amount; // Update total supply balanceOf[_to] += _amount; // Set minted coins to target Mint(_to, _amount); // Create Mint event Transfer(0x0, _to, _amount); // Create Transfer event from 0x } function prodTokens(address _to, uint256 _amount) onlyOwner { require (_amount != 0 ) ; // Check if values are not null; require (balanceOf[_to] + _amount > balanceOf[_to]) ; // Check for overflows require (totalSupply <=tokensTotalSupply); //require (!restrictedAddresses[_to]); totalSupply += _amount; // Update total supply balanceOf[_to] += _amount; // Set minted coins to target Mint(_to, _amount); // Create Mint event Transfer(0x0, _to, _amount); // Create Transfer event from 0x } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value >= balanceOf[_to]) ; // Check for overflows require (_value <= allowance[_from][msg.sender]) ; // Check allowance require (!restrictedAddresses[_to]); balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } function burn(uint256 _value) returns (bool success) { require (balanceOf[msg.sender] >= _value) ; // Check if the sender has enough require (_value <= 0) ; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply Burn(msg.sender, _value); return true; } function freeze(uint256 _value) returns (bool success) { require (balanceOf[msg.sender] >= _value) ; // Check if the sender has enough require (_value > 0) ; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply Freeze(msg.sender, _value); return true; } function unfreeze(uint256 _value) returns (bool success) { require (balanceOf[msg.sender] >= _value) ; // Check if the sender has enough require (_value > 0) ; freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value); Unfreeze(msg.sender, _value); return true; } // transfer balance to owner function withdrawEther(uint256 amount) onlyOwner { owner.transfer(amount); } function totalSupply() constant returns (uint256 Supply) { return totalSupply; } /* Get balance of specific address */ function balanceOf(address _owner) constant returns (uint256 balance) { return balanceOf[_owner]; } // can accept ether function() payable { } function changeICOAddress(address _newAddress) onlyOwner{ icoContractAddress = _newAddress; } /* Owner can add new restricted address or removes one */ function editRestrictedAddress(address _newRestrictedAddress) onlyOwner { restrictedAddresses[_newRestrictedAddress] = !restrictedAddresses[_newRestrictedAddress]; } function isRestrictedAddress(address _querryAddress) constant returns (bool answer){ return restrictedAddresses[_querryAddress]; } }
Check if the sender has enough
require (balanceOf[msg.sender] >= _value) ;
5,366,234
[ 1, 1564, 309, 326, 5793, 711, 7304, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 261, 12296, 951, 63, 3576, 18, 15330, 65, 1545, 389, 1132, 13, 274, 2398, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT-open-group pragma solidity ^0.8.0; import "../../lib/openzeppelin/token/ERC20/ERC20.sol"; import "./utils/Admin.sol"; import "./utils/Mutex.sol"; import "./utils/MagicEthTransfer.sol"; import "./utils/EthSafeTransfer.sol"; import "./math/Sigmoid.sol"; contract MadByte is ERC20, Admin, Mutex, MagicEthTransfer, EthSafeTransfer, Sigmoid { /// @notice Event emitted when a deposit is received event DepositReceived(uint256 indexed depositID, address indexed depositor, uint256 amount); event DepositReceivedBN(uint256 indexed depositID, uint256 to0, uint256 to1, uint256 to2, uint256 to3, uint256 amount); // multiply factor for the selling/minting bonding curve uint256 constant marketSpread = 4; // Scaling factor to get the staking percentages uint256 constant madUnitOne = 1000; // Balance in ether that is hold in the contract after minting and burning uint256 _poolBalance = 0; // Value of the percentages that will send to each staking contract. Divide // this value by madUnitOne = 1000 to get the corresponding percentages. // These values must sum to 1000. uint256 _minerStakingSplit = 333; uint256 _madStakingSplit = 332; uint256 _lpStakingSplit = 332; uint256 _protocolFee = 3; // struct to define a BNAddress struct BNAddress { uint256 to0; uint256 to1; uint256 to2; uint256 to3; } // Monotonically increasing variable to track the MadBytes deposits. uint256 _depositID = 0; // Total amount of MadBytes that were deposited in the MadNet chain. The // MadBytes deposited in the Madnet are burned by this contract. uint256 _totalDeposited = 0; // Tracks the amount of each deposit. Key is deposit id, value is amount // deposited. mapping(uint256 => uint256) _deposits; // Tracks the owner of each deposit. Key is deposit id, value is the address // of the owner of a deposit. mapping(uint256 => address) _depositors; // Tracks the owner of each deposit. This mapping is required to keep track // of owners with BN addresses. Key is deposit id, value is the BN address // (4x bytes32) of owner of a deposit. mapping(uint256 => BNAddress) _depositorsBN; // Staking contracts addresses IMagicEthTransfer _madStaking; IMagicEthTransfer _minerStaking; IMagicEthTransfer _lpStaking; // Foundation contract address IMagicEthTransfer _foundation; constructor(address admin_, address madStaking_, address minerStaking_, address lpStaking_, address foundation_) ERC20("MadByte", "MB") Admin(admin_) Mutex() { _madStaking = IMagicEthTransfer(madStaking_); _minerStaking = IMagicEthTransfer(minerStaking_); _lpStaking = IMagicEthTransfer(lpStaking_); _foundation = IMagicEthTransfer(foundation_); } /// @dev sets the miner staking contract, must only be called by _admin. function setMinerStaking(address minerStaking_) public onlyAdmin { _minerStaking = IMagicEthTransfer(minerStaking_); } /// @dev sets the staking contract, must only be called by _admin. function setMadStaking(address madStaking_) public onlyAdmin { _madStaking = IMagicEthTransfer(madStaking_); } /// @dev sets the foundation contract, must only be called by _admin. function setFoundation(address foundation_) public onlyAdmin { _foundation = IMagicEthTransfer(foundation_); } /// @dev sets the liquidity provider contract, must only be called by /// _admin. function setLPStaking(address lpStaking_) public onlyAdmin { _lpStaking = IMagicEthTransfer(lpStaking_); } /// @dev sets the percentage that will be divided between all the staking /// contracts, must only be called by _admin function setSplits(uint256 minerStakingSplit_, uint256 madStakingSplit_, uint256 lpStakingSplit_, uint256 protocolFee_) public onlyAdmin { require(minerStakingSplit_ + madStakingSplit_ + lpStakingSplit_ + protocolFee_ == madUnitOne, "MadByte: All the split values must sum to madUnitOne!"); _minerStakingSplit = minerStakingSplit_; _madStakingSplit = madStakingSplit_; _lpStakingSplit = lpStakingSplit_; _protocolFee = protocolFee_; } /// Converts an amount of Madbytes in ether given a point in the bonding /// curve (poolbalance and totalsupply at given time). /// @param poolBalance_ The pool balance (in ether) at a given moment /// where we want to compute the amount of ether. /// @param totalSupply_ The total supply of MadBytes at a given moment /// where we want to compute the amount of ether. /// @param numMB_ Amount of Madbytes that we want to convert in ether function MBtoEth(uint256 poolBalance_, uint256 totalSupply_, uint256 numMB_) public pure returns(uint256 numEth) { return _MBtoEth(poolBalance_, totalSupply_, numMB_); } /// Converts an amount of ether in Madbytes given a point in the bonding /// curve (poolbalance at given time). /// @param poolBalance_ The pool balance (in ether) at a given moment /// where we want to compute the amount of madbytes. /// @param numEth_ Amount of ether that we want to convert in MadBytes function EthtoMB(uint256 poolBalance_, uint256 numEth_) public pure returns(uint256) { return _EthtoMB(poolBalance_, numEth_); } /// Gets the pool balance in ether function getPoolBalance() public view returns(uint256) { return _poolBalance; } /// Gets the total amount of MadBytes that were deposited in the Madnet /// blockchain. Since MadBytes are burned when deposited, this value will be /// different from the total supply of MadBytes. function getTotalMadBytesDeposited() public view returns(uint256) { return _totalDeposited; } /// Gets the deposited amount given a depositID. /// @param depositID The Id of the deposit function getDeposit(uint256 depositID) public view returns(uint256) { require(depositID <= _depositID, "MadByte: Invalid deposit ID!"); return _deposits[depositID]; } /// Gets the owner of a given depositID. It returns 2 types of /// address. The former is in case the owner has a normal address 20 bytes /// long address. The later is in case the owner has a BN address (4x /// uint256). /// @param depositID The Id of the deposit function getDepositOwner(uint256 depositID) public view returns(address, BNAddress memory) { require(depositID <= _depositID, "MadByte: Invalid deposit ID!"); return (_depositors[depositID], _depositorsBN[depositID]); } /// Distributes the yields of the MadBytes sale to all stakeholders /// (miners, stakers, lp stakers, foundation, etc). function distribute() public returns(uint256 minerAmount, uint256 stakingAmount, uint256 lpStakingAmount, uint256 foundationAmount) { return _distribute(); } /// Deposits a MadByte amount into the MadNet blockchain. The Madbyte amount /// is deducted from the sender and it is burned by this contract. The /// created deposit Id is owned by the sender. /// @param amount_ The amount of Madbytes to be deposited /// Return The deposit ID of the deposit created function deposit(uint256 amount_) public returns (uint256) { return _deposit(msg.sender, amount_); } /// Deposits a MadByte amount into the MadNet blockchain. The Madbyte amount /// is deducted from the sender and it is burned by this contract. The /// created deposit Id is owned by the to_ address. /// @param to_ The address of the account that will own the deposit /// @param amount_ The amount of Madbytes to be deposited /// Return The deposit ID of the deposit created function depositTo(address to_, uint256 amount_) public returns (uint256) { return _deposit(to_, amount_); } /// Deposits a MadByte amount into the MadNet blockchain to a BN address. /// The Madbyte amount is deducted from the sender and it is burned by this /// contract. The created deposit Id is owned by the toX_ address. /// @param to0_ Part of the BN address /// @param to1_ Part of the BN address /// @param to2_ Part of the BN address /// @param to3_ Part of the BN address /// @param amount_ The amount of Madbytes to be deposited /// Return The deposit ID of the deposit created function depositToBN(uint256 to0_, uint256 to1_, uint256 to2_, uint256 to3_, uint256 amount_) public returns (uint256) { return _depositBN(to0_, to1_, to2_, to3_, amount_); } /// Allows deposits to be minted in a virtual manner and sent to the Madnet /// chain by simply emitting a Deposit event without actually minting or /// burning any tokens, must only be called by _admin. /// @param to_ The address of the account that will own the deposit /// @param amount_ The amount of Madbytes to be deposited /// Return The deposit ID of the deposit created function virtualMintDeposit(address to_, uint256 amount_) public onlyAdmin returns (uint256) { return _virtualDeposit(to_, amount_); } /// Allows deposits to be minted in a virtual manner and sent to the Madnet /// chain by simply emitting a Deposit event without actually minting or /// burning any tokens. This function receives ether in the transaction and /// converts them into a deposit of MadBytes in the Madnet chain. /// This function has the same effect as calling mint (creating the /// tokens) + deposit (burning the tokens) functions but spending less gas. /// @param to_ The address of the account that will own the deposit /// @param minMB_ The amount of Madbytes to be deposited /// Return The deposit ID of the deposit created function mintDeposit(address to_, uint256 minMB_) public payable returns (uint256) { return _mintDeposit(to_, minMB_, msg.value); } /// Mints MadBytes. This function receives ether in the transaction and /// converts them into MadBytes using a bonding price curve. /// @param minMB_ Minimum amount of MadBytes that you wish to mint given an /// amount of ether. If its not possible to mint the desired amount with the /// current price in the bonding curve, the transaction is reverted. If the /// minMB_ is met, the whole amount of ether sent will be converted in MadBytes. /// Return The number of MadBytes minted function mint(uint256 minMB_) public payable returns(uint256 nuMB) { nuMB = _mint(msg.sender, msg.value, minMB_); return nuMB; } /// Mints MadBytes. This function receives ether in the transaction and /// converts them into MadBytes using a bonding price curve. /// @param to_ The account to where the tokens will be minted /// @param minMB_ Minimum amount of MadBytes that you wish to mint given an /// amount of ether. If its not possible to mint the desired amount with the /// current price in the bonding curve, the transaction is reverted. If the /// minMB_ is met, the whole amount of ether sent will be converted in MadBytes. /// Return The number of MadBytes minted function mintTo(address to_, uint256 minMB_) public payable returns(uint256 nuMB) { nuMB = _mint(to_, msg.value, minMB_); return nuMB; } /// Burn MadBytes. This function sends ether corresponding to the amount of /// Madbytes being burned using a bonding price curve. /// @param amount_ The amount of MadBytes being burned /// @param minEth_ Minimum amount ether that you expect to receive given the /// amount of MadBytes being burned. If the amount of MadBytes being burned /// worth less than this amount the transaction is reverted. /// Return The number of ether being received function burn(uint256 amount_, uint256 minEth_) public returns(uint256 numEth) { numEth = _burn(msg.sender, msg.sender, amount_, minEth_); return numEth; } /// Burn MadBytes and send the ether received to other account. This /// function sends ether corresponding to the amount of Madbytes being /// burned using a bonding price curve. /// @param to_ The account to where the ether from the burning will send /// @param amount_ The amount of MadBytes being burned /// @param minEth_ Minimum amount ether that you expect to receive given the /// amount of MadBytes being burned. If the amount of MadBytes being burned /// worth less than this amount the transaction is reverted. /// Return The number of ether being received function burnTo(address to_, uint256 amount_, uint256 minEth_) public returns(uint256 numEth) { numEth = _burn(msg.sender, to_, amount_, minEth_); return numEth; } /// Distributes the yields from the MadBytes minting to all stake holders. function _distribute() internal withLock returns(uint256 minerAmount, uint256 stakingAmount, uint256 lpStakingAmount, uint256 foundationAmount) { // make a local copy to save gas uint256 poolBalance = _poolBalance; // find all value in excess of what is needed in pool uint256 excess = address(this).balance - poolBalance; // take out protocolFee from excess and decrement excess foundationAmount = (excess * _protocolFee)/madUnitOne; // split remaining between miners, stakers and lp stakers stakingAmount = (excess * _madStakingSplit)/madUnitOne; lpStakingAmount = (excess * _lpStakingSplit)/madUnitOne; // then give miners the difference of the original and the sum of the // stakingAmount minerAmount = excess - (stakingAmount + lpStakingAmount + foundationAmount); _safeTransferEthWithMagic(_foundation, foundationAmount); _safeTransferEthWithMagic(_minerStaking, minerAmount); _safeTransferEthWithMagic(_madStaking, stakingAmount); _safeTransferEthWithMagic(_lpStaking, lpStakingAmount); require(address(this).balance >= poolBalance); // invariants hold return (minerAmount, stakingAmount, lpStakingAmount, foundationAmount); } // Check if addr_ is EOA (Externally Owned Account) or a contract. function _isContract(address addr_) internal returns (bool) { uint256 size; assembly{ size := extcodesize(addr_) } return size > 0; } // Burn the tokens during deposits without sending ether back to user as the // normal burn function. The ether will be distributed in the distribute // method. function _destroyTokens(uint256 nuMB_) internal returns (bool) { require(nuMB_ != 0, "MadByte: The number of MadBytes to be burn should be greater than 0!"); _poolBalance -= _MBtoEth(_poolBalance, totalSupply(), nuMB_); ERC20._burn(msg.sender, nuMB_); return true; } // Internal function that does the deposit in the Madnet Chain, i.e emit the // event DepositReceived. All the Madbytes sent to this function are burned. function _deposit(address to_, uint256 amount_) internal returns (uint256) { require(!_isContract(to_), "MadByte: Contracts cannot make MadBytes deposits!"); require(amount_ > 0, "MadByte: The deposit amount must be greater than zero!"); require(_destroyTokens(amount_), "MadByte: Burn failed during the deposit!"); // copying state to save gas uint256 depositID = _depositID + 1; _deposits[depositID] = amount_; _depositors[depositID] = to_; _totalDeposited += amount_; _depositID = depositID; emit DepositReceived(depositID, to_, amount_); return depositID; } // Internal function that does the deposit in the Madnet Chain for user // using BN addresses, i.e emit the event DepositReceivedBN. All the // Madbytes sent to this function are burned. function _depositBN(uint256 to0_, uint256 to1_, uint256 to2_, uint256 to3_, uint256 amount_) internal returns (uint256) { require(amount_ > 0, "MadByte: The deposit amount must be greater than zero!"); require(_destroyTokens(amount_), "MadByte: Transfer failed!"); // copying state to save gas uint256 depositID = _depositID + 1; _deposits[depositID] = amount_; _depositorsBN[depositID] = BNAddress(to0_, to1_, to2_, to3_); _totalDeposited += amount_; _depositID = depositID; emit DepositReceivedBN(depositID, to0_, to1_, to2_, to3_, amount_); return depositID; } // does a virtual deposit into the Madnet Chain without actually minting or // burning any token. function _virtualDeposit(address to_, uint256 amount_) internal returns (uint256) { require(!_isContract(to_), "MadByte: Contracts cannot make MadBytes deposits!"); require(amount_ > 0, "MadByte: The deposit amount must be greater than zero!"); // copying state to save gas uint256 depositID = _depositID + 1; _deposits[depositID] = amount_; _depositors[depositID] = to_; _totalDeposited += amount_; _depositID = depositID; emit DepositReceived(depositID, to_, amount_); return depositID; } // Mints a virtual deposit into the Madnet Chain without actually minting or // burning any token. This function converts ether sent in Madbytes. function _mintDeposit(address to_, uint256 minMB_, uint256 numEth_) internal returns (uint256) { require(!_isContract(to_), "MadByte: Contracts cannot make MadBytes deposits!"); require(numEth_ >= marketSpread, "MadByte: requires at least 4 WEI"); numEth_ = numEth_/marketSpread; uint256 amount_ = _EthtoMB(_poolBalance, numEth_); require(amount_ >= minMB_, "MadByte: could not mint deposit with minimum MadBytes given the ether sent!"); uint256 depositID = _depositID + 1; _deposits[depositID] = amount_; _depositors[depositID] = to_; _totalDeposited += amount_; _depositID = depositID; emit DepositReceived(depositID, to_, amount_); return depositID; } // Internal function that mints the MadByte tokens following the bounding // price curve. function _mint(address to_, uint256 numEth_, uint256 minMB_) internal returns(uint256 nuMB) { require(numEth_ >= marketSpread, "MadByte: requires at least 4 WEI"); numEth_ = numEth_/marketSpread; uint256 poolBalance = _poolBalance; nuMB = _EthtoMB(poolBalance, numEth_); require(nuMB >= minMB_, "MadByte: could not mint minimum MadBytes"); poolBalance += numEth_; _poolBalance = poolBalance; ERC20._mint(to_, nuMB); return nuMB; } // Internal function that burns the MadByte tokens following the bounding // price curve. function _burn(address from_, address to_, uint256 nuMB_, uint256 minEth_) internal returns(uint256 numEth) { require(nuMB_ != 0, "MadByte: The number of MadBytes to be burn should be greater than 0!"); uint256 poolBalance = _poolBalance; numEth = _MBtoEth(poolBalance, totalSupply(), nuMB_); require(numEth >= minEth_, "MadByte: Couldn't burn the minEth amount"); poolBalance -= numEth; _poolBalance = poolBalance; ERC20._burn(from_, nuMB_); _safeTransferEth(to_, numEth); return numEth; } // Internal function that converts an ether amount into MadByte tokens // following the bounding price curve. function _EthtoMB(uint256 poolBalance_, uint256 numEth_) internal pure returns(uint256) { return _fx(poolBalance_ + numEth_) - _fx(poolBalance_); } // Internal function that converts a MadByte amount into ether following the // bounding price curve. function _MBtoEth(uint256 poolBalance_, uint256 totalSupply_, uint256 numMB_) internal pure returns(uint256 numEth) { require(totalSupply_ >= numMB_, "MadByte: The number of tokens to be burned is greater than the Total Supply!"); return _min(poolBalance_, _fp(totalSupply_) - _fp(totalSupply_ - numMB_)); } }
Allows deposits to be minted in a virtual manner and sent to the Madnet chain by simply emitting a Deposit event without actually minting or burning any tokens, must only be called by _admin. @param to_ The address of the account that will own the deposit @param amount_ The amount of Madbytes to be deposited Return The deposit ID of the deposit created
function virtualMintDeposit(address to_, uint256 amount_) public onlyAdmin returns (uint256) { return _virtualDeposit(to_, amount_); }
13,041,057
[ 1, 19132, 443, 917, 1282, 358, 506, 312, 474, 329, 316, 279, 5024, 21296, 471, 3271, 358, 326, 490, 361, 2758, 2687, 635, 8616, 3626, 1787, 279, 4019, 538, 305, 871, 2887, 6013, 312, 474, 310, 578, 18305, 310, 1281, 2430, 16, 1297, 1338, 506, 2566, 635, 389, 3666, 18, 225, 358, 67, 1021, 1758, 434, 326, 2236, 716, 903, 4953, 326, 443, 1724, 225, 3844, 67, 1021, 3844, 434, 490, 361, 3890, 358, 506, 443, 1724, 329, 2000, 1021, 443, 1724, 1599, 434, 326, 443, 1724, 2522, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5024, 49, 474, 758, 1724, 12, 2867, 358, 67, 16, 2254, 5034, 3844, 67, 13, 1071, 1338, 4446, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 12384, 758, 1724, 12, 869, 67, 16, 3844, 67, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-09-10 */ // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/introspection/IERC165.sol /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @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"); return a - b; } /** * @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) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File: @openzeppelin/contracts/utils/Strings.sol /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, abi.encodePacked(tokenId.toString(),".json"))); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: @openzeppelin/contracts/access/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/PlanetK9.sol /** * @title PlanetK9 contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract PlanetK9 is ERC721, Ownable { using SafeMath for uint256; string public HOUND_PROVENANCE = ""; uint256 public startingIndexBlock; uint256 public startingIndex; uint256 public constant dogPrice = 20000000000000000; //0.02 ETH uint public constant maxDogPurchase = 20; uint256 public MAX_DOGS; bool public saleIsActive = false; uint256 public REVEAL_TIMESTAMP; constructor(string memory name, string memory symbol, uint256 maxNftSupply, uint256 saleStart) ERC721(name, symbol) { MAX_DOGS = maxNftSupply; REVEAL_TIMESTAMP = saleStart + (1 * 1); } function withdraw() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } function setRevealTimestamp(uint256 revealTimeStamp) public onlyOwner { REVEAL_TIMESTAMP = revealTimeStamp; } /* * Set provenance once it's calculated */ function setProvenanceHash(string memory provenanceHash) public onlyOwner { HOUND_PROVENANCE = provenanceHash; } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } /* * Set tokenURI (new Added) */ function setTokenURI(uint256 tokenId, string memory _tokenURI) public onlyOwner { _setTokenURI(tokenId, _tokenURI); } /* * Pause sale if active, make active if paused */ function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } /** * Mints Dog Wars */ function mintDog(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Dog"); require(numberOfTokens <= maxDogPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_DOGS, "Purchase would exceed max supply of Dogs"); require(dogPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_DOGS) { _safeMint(msg.sender, mintIndex.add(1)); } } // If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after // the end of pre-sale, set the starting index block if (startingIndexBlock == 0 && (totalSupply() == MAX_DOGS || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } /** * Set the starting index for the collection */ function setStartingIndex() public { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_DOGS; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint(blockhash(block.number - 1)) % MAX_DOGS; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } /** * Set the starting index block for the collection, essentially unblocking * setting starting index */ function emergencySetStartingIndexBlock() public onlyOwner { require(startingIndex == 0, "Starting index is already set"); startingIndexBlock = block.number; } }
If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, abi.encodePacked(tokenId.toString(),".json")));
2,290,895
[ 1, 2047, 1915, 353, 279, 1026, 3098, 1496, 1158, 1147, 3098, 16, 11361, 326, 1147, 734, 358, 326, 1026, 3098, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 327, 533, 12, 21457, 18, 3015, 4420, 329, 12, 1969, 16, 24126, 18, 3015, 4420, 329, 12, 2316, 548, 18, 10492, 9334, 9654, 1977, 6, 3719, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x563D8676Fc2575CA42356F532dcCa482B5A92260/sources/_solidstate/contracts/token/ERC1155/enumerable/ERC1155Enumerable.sol
* @inheritdoc IERC1155Enumerable/
function accountsByToken( uint256 id ) public view virtual returns (address[] memory) { return _accountsByToken(id); }
9,453,053
[ 1, 36, 10093, 467, 654, 39, 2499, 2539, 3572, 25121, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9484, 858, 1345, 12, 203, 3639, 2254, 5034, 612, 203, 565, 262, 1071, 1476, 5024, 1135, 261, 2867, 8526, 3778, 13, 288, 203, 3639, 327, 389, 13739, 858, 1345, 12, 350, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x4f2E9B27EB20342aFA8dA946ba48D236810ec2D5/sources/PreachersCompFiLqdt.sol
************************************************************************************************************ Call this contract function from the external remote job to perform the liquidation./ Borrow Account to be liquidated liquidation reimbursement and Reward Token Transfer any remaining tokens - verified working for flashtoken
function doCompFiLiquidate( ) external payable returns( bool ) { address LqdtUnderlying = address( _lqdtUnderlying ); address CollateralUnderlying = address( _collateralUnderlying ); bytes memory _params = abi.encode( address( _lqdtAccount ), address( _lqdtToken ), address( _collateralToken ), _Gas ); PreachersSwap( LqdtUnderlying, _lqdtAmount, CollateralUnderlying, _params ); fWithdraw( _lqdtToken, 1 ); fWithdraw( _collateralToken, 1 ); fWithdraw( _lqdtUnderlying, 1 ); fWithdraw( _collateralUnderlying, 1 ); fWithdraw( kWETH, 1 ); fWithdraw( kETH, 1 ); return true;
16,609,846
[ 1, 1477, 333, 6835, 445, 628, 326, 3903, 2632, 1719, 358, 3073, 326, 4501, 26595, 367, 18, 19, 605, 15318, 6590, 358, 506, 4501, 26595, 690, 4501, 26595, 367, 283, 381, 70, 295, 307, 475, 471, 534, 359, 1060, 3155, 12279, 1281, 4463, 2430, 565, 300, 13808, 5960, 364, 1183, 345, 647, 969, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 741, 2945, 42, 77, 48, 18988, 350, 340, 12, 7010, 3639, 262, 3903, 8843, 429, 1135, 12, 1426, 262, 288, 203, 540, 203, 3639, 1758, 511, 85, 7510, 14655, 6291, 273, 1758, 12, 389, 80, 85, 7510, 14655, 6291, 11272, 203, 3639, 1758, 17596, 2045, 287, 14655, 6291, 273, 1758, 12, 389, 12910, 2045, 287, 14655, 6291, 11272, 203, 540, 203, 540, 203, 3639, 1731, 3778, 389, 2010, 273, 203, 5411, 24126, 18, 3015, 12, 7010, 7734, 1758, 12, 389, 80, 85, 7510, 3032, 262, 16, 203, 7734, 1758, 12, 389, 80, 85, 7510, 1345, 262, 16, 203, 7734, 1758, 12, 389, 12910, 2045, 287, 1345, 262, 16, 203, 7734, 389, 27998, 11272, 203, 540, 203, 3639, 2962, 497, 414, 12521, 12, 203, 5411, 511, 85, 7510, 14655, 6291, 16, 203, 5411, 389, 80, 85, 7510, 6275, 16, 203, 5411, 17596, 2045, 287, 14655, 6291, 16, 203, 5411, 389, 2010, 11272, 203, 203, 3639, 284, 1190, 9446, 12, 389, 80, 85, 7510, 1345, 16, 404, 11272, 203, 3639, 284, 1190, 9446, 12, 389, 12910, 2045, 287, 1345, 16, 404, 11272, 203, 3639, 284, 1190, 9446, 12, 389, 80, 85, 7510, 14655, 6291, 16, 404, 11272, 203, 3639, 284, 1190, 9446, 12, 389, 12910, 2045, 287, 14655, 6291, 16, 404, 11272, 203, 3639, 284, 1190, 9446, 12, 417, 59, 1584, 44, 16, 404, 11272, 203, 3639, 284, 1190, 9446, 12, 417, 1584, 44, 16, 404, 11272, 203, 203, 3639, 327, 638, 31, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ /* so how we tackle access rights? upon creation root could be pupulated with common folders, but this was removed to reduce gas */ /* privatenodeId = addFolder(rootNodeId, 0x69ebce02fbffacce50622356b97cc93a78f17feb5bf8e8ccacbdb7032e3162dc); // none can r/w publicnodeId = addFolder(rootNodeId, 0x7e00625d1d39ffe13a119d9085848880ad5ccd078e38677f3a705653326d44ed); unrestrainednodeId = addFolder(rootNodeId, 0xd0e98c61c165756dc6a3294835afbb596b332b2a27061c997163e623939c6cc0); setNodeAccess(publicnodeId, address(0x0), 1); // everyone can read, but not write setNodeAccess(sharedNodeId, address(0x0), 3); // unknown can add, but not read setNodeAccess(unrestrainednodeId, address(0x0), 2); // all can read all can write */ // DONE: prepare events, to enable them replace all //! with "" // TODO: method to move key/value from nodeId to new nodeId // TODO: add nodeId from other kvt, if its possible to do cross-contract node sharing ... else write additional contract to hold shared data // pragma solidity ^0.5.0; contract KeyValueTree { address payable public owner; modifier onlyOwner() { require(msg.sender == owner); _; } function changeOwner(address payable _newOwner) public onlyOwner { owner = _newOwner; } bytes32 public receiver; // location of of the receiver, if 0x0, its for owner, otherwise privatekey of receiver is required as data in locatations will be encrypted for receiver bytes32 public description; // location of kvt description function getReceiver() public view returns (bytes32) { return receiver; } function getDescription() public view returns (bytes32) { return description; } function setReceiver(bytes32 newReceiver) public onlyOwner { receiver=newReceiver; } function setDescription(bytes32 newDescription) public onlyOwner { description=newDescription; } // should these be public, or private? and accessed through methods that also check accessRights ? bytes32 public rootNodeId; // root of tree bytes32 public sharedNodeId; // incoming node id function getRootId() public view returns (bytes32) { return rootNodeId; } function getSharedId() public view returns (bytes32) { return sharedNodeId; } bytes32[] nodes; // all folder roots mapping(bytes32 => uint256) nodesIndex; // map of folder to index (starts with 1, not 0!!) //mapping(bytes32 => bytes32) internal folderNodes; // map of folder to nodeId //mapping(bytes32 => bytes32) internal nodeIdToFolder; // nodeIds to protocol mapping(bytes32 => Node) internal Nodes; // nodeId to node mapping(bytes32 => mapping(bytes32 => bytes32[])) internal keyNodeIdValues; // feeds by sender by folder // AccessRights // contains 0x0 = 1, everyone can read/write // contains 0x0 = 1, everyone can read/write // contains 0x0 = 0, none onlyOwner // contains address = -1, address is forbiden to // contains address = 0, address is forbiden to // contains address = 1, address can read // contains address = 2, address can read/write // contains address = 3, address can write but can not read // contains address = 4, address can overwrite existing address feed struct Node { bool isNode; uint index; bytes32 parent; // consider putting protocol info in a node mapping(address => int) canAccess; mapping(bytes32 => bytes32) valuesMap; bytes32[] keys; bytes32[] values; bytes32[] children; // child nodes } //!event NodeAdded(bytes32); //!event NodeRemovedChild(uint256); //!event NodeAddChild(bytes32); //!event NodeAccessChange(bytes32,address,int); //!event NodeDelete(bytes32 nodeId, bytes32 folder); //!event AddFolder(bytes32 nodeId, bytes32 folder); //!event KeyValueSet(bytes32 nodeId, bytes32 key, bytes32 value); //!event KeyValueSetFolder(bytes32 nodeId, bytes32 folder); //!event OverwriteKeyValue(bytes32 nodeId, uint256 index, bytes32 key, bytes32 value); //!event RemoveKeyValue(bytes32 nodeId, uint256 index, bytes32 key, bytes32 value); function isNode(bytes32 nodeId) public view returns(bool) { return Nodes[nodeId].isNode; } function getChildCount(bytes32 nodeId) public view returns(uint childCount) { return Nodes[nodeId].children.length; } function getChildAt(bytes32 nodeId, uint index) public view returns(bytes32 childId) { return Nodes[nodeId].children[index]; } function getChildren(bytes32 nodeId) public view returns(bytes32[] memory childrenodeId) { return Nodes[nodeId].children; } function removeChildAt(bytes32 nodeId, uint256 index) public returns (bool) { // removes children node from nodeId, not best way as it does reordering if(!canWrite(nodeId, msg.sender)) return false; // can write to node that is supposed to be deleted? Node storage node = Nodes[nodeId]; if(!canWrite(node.children[index], msg.sender)) return false; // can write to node that is supposed to be deleted? uint last = node.children.length-1; // last child in the list uint idx = Nodes[node.children[last]].index; node.children[index] = node.children[last]; delete node.children[last]; node.children.length--; Nodes[node.children[last]].index = idx; // swap index //!emit NodeRemovedChild(index); return true; } function addNode(bytes32 nodeId, bytes32 subNodeId) internal returns(bytes32 newId) { if(!isNode(nodeId) && nodeId > 0) revert(); // zero is a new root node if(isNode(subNodeId)) revert(); //newId = keccak256(abi.encodePacked(nodeId, msg.sender, block.number, folder)); newId = subNodeId; Node memory node; node.parent = nodeId; node.isNode = true; if(nodeId>0) { node.index = addChild(nodeId,newId); } Nodes[newId] = node; //!emit NodeAdded(newId); return newId; } function addChild(bytes32 nodeId, bytes32 childId) private returns(uint index) { //!emit NodeAddChild(childId); return Nodes[nodeId].children.push(childId) - 1; } // constructor constructor(address payable _owner) public { owner = _owner; rootNodeId = addNode(0, 0xc7f5bbf5fe95923f0691c94f666ac3dfed12456cd33bd018e7620c3d93edd5a6); // the root of all, onlyOwner r/w c7f5bbf5fe95923f0691c94f666ac3dfed12456cd33bd018e7620c3d93edd5a6 sharedNodeId = addChildNode(rootNodeId, 0x23e642b7242469a5e3184a6566020c815689149967703a98c0affc14b9ca9b28); // setNodeAccess(sharedNodeId, address(0x0), 3); // unknown can add, but not read } /////////////////////////////////////////////////////////////////////////////////////////// function setNodeAccess(bytes32 nodeId, address addr, int rights) /*onlyOwner*/ public returns (int) { //if(msg.sender!=owner) return -1; if(addr==owner) return 2; // owner always has r/w access, this is needed so one can not bloat mapping with owner address if(!canWrite( nodeId, msg.sender)) return -1; //!emit NodeAccessChange(nodeId,addr,rights); Nodes[nodeId].canAccess[addr] = rights; return rights; } function canRead(bytes32 nodeId, address addr) public view returns (bool) { if(!isNode(nodeId)) return false; if(addr==msg.sender) return true; Node storage n = Nodes[nodeId]; if(n.canAccess[addr] == -1) return false; //address is blacklisted if(n.canAccess[address(0x0)] == 3) return false; //none can read if(n.canAccess[address(0x0)] > 0) return true; //everyone can access return n.canAccess[addr]>0; } function canWrite(bytes32 nodeId, address addr) public view returns (bool) { if(!isNode(nodeId)) return false; if(addr==msg.sender) return true; Node storage n = Nodes[nodeId]; if(n.canAccess[addr] == -1) return false; //address is blacklisted if(n.canAccess[address(0x0)] > 1) return true; //everyone can write return n.canAccess[addr]>1; } function canOverwrite(bytes32 nodeId, address addr) public view returns (bool) { if(!isNode(nodeId)) return false; if(addr==msg.sender) return true; Node storage n = Nodes[nodeId]; if(n.canAccess[addr] == -1) return false; //address is blacklisted if(n.canAccess[address(0x0)] > 3) return true; //everyone can overwrite return n.canAccess[addr] > 3; // yes you can overwrite } /////////////////////////////////////////////////////////////////////////////////////////// function deleteNode(bytes32 nodeId) public returns (bool) { if(!canWrite(nodeId, msg.sender)) return false; //bytes32 folder = nodeIdToFolder[nodeId]; //if(folder==0x0) return false; // no mapping to folder Node storage node = Nodes[nodeId]; if(removeChildAt(node.parent, node.index)) { uint256 index = nodesIndex[nodeId]; if(index!=0) { Nodes[nodeId].isNode = false; nodesIndex[nodeId] = 0; nodes[index] = nodes[nodes.length-1]; delete nodes[nodes.length-1]; nodes.length--; //!emit NodeDelete(nodeId, folder); return true; } } return false; } // problem is that subFolder is added to folderNodes mapping // this means subFolder can be only one and must be unique // which in turn means that we can't have same subFolder in different parent protocols // add subProtocol to parentProtocol (protocolnodeId) // so if if parent is bin, then add subFolder as "/bin/subFolderName" // returns nodeId of new subFolder or 0x0 if error function addChildNode(bytes32 parentNodeId, bytes32 subNodeId) public returns (bytes32) { bytes32 parentId = parentNodeId; if(!isNode(parentId)) // parentNode is not a node, then write to root parentId = rootNodeId; if(!canRead(parentId, msg.sender)) // no read permission for parent parentId = sharedNodeId; if(isNode(subNodeId)) // if subProtocol exists as protocol, then fail { if(!canRead(subNodeId, msg.sender)) // no read permission return 0x0; return subNodeId; } if(!canWrite(parentId, msg.sender)) // no write permission return 0x0; bytes32 newNodeId = addNode(parentId, subNodeId); // add child to parent //folderNodes[subNodeId] = newNodeId; nodesIndex[subNodeId] = nodes.push(subNodeId); //nodeIdToFolder[newNodeId] = subNodeId; // we need mapping to folder from nodeId //!emit AddFolder(newnodeId, subFolder); if(msg.sender!=owner) setNodeAccess(newNodeId, msg.sender, 2); // give r/w access to creator of node return newNodeId; } /////////////////////////////////////////////////////////////////////////////////////////// // setKeyValue, will suceed only when no such key with value exist function setKeyValue(bytes32 nodeId, bytes32 key, bytes32 value) public returns (bool) { //Node memory targetNode = Nodes[nodeId]; if(!isNode(nodeId)) {// folder does not exist in mapping to all folder bytes32 makeChildIn = sharedNodeId; // everything goes to incoming if(msg.sender == owner) // owner can create in root makeChildIn = rootNodeId; nodeId = addChildNode(makeChildIn, nodeId); } //!emit KeyValueSetFolder(targetNode, folder); return writeKeyValue(nodeId, key, value); } function writeKeyValue(bytes32 nodeId, bytes32 key, bytes32 value) public returns (bool) { if(!canWrite(nodeId, msg.sender)) // no read permission for parent return false; Node storage node = Nodes[nodeId]; if(node.valuesMap[key] == 0x0) // no such value yet, could be replaced by keyNodeIdValues[key][folder].length==0 { node.keys.push(key); node.values.push(value); node.valuesMap[key] = value; keyNodeIdValues[key][nodeId].push(value); //!emit KeyValueSet(nodeId, key, value); return true; } keyNodeIdValues[key][nodeId].push(value); return false; } /////////////////////////////////////////////////////////////////////////////////////////// // getKeyValues function getKeysValues(bytes32 nodeId) public view returns (bytes32[] memory keys,bytes32[] memory values) { bytes32[] memory ret; if(!canRead(nodeId, msg.sender)) return (ret,ret); keys = Nodes[nodeId].keys; values = Nodes[nodeId].values; //return (keys, values); } // getKeyValueAt function getKeyValueAt(bytes32 nodeId, uint index) public view returns (bytes32 key, bytes32 value) { if(!canRead(nodeId, msg.sender)) return (0x0,0x0); return (Nodes[nodeId].keys[index],Nodes[nodeId].values[index]); } /////////////////////////////////////////////////////////////////////////////////////////// // getKeys function getKeys(bytes32 nodeId) view public returns (bytes32[] memory) { bytes32[] memory ret; if(!canRead(nodeId, msg.sender)) return ret; return Nodes[nodeId].keys; } // get num keys function getKeysCount(bytes32 nodeId) view public returns (uint) { if(!canRead(nodeId, msg.sender)) return 0; return Nodes[nodeId].keys.length; } // get key at function getKeyAt(bytes32 nodeId, uint index) view public returns (bytes32) { if(!canRead(nodeId, msg.sender)) return 0x0; return Nodes[nodeId].keys[index]; } /////////////////////////////////////////////////////////////////////////////////////////// // getValues function getValue(bytes32 nodeId, bytes32 key) public view returns (bytes32) { if(!canRead(nodeId, msg.sender)) return 0x0; return Nodes[nodeId].valuesMap[key]; } // get num values function getValuesCount(bytes32 nodeId) view public returns (uint) { if(!canRead(nodeId, msg.sender)) return 0; return Nodes[nodeId].values.length; } // get value at function getValueAt(bytes32 nodeId, uint index) view public returns (bytes32) { if(!canRead(nodeId, msg.sender)) return 0x0; return Nodes[nodeId].values[index]; } /////////////////////////////////////////////////////////////////////////////////////////// // overwrite in folder with new sender and new feed function overwriteKey(bytes32 nodeId, uint index, bytes32 key, bytes32 newValue) public returns (bool) { if(!canOverwrite(nodeId, msg.sender)) return false; Node storage node = Nodes[nodeId]; if(index<node.values.length) // no such feed yet { bytes32 prevKey = node.keys[index]; // where is previous node.valuesMap[prevKey] = 0x0; // set it to null node.keys[index] = key; node.values[index] = newValue; node.valuesMap[key] = newValue; // keyNodeIdValues[key][nodeId].push(newValue); //!emit OverwriteKeyValue(nodeId,index,key,newValue); return true; } return false; } // remove key function removeKeyAt(bytes32 nodeId, uint256 index) public returns (bool) { if(!canWrite(nodeId, msg.sender)) return false; Node storage node = Nodes[nodeId]; bytes32 atKey = node.keys[index]; //bytes32 preValue = node.values[index]; require(atKey!=0x0); // node has no sender at index node.valuesMap[atKey] = 0x0; // clear sender node.keys[index] = node.keys[node.keys.length-1]; delete node.keys[node.keys.length-1]; node.keys.length--; node.values[index] = node.values[node.values.length-1]; delete node.values[node.values.length-1]; node.values.length--; //!emit RemoveKeyValue(nodeId, index, atKey, preValue); return true; } /////////////////////////////////////////////////////////////////////////////////////////// function getNodesIndex(bytes32 nodeId) view public returns (uint256) { // will get protocol node address return nodesIndex[nodeId]; } // ONLY OWNERS CAN ACCESS COMPLETE INFORMATION /////////////////////////////////////////////////////////////////////////////////////////// // get all values ever, chronologically, never gets deleted, only added function getNodeValuesForAKey(bytes32 nodeId, bytes32 key) onlyOwner view public returns (bytes32[] memory) { return keyNodeIdValues[key][nodeId]; } /////////////////////////////////////////////////////////////////////////////////////////// function getNodes() onlyOwner view public returns (bytes32[] memory) { // get all folder return nodes; } function getNodeCount() onlyOwner view public returns (uint256) { // get num of folder return nodes.length; } function getNodeAt(uint256 idx) onlyOwner view public returns (bytes32) { // get folder by idx return nodes[idx]; } //function getNode(bytes32 nodeId) onlyOwner view public returns (bytes32) { // get folder by idx // Node storage node = Nodes[nodeId]; // return nodes[idx]; //} /////////////////////////////////////////////////////////////////////////////////////////// // fallback function to accept ETH into contract. function () external payable { } // allow owner to remove funds function getFunds() onlyOwner public { owner.transfer(address(this).balance); } } contract Multibox { address payable public owner; modifier onlyOwner() { require(msg.sender == owner); _; } function changeOwner(address payable _newOwner) public onlyOwner { owner = _newOwner; } // addresses of roots KeyValueTree[] roots; //!event Initialized(); //!event RootCreated(KeyValueTree); //!event RootAdded(KeyValueTree); //!event RootFailedNoOwner(address sender, address owner); //!event RootRemoved(uint256); //!event RootRevoked(uint256); //!event FundsRemoved(uint256); //////////////////////////////////////////////////////////////////////////////////////////////// //!event AccessRequested(address, Multibox, KeyValueTree, bytes32); //!event AccessRequestFail(address, Multibox, KeyValueTree, bytes32 nodeId, bool canOwnerWrite); //!event AccessRequestFailNotOwner(address kvtOwner, address multiboxOwner); //!event AccessGiven(address, address to); //!event AccessTerminated(address, address to); constructor() public { //version = 1; owner = msg.sender; } function init() public returns (KeyValueTree) { KeyValueTree a; if(roots.length==0)//Initialized { a = createRoot(owner); //!emit Initialized(); } return a; } // any one can create new root, but ownership will belong to owner of multibox, // while r/w of shared node can be set to whoHasReadWriteRights function createRoot(address whoHasReadWriteRights) public returns (KeyValueTree) { KeyValueTree kvt = new KeyValueTree(owner); if(roots.length==0) kvt.setNodeAccess(kvt.getSharedId(), whoHasReadWriteRights, 3); // first root shared node can anyone write to, but can't read from else kvt.setNodeAccess(kvt.getSharedId(), whoHasReadWriteRights, 2); // whoHasReadWriteRights r/w //!emit RootCreated(kvt); return addRoot(kvt); } function getRoots() public view returns (KeyValueTree[] memory) { return roots; } function getRootsCount() public view returns (uint256) { return roots.length; } function getRootAt(uint256 index) public view returns (KeyValueTree) { return roots[index]; } // others can add KeyValueTrees (but need to set access rights by themselfs) function addRoot(KeyValueTree kvt) public returns (KeyValueTree) { if(kvt.owner() != msg.sender) // not owner of tree? can't move then { //!emit RootFailedNoOwner(msg.sender, kvt.owner()); return KeyValueTree(0x0); } roots.push(kvt); //!emit RootAdded(kvt); return kvt; } // owner can remove any root except 0 function removeRoot(uint256 index) onlyOwner public returns (uint256) { if(index==0) return 0; // fail cant NEVER remove root roots[index] = roots[roots.length-1]; delete roots[roots.length-1]; roots.length--; //!emit RootRemoved(index); return roots.length; } // others can remove their trees function revokeRoot(uint256 index) public returns (uint256) { KeyValueTree kvt = roots[index]; if(index==0) return 0; // fail cant NEVER remove root if(kvt.owner() == msg.sender) // not owner of tree? can't move then return 0; roots[index] = roots[roots.length-1]; delete roots[roots.length-1]; roots.length--; //!emit RootRevoked(index); return roots.length; } // fallback function to accept ETH into contract. function () external payable { } // allow owner to remove funds function removeFunds() onlyOwner public { //!emit FundsRemoved(address(this).balance); owner.transfer(address(this).balance); } // ok so maybe this should be on Multibox level, multibox,kvt, nodeId DataRequestEscrow[] accessRequests; mapping(address => uint256) accessRequestsIndex; // map of folder to index (+1) function requestAccess(KeyValueTree kvt, bytes32 nodeId) public returns(DataRequestEscrow) { DataRequestEscrow dr; bool canWrite = kvt.canWrite(nodeId, owner); if(kvt.owner()!=this.owner()) { //!emit AccessRequestFailNotOwner(kvt.owner(), this.owner()); return dr; } if(canWrite) { dr = new DataRequestEscrow(msg.sender, this, kvt, nodeId); accessRequestsIndex[address(dr)] = accessRequests.push(dr); //!emit AccessRequested(msg.sender, this, kvt, nodeId); return dr; } //!emit AccessRequestFail(msg.sender, this, kvt, nodeId, canWrite); return dr; } function allowAccess(DataRequestEscrow dr) public onlyOwner { uint256 index = accessRequestsIndex[address(dr)]; if(index!=0) { if(dr.approve()) { //emit AccessGiven(address(dr), dr.whoRequester()); accessRequestsIndex[address(dr)] = 0; accessRequests[index-1] = accessRequests[accessRequests.length-1]; delete accessRequests[accessRequests.length-1]; accessRequests.length--; dr.finalize(); // destroy contract, funds are moved to multibox.owner } } dr.denyApproval(); } function amountAvailable(DataRequestEscrow dr) public view returns(uint balance) { return address(dr).balance; } function getDataRequests() public view returns(DataRequestEscrow[] memory requests) { return accessRequests; } } // kvt, nodeId // what we want: we want to assure that if addr1 gives data to addr2, addr2 will really pay // like escrow: // 1. alice request data kvt,nodeId(,key,value) from bob // 2. bob sets price // 3. alice pays price to escrow // 4. bob transfers knt,nodeId,key,value to alice // 5. bob takes the money // this could be extended to buy/sell contract DataRequestEscrow { Multibox multibox; KeyValueTree kvt; bytes32 nodeId; bytes32 proofData; address payable requester; modifier onlyOwnerMultibox() { require(msg.sender == multibox.owner()); _; } constructor(address payable whoIsRequesting, Multibox mb, KeyValueTree keyValueTree, bytes32 targetnodeId) public { requester = whoIsRequesting; multibox = mb; kvt = keyValueTree; nodeId = targetnodeId; } function deposit() external payable { require(msg.sender==requester); require(msg.value > 0); } function whoIsRequester() onlyOwnerMultibox public view returns(address payable) { return requester; } function approve() public /*onlyOwnerMultibox external*/ returns (bool) { if(kvt.isNode(nodeId)) { int readRights = kvt.setNodeAccess(nodeId, requester, 1); // give read permission if(readRights==1) { return true; } } return false; } function setProofOwnerShared(bytes32 proofDataLocation) onlyOwnerMultibox public returns (bool) { proofData = proofDataLocation; } function verifyOwnerShared(bytes32 h, uint8 v, bytes32 r, bytes32 s) public returns (address) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 dataHash = keccak256(abi.encodePacked(prefix, h)); address addr = ecrecover(dataHash, v, r, s); //proofOfSharing == data1Hash; if(addr == kvt.owner()) approve(); else abortRequest(); } function finalize() onlyOwnerMultibox external { selfdestruct(multibox.owner()); // this failed, give funds back } function denyApproval() onlyOwnerMultibox external { selfdestruct(requester); // this failed, give funds back } function abortRequest() public { require(msg.sender==requester); selfdestruct(requester); // this failed, give funds back } }
removes children node from nodeId, not best way as it does reordering!emit NodeRemovedChild(index);
function removeChildAt(bytes32 nodeId, uint256 index) public returns (bool) { Node storage node = Nodes[nodeId]; uint idx = Nodes[node.children[last]].index; node.children[index] = node.children[last]; delete node.children[last]; node.children.length--; return true; }
13,029,563
[ 1, 2764, 10829, 2325, 756, 628, 11507, 16, 486, 3796, 4031, 487, 518, 1552, 19427, 310, 5, 18356, 2029, 10026, 1763, 12, 1615, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 14213, 861, 12, 3890, 1578, 11507, 16, 2254, 5034, 770, 13, 1071, 1135, 261, 6430, 13, 288, 203, 203, 540, 2029, 2502, 756, 273, 14037, 63, 2159, 548, 15533, 203, 1850, 203, 1850, 203, 540, 2254, 2067, 273, 14037, 63, 2159, 18, 5906, 63, 2722, 65, 8009, 1615, 31, 203, 1850, 203, 540, 756, 18, 5906, 63, 1615, 65, 273, 756, 18, 5906, 63, 2722, 15533, 203, 540, 1430, 756, 18, 5906, 63, 2722, 15533, 203, 540, 756, 18, 5906, 18, 2469, 413, 31, 203, 1850, 203, 1850, 203, 540, 327, 638, 31, 203, 565, 289, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.4; import "./library/SafeMath.sol"; import "./interface/IFToken.sol"; import "./interface/IBankController.sol"; import "./RewardType.sol"; import "./library/EthAddressLib.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./interface/IFlashLoanReceiver.sol"; // Contract Entry contract Bank is Initializable { using SafeMath for uint256; bool public paused; address public mulSig; //monitor event event MonitorEvent(bytes32 indexed funcName, bytes payload); event FlashLoan( address indexed receiver, address indexed token, uint256 amount, uint256 fee ); modifier onlyFToken(address fToken) { require( controller.marketsContains(fToken) || msg.sender == address(controller), "only supported ftoken or controller" ); _; } function MonitorEventCallback(bytes32 funcName, bytes calldata payload) external onlyFToken(msg.sender) { emit MonitorEvent(funcName, payload); } // bank controller instance IBankController public controller; address public admin; address public proposedAdmin; address public pauser; bool private loaning; modifier nonSelfLoan() { require(!loaning, "re-loaning"); loaning = true; _; loaning = false; } modifier onlyAdmin { require(msg.sender == admin, "OnlyAdmin"); _; } modifier whenUnpaused { require(!paused, "System paused"); _; } modifier onlyMulSig { require(msg.sender == mulSig, "require mulsig"); _; } modifier onlySelf { require(msg.sender == address(this), "require self"); _; } modifier onlyPauser { require(msg.sender == pauser, "require pauser"); _; } // Initialization, can only be initialized once function initialize(address _controller, address _mulSig) public initializer { controller = IBankController(_controller); mulSig = _mulSig; paused = false; admin = msg.sender; } function setController(address _controller) public onlyAdmin { controller = IBankController(_controller); } function setPaused() public onlyPauser { paused = true; } function setUnpaused() public onlyPauser { paused = false; } function setPauser(address _pauser) public onlyAdmin { pauser = _pauser; } function proposeNewAdmin(address admin_) external onlyMulSig { proposedAdmin = admin_; } function claimAdministration() external { require(msg.sender == proposedAdmin, "Not proposed admin."); admin = proposedAdmin; proposedAdmin = address(0); } // User deposit function deposit(address token, uint256 amount) public payable whenUnpaused { return this._deposit{value: msg.value}(token, amount, msg.sender); } // User deposit function _deposit( address token, uint256 amount, address account ) external payable whenUnpaused onlySelf nonSelfLoan { IFToken fToken = IFToken(controller.getFTokeAddress(token)); require( controller.marketsContains(address(fToken)), "unsupported token" ); bytes memory flog = fToken.mint(account, amount); controller.transferIn{value: msg.value}(account, token, amount); fToken.addTotalCash(amount); emit MonitorEvent("Deposit", flog); } // User borrow function borrow(address underlying, uint256 borrowAmount) public whenUnpaused nonSelfLoan { IFToken fToken = IFToken(controller.getFTokeAddress(underlying)); require( controller.marketsContains(address(fToken)), "unsupported token" ); bytes memory flog = fToken.borrow(msg.sender, borrowAmount); emit MonitorEvent("Borrow", flog); } // The user specifies a certain amount of ftoken and retrieves the underlying assets function withdraw(address underlying, uint256 withdrawTokens) public whenUnpaused nonSelfLoan returns (uint256) { IFToken fToken = IFToken(controller.getFTokeAddress(underlying)); require( controller.marketsContains(address(fToken)), "unsupported token" ); (uint256 amount, bytes memory flog) = fToken.withdraw( msg.sender, withdrawTokens, 0 ); emit MonitorEvent("Withdraw", flog); return amount; } // The user retrieves a certain amount of underlying assets function withdrawUnderlying(address underlying, uint256 withdrawAmount) public whenUnpaused nonSelfLoan returns (uint256) { IFToken fToken = IFToken(controller.getFTokeAddress(underlying)); require( controller.marketsContains(address(fToken)), "unsupported token" ); (uint256 amount, bytes memory flog) = fToken.withdraw( msg.sender, 0, withdrawAmount ); emit MonitorEvent("WithdrawUnderlying", flog); return amount; } // User repayment function repay(address token, uint256 repayAmount) public payable whenUnpaused returns (uint256) { return this._repay{value: msg.value}(token, repayAmount, msg.sender); } // User repayment function _repay( address token, uint256 repayAmount, address account ) public payable whenUnpaused onlySelf nonSelfLoan returns (uint256) { IFToken fToken = IFToken(controller.getFTokeAddress(token)); require( controller.marketsContains(address(fToken)), "unsupported token" ); (uint256 actualRepayAmount, bytes memory flog) = fToken.repay( account, repayAmount ); controller.transferIn{value: msg.value}( account, token, actualRepayAmount ); fToken.addTotalCash(actualRepayAmount); emit MonitorEvent("Repay", flog); return actualRepayAmount; } // User Liquidate function liquidateBorrow( address borrower, address underlyingBorrow, address underlyingCollateral, uint256 repayAmount ) public payable whenUnpaused nonSelfLoan { require(msg.sender != borrower, "Liquidator cannot be borrower"); require(repayAmount > 0, "Liquidate amount not valid"); IFToken fTokenBorrow = IFToken( controller.getFTokeAddress(underlyingBorrow) ); IFToken fTokenCollateral = IFToken( controller.getFTokeAddress(underlyingCollateral) ); bytes memory flog = fTokenBorrow.liquidateBorrow( msg.sender, borrower, repayAmount, address(fTokenCollateral) ); controller.transferIn{value: msg.value}( msg.sender, underlyingBorrow, repayAmount ); fTokenBorrow.addTotalCash(repayAmount); emit MonitorEvent("LiquidateBorrow", flog); } // tokenIn, is a combination of repayment and deposit function tokenIn(address token, uint256 amountIn) public payable whenUnpaused { IFToken fToken = IFToken(controller.getFTokeAddress(token)); require( controller.marketsContains(address(fToken)), "unsupported token" ); cancellingOut(token); uint256 curBorrowBalance = fToken.borrowBalanceCurrent(msg.sender); uint256 actualRepayAmount; //Pay off debts if (amountIn == uint256(-1)) { require(curBorrowBalance > 0, "no debt to repay"); if (token != EthAddressLib.ethAddress()) { require( msg.value == 0, "msg.value should be 0 for ERC20 repay" ); actualRepayAmount = this._repay{value: 0}( token, amountIn, msg.sender ); } else { require( msg.value >= curBorrowBalance, "msg.value need great or equal than current debt" ); actualRepayAmount = this._repay{value: curBorrowBalance}( token, amountIn, msg.sender ); if (msg.value > actualRepayAmount) { (bool result, ) = msg.sender.call{ value: msg.value.sub(actualRepayAmount), gas: controller.transferEthGasCost() }(""); require(result, "Transfer of exceed ETH failed"); } } emit MonitorEvent("TokenIn", abi.encode(token, actualRepayAmount)); } else { if (curBorrowBalance > 0) { uint256 repayEthValue = SafeMath.min( curBorrowBalance, amountIn ); if (token != EthAddressLib.ethAddress()) { repayEthValue = 0; } actualRepayAmount = this._repay{value: repayEthValue}( token, SafeMath.min(curBorrowBalance, amountIn), msg.sender ); } // If the repayment amount is left, it will be converted to deposit if (actualRepayAmount < amountIn) { uint256 exceedAmout = SafeMath.sub(amountIn, actualRepayAmount); if (token != EthAddressLib.ethAddress()) { exceedAmout = 0; } this._deposit{value: exceedAmout}( token, SafeMath.sub(amountIn, actualRepayAmount), msg.sender ); } emit MonitorEvent("TokenIn", abi.encode(token, amountIn)); } } // tokenOut, is a combination of withdrawal and borrowing function tokenOut(address token, uint256 amountOut) external whenUnpaused { IFToken fToken = IFToken(controller.getFTokeAddress(token)); require( controller.marketsContains(address(fToken)), "unsupported token" ); cancellingOut(token); uint256 supplyAmount = 0; if (amountOut == uint256(-1)) { uint256 fBalance = fToken.balanceOf(msg.sender); require(fBalance > 0, "no asset to withdraw"); supplyAmount = withdraw(token, fBalance); emit MonitorEvent("TokenOut", abi.encode(token, supplyAmount)); } else { uint256 userSupplyBalance = fToken.calcBalanceOfUnderlying( msg.sender ); if (userSupplyBalance > 0) { if (userSupplyBalance < amountOut) { supplyAmount = withdraw( token, fToken.balanceOf(msg.sender) ); } else { supplyAmount = withdrawUnderlying( token, amountOut ); } } if (supplyAmount < amountOut) { borrow(token, amountOut.sub(supplyAmount)); } emit MonitorEvent("TokenOut", abi.encode(token, amountOut)); } } function cancellingOut(address token) public whenUnpaused nonSelfLoan { IFToken fToken = IFToken(controller.getFTokeAddress(token)); (bool strikeOk, bytes memory strikeLog) = fToken.cancellingOut( msg.sender ); if (strikeOk) { emit MonitorEvent("CancellingOut", strikeLog); } } function flashloan( address receiver, address token, uint256 amount, bytes memory params ) public whenUnpaused nonSelfLoan { uint256 balanceBefore = controller.balance(token); require(amount > 0 && amount <= balanceBefore, "insufficient flashloan liquidity"); uint256 fee = amount.mul(controller.flashloanFeeBips()).div(10000); address payable _receiver = address(uint160(receiver)); controller.transferFlashloanAsset(token, _receiver, amount); IFlashLoanReceiver(_receiver).executeOperation(token, amount, fee, params); uint256 balanceAfter = controller.balance(token); require(balanceAfter >= balanceBefore.add(fee), "invalid flashloan payback amount"); address payable vault = address(uint160(controller.flashloanVault())); controller.transferFlashloanAsset(token, vault, fee); emit FlashLoan(receiver, token, amount, fee); } }
The user retrieves a certain amount of underlying assets
function withdrawUnderlying(address underlying, uint256 withdrawAmount) public whenUnpaused nonSelfLoan returns (uint256) { IFToken fToken = IFToken(controller.getFTokeAddress(underlying)); require( controller.marketsContains(address(fToken)), "unsupported token" ); (uint256 amount, bytes memory flog) = fToken.withdraw( msg.sender, 0, withdrawAmount ); emit MonitorEvent("WithdrawUnderlying", flog); return amount; }
2,570,967
[ 1, 1986, 729, 9023, 279, 8626, 3844, 434, 6808, 7176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 14655, 6291, 12, 2867, 6808, 16, 2254, 5034, 598, 9446, 6275, 13, 203, 3639, 1071, 203, 3639, 1347, 984, 8774, 3668, 203, 3639, 1661, 10084, 1504, 304, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 11083, 1345, 284, 1345, 273, 11083, 1345, 12, 5723, 18, 588, 4464, 3056, 1887, 12, 9341, 6291, 10019, 203, 3639, 2583, 12, 203, 5411, 2596, 18, 3355, 2413, 10846, 12, 2867, 12, 74, 1345, 13, 3631, 203, 5411, 315, 24666, 1147, 6, 203, 3639, 11272, 203, 203, 3639, 261, 11890, 5034, 3844, 16, 1731, 3778, 284, 1330, 13, 273, 284, 1345, 18, 1918, 9446, 12, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 374, 16, 203, 5411, 598, 9446, 6275, 203, 3639, 11272, 203, 3639, 3626, 14086, 1133, 2932, 1190, 9446, 14655, 6291, 3113, 284, 1330, 1769, 203, 3639, 327, 3844, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.19; /*standart library for uint */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0){ return 0; } uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /* contract to identify owner */ contract Ownable { address public owner; address public newOwner; address public techSupport; address public newTechSupport; modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyTechSupport() { require(msg.sender == techSupport); _; } function Ownable() public { owner = msg.sender; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); newOwner = _newOwner; } function acceptOwnership() public { if (msg.sender == newOwner) { owner = newOwner; } } function transferTechSupport (address _newSupport) public{ require (msg.sender == owner || msg.sender == techSupport); newTechSupport = _newSupport; } function acceptSupport() public{ if(msg.sender == newTechSupport){ techSupport = newTechSupport; } } } /* ERC - 20 token contract */ contract VGCToken { function setCrowdsaleContract (address _address) public {} function burnTokens(address _address) public{} function getCrowdsaleBalance() public view returns(uint) {} function getRefBalSended () public view returns(bool){} function sendCrowdsaleBalance (address _address, uint _value) public {} function finishIco() public{} } //Crowdsale contract contract Crowdsale is Ownable{ using SafeMath for uint; //power function function pow(uint256 a, uint256 b) internal pure returns (uint256){ return (a**b); } uint decimals = 2; // Token contract address VGCToken public token; struct Ico{ uint bonus; uint balance; } // Constructor function Crowdsale(address _tokenAddress, address _addressOwner) public{ token = VGCToken(_tokenAddress); owner = _addressOwner; structurePreIco.push(Ico(55555555555,1000000*pow(10,decimals))); //80% bonus structurePreIco.push(Ico(58823529411,1000000*pow(10,decimals))); //70 structurePreIco.push(Ico(62500000000,1000000*pow(10,decimals))); //60 structurePreIco.push(Ico(66666666666,1000000*pow(10,decimals))); //50 structurePreIco.push(Ico(71428571428,1000000*pow(10,decimals))); //40 structurePreIco.push(Ico(76923076923,1000000*pow(10,decimals))); //30 structureIco.push(Ico(83333333333,10000000*pow(10,decimals))); //20 structureIco.push(Ico(90909090909,10000000*pow(10,decimals))); //10 structureIco.push(Ico(100000000000,10000000*pow(10,decimals))); //0 techSupport = msg.sender; token.setCrowdsaleContract(this); } //ICO structures (technical decision) Ico[] public structurePreIco; Ico[] public structureIco; // Buy constants uint public tokenPrice = 2000000000000000 / pow(10,decimals); uint minDeposit = 100000000000000000; //0.1 ETH // preIco constants uint public preIcoStart = 1516320000; // 01/19/2018 uint public preIcoFinish = 1521590400; // 03/21/2018 // Ico constants uint public icoStart = 1521590401; // 03/21/2018 uint public icoFinish = 1529625600; //06/21/2018 uint icoMinCap = 300000*pow(10,decimals); //check is now preICO function isPreIco(uint _time) constant public returns (bool){ if((preIcoStart <= _time) && (_time <= preIcoFinish)){ return true; } return false; } //check is now ICO function isIco(uint _time) constant public returns (bool){ if((icoStart <= _time) && (_time <= icoFinish)){ return true; } return false; } //crowdsale variables uint public preIcoTokensSold = 0; uint public iCoTokensSold = 0; uint public tokensSold = 0; uint public ethCollected = 0; //Ethereum investor balances (how much Eth they're donate to ICO) mapping (address => uint) public investorBalances; //function calculate how many tokens will be send to investor in preIco function buyIfPreIcoDiscount (uint _value) internal returns(uint,uint) { uint buffer = 0; uint bufferEth = 0; uint bufferValue = _value; uint res = 0; for (uint i = 0; i<structurePreIco.length; i++){ res = _value/(tokenPrice*structurePreIco[i].bonus/100000000000); //Purchase over 5,000 VGC and get extra 10% bonus if(res >= (uint)(5000).mul(pow(10,decimals))){ res = res.add(res/10); } if (res<=structurePreIco[i].balance){ // bufferEth = bufferEth+_value; structurePreIco[i].balance = structurePreIco[i].balance.sub(res); buffer = res.add(buffer); return (buffer,0); }else { buffer = buffer.add(structurePreIco[i].balance); // bufferEth = bufferEth.add(structurePreIco[i].balance.mul(tokenPrice)/structurePreIco[i].bonus); bufferEth += structurePreIco[i].balance*tokenPrice*structurePreIco[i].bonus/100000000000; _value = _value.sub(structurePreIco[i].balance*tokenPrice*structurePreIco[i].bonus/100000000000); structurePreIco[i].balance = 0; } } return (buffer,bufferValue.sub(bufferEth)); } //function calculate how many tokens will be send to investor in Ico function buyIfIcoDiscount (uint _value) internal returns(uint,uint) { uint buffer = 0; uint bufferEth = 0; uint bufferValue = _value; uint res = 0; for (uint i = 0; i<structureIco.length; i++){ res = _value/(tokenPrice*structureIco[i].bonus/100000000000); //Purchase over 5,000 VGC and get extra 10% bonus if(res >= (uint)(5000).mul(pow(10,decimals))){ res = res.add(res/10); } if (res<=structureIco[i].balance){ bufferEth = bufferEth+_value; structureIco[i].balance = structureIco[i].balance.sub(res); buffer = res.add(buffer); return (buffer,0); }else { buffer = buffer.add(structureIco[i].balance); bufferEth += structureIco[i].balance*tokenPrice*structureIco[i].bonus/100000000000; _value = _value.sub(structureIco[i].balance*tokenPrice*structureIco[i].bonus/100000000000); structureIco[i].balance = 0; } } return (buffer,bufferValue.sub(bufferEth)); } //fallback function (when investor send ether to contract) function() public payable{ require(msg.value >= minDeposit); require(isIco(now) || isPreIco(now)); require(buy(msg.sender,msg.value,now,false)); //redirect to func buy } bool public preIcoEnded = false; //function buy Tokens function buy(address _address, uint _value, uint _time, bool dashboard) internal returns (bool){ uint tokensForSend; uint etherForSend; if (isPreIco(_time)){ (tokensForSend,etherForSend) = buyIfPreIcoDiscount(_value); assert (tokensForSend >= 50*pow(10,decimals)); preIcoTokensSold += tokensForSend; if (etherForSend!=0 && !dashboard){ _address.transfer(etherForSend); } owner.transfer(this.balance); } if (isIco(_time)){ if(!preIcoEnded){ for (uint i = 0; i<structurePreIco.length; i++){ structureIco[structureIco.length-1].balance = structureIco[structureIco.length-1].balance.add(structurePreIco[i].balance); structurePreIco[i].balance = 0; } preIcoEnded = true; } (tokensForSend,etherForSend) = buyIfIcoDiscount(_value); assert (tokensForSend >= 50*pow(10,decimals)); iCoTokensSold += tokensForSend; if (etherForSend!=0 && !dashboard){ _address.transfer(etherForSend); } investorBalances[_address] += _value.sub(etherForSend); if (isIcoTrue()){ owner.transfer(this.balance); } } tokensSold += tokensForSend; token.sendCrowdsaleBalance(_address,tokensForSend); ethCollected = ethCollected.add(_value.sub(etherForSend)); return true; } //someone can end ICO using this function (require 3 days after ICO end) function finishIco() public { require (now > icoFinish + 3 days); require (token.getRefBalSended()); for (uint i = 0; i<structureIco.length; i++){ structureIco[i].balance = 0; } for (i = 0; i<structurePreIco.length; i++){ structurePreIco[i].balance = 0; } token.finishIco(); } //function check is ICO complete (minCap exceeded) function isIcoTrue() public constant returns (bool){ if (tokensSold >= icoMinCap){ return true; } return false; } //if ICO failed and now = ICO finished date +3 days then investor can withdrow his ether function refund() public{ require (!isIcoTrue()); require (icoFinish + 3 days <= now); token.burnTokens(msg.sender); msg.sender.transfer(investorBalances[msg.sender]); investorBalances[msg.sender] = 0; } //ICO cabinets function function sendEtherManually(address _address, uint _value) public onlyTechSupport{ require(buy(_address,_value,now,true)); } //ICO cabinets function, just for view function tokensCount(uint _value) public view onlyTechSupport returns(uint res) { if (isPreIco(now)){ (res,) = buyIfPreIcoDiscount(_value); } if (isIco(now)){ (res,) = buyIfIcoDiscount(_value); } return res; } function getEtherBalanceOnCrowdsale() public view returns(uint) { return this.balance; } }
ICO cabinets function
function sendEtherManually(address _address, uint _value) public onlyTechSupport{ require(buy(_address,_value,now,true)); }
1,822,463
[ 1, 2871, 51, 276, 378, 267, 2413, 445, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1366, 41, 1136, 5669, 3452, 12, 2867, 389, 2867, 16, 2254, 389, 1132, 13, 1071, 1338, 56, 8987, 6289, 95, 203, 565, 2583, 12, 70, 9835, 24899, 2867, 16, 67, 1132, 16, 3338, 16, 3767, 10019, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Math * @dev Assorted math operations */ library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; function DetailedERC20(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } /** * @title Interface for the ST20 token standard */ contract IST20 is StandardToken, DetailedERC20 { // off-chain hash string public tokenDetails; //transfer, transferFrom must respect use respect the result of verifyTransfer function verifyTransfer(address _from, address _to, uint256 _amount) public returns (bool success); /** * @notice mints new tokens and assigns them to the target _investor. * Can only be called by the STO attached to the token (Or by the ST owner if there's no STO attached yet) */ function mint(address _investor, uint256 _amount) public returns (bool success); /** * @notice Burn function used to burn the securityToken * @param _value No. of token that get burned */ function burn(uint256 _value) public; event Minted(address indexed to, uint256 amount); event Burnt(address indexed _burner, uint256 _value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() 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 { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Interface for all security tokens */ contract ISecurityToken is IST20, Ownable { uint8 public constant PERMISSIONMANAGER_KEY = 1; uint8 public constant TRANSFERMANAGER_KEY = 2; uint8 public constant STO_KEY = 3; uint8 public constant CHECKPOINT_KEY = 4; uint256 public granularity; // Value of current checkpoint uint256 public currentCheckpointId; // Total number of non-zero token holders uint256 public investorCount; // List of token holders address[] public investors; // Permissions this to a Permission module, which has a key of 1 // If no Permission return false - note that IModule withPerm will allow ST owner all permissions anyway // this allows individual modules to override this logic if needed (to not allow ST owner all permissions) function checkPermission(address _delegate, address _module, bytes32 _perm) public view returns(bool); /** * @notice returns module list for a module type * @param _moduleType is which type of module we are trying to remove * @param _moduleIndex is the index of the module within the chosen type */ function getModule(uint8 _moduleType, uint _moduleIndex) public view returns (bytes32, address, bool); /** * @notice returns module list for a module name - will return first match * @param _moduleType is which type of module we are trying to remove * @param _name is the name of the module within the chosen type */ function getModuleByName(uint8 _moduleType, bytes32 _name) public view returns (bytes32, address, bool); /** * @notice Queries totalSupply as of a defined checkpoint * @param _checkpointId Checkpoint ID to query as of */ function totalSupplyAt(uint256 _checkpointId) public view returns(uint256); /** * @notice Queries balances as of a defined checkpoint * @param _investor Investor to query balance for * @param _checkpointId Checkpoint ID to query as of */ function balanceOfAt(address _investor, uint256 _checkpointId) public view returns(uint256); /** * @notice Creates a checkpoint that can be used to query historical balances / totalSuppy */ function createCheckpoint() public returns(uint256); /** * @notice gets length of investors array * NB - this length may differ from investorCount if list has not been pruned of zero balance investors * @return length */ function getInvestorsLength() public view returns(uint256); } /** * @title Interface that any module factory contract should implement */ contract IModuleFactory is Ownable { ERC20 public polyToken; uint256 public setupCost; uint256 public usageCost; uint256 public monthlySubscriptionCost; event LogChangeFactorySetupFee(uint256 _oldSetupcost, uint256 _newSetupCost, address _moduleFactory); event LogChangeFactoryUsageFee(uint256 _oldUsageCost, uint256 _newUsageCost, address _moduleFactory); event LogChangeFactorySubscriptionFee(uint256 _oldSubscriptionCost, uint256 _newMonthlySubscriptionCost, address _moduleFactory); event LogGenerateModuleFromFactory(address _module, bytes32 indexed _moduleName, address indexed _moduleFactory, address _creator, uint256 _timestamp); /** * @notice Constructor * @param _polyAddress Address of the polytoken */ constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public { polyToken = ERC20(_polyAddress); setupCost = _setupCost; usageCost = _usageCost; monthlySubscriptionCost = _subscriptionCost; } //Should create an instance of the Module, or throw function deploy(bytes _data) external returns(address); /** * @notice Type of the Module factory */ function getType() public view returns(uint8); /** * @notice Get the name of the Module */ function getName() public view returns(bytes32); /** * @notice Get the description of the Module */ function getDescription() public view returns(string); /** * @notice Get the title of the Module */ function getTitle() public view returns(string); /** * @notice Get the Instructions that helped to used the module */ function getInstructions() public view returns (string); /** * @notice Get the tags related to the module factory */ function getTags() public view returns (bytes32[]); //Pull function sig from _data function getSig(bytes _data) internal pure returns (bytes4 sig) { uint len = _data.length < 4 ? _data.length : 4; for (uint i = 0; i < len; i++) { sig = bytes4(uint(sig) + uint(_data[i]) * (2 ** (8 * (len - 1 - i)))); } } /** * @notice used to change the fee of the setup cost * @param _newSetupCost new setup cost */ function changeFactorySetupFee(uint256 _newSetupCost) public onlyOwner { uint256 _oldSetupcost = setupCost; setupCost = _newSetupCost; emit LogChangeFactorySetupFee(_oldSetupcost, setupCost, address(this)); } /** * @notice used to change the fee of the usage cost * @param _newUsageCost new usage cost */ function changeFactoryUsageFee(uint256 _newUsageCost) public onlyOwner { uint256 _oldUsageCost = usageCost; usageCost = _newUsageCost; emit LogChangeFactoryUsageFee(_oldUsageCost, usageCost, address(this)); } /** * @notice used to change the fee of the subscription cost * @param _newSubscriptionCost new subscription cost */ function changeFactorySubscriptionFee(uint256 _newSubscriptionCost) public onlyOwner { uint256 _oldSubscriptionCost = monthlySubscriptionCost; monthlySubscriptionCost = _newSubscriptionCost; emit LogChangeFactorySubscriptionFee(_oldSubscriptionCost, monthlySubscriptionCost, address(this)); } } /** * @title Interface that any module contract should implement */ contract IModule { address public factory; address public securityToken; bytes32 public FEE_ADMIN = "FEE_ADMIN"; ERC20 public polyToken; /** * @notice Constructor * @param _securityToken Address of the security token * @param _polyAddress Address of the polytoken */ constructor (address _securityToken, address _polyAddress) public { securityToken = _securityToken; factory = msg.sender; polyToken = ERC20(_polyAddress); } /** * @notice This function returns the signature of configure function */ function getInitFunction() public returns (bytes4); //Allows owner, factory or permissioned delegate modifier withPerm(bytes32 _perm) { bool isOwner = msg.sender == ISecurityToken(securityToken).owner(); bool isFactory = msg.sender == factory; require(isOwner||isFactory||ISecurityToken(securityToken).checkPermission(msg.sender, address(this), _perm), "Permission check failed"); _; } modifier onlyOwner { require(msg.sender == ISecurityToken(securityToken).owner(), "Sender is not owner"); _; } modifier onlyFactory { require(msg.sender == factory, "Sender is not factory"); _; } modifier onlyFactoryOwner { require(msg.sender == IModuleFactory(factory).owner(), "Sender is not factory owner"); _; } /** * @notice Return the permissions flag that are associated with Module */ function getPermissions() public view returns(bytes32[]); /** * @notice used to withdraw the fee by the factory owner */ function takeFee(uint256 _amount) public withPerm(FEE_ADMIN) returns(bool) { require(polyToken.transferFrom(address(this), IModuleFactory(factory).owner(), _amount), "Unable to take fee"); return true; } } /** * @title Interface for the polymath module registry contract */ contract IModuleRegistry { /** * @notice Called by a security token to notify the registry it is using a module * @param _moduleFactory is the address of the relevant module factory */ function useModule(address _moduleFactory) external; /** * @notice Called by moduleFactory owner to register new modules for SecurityToken to use * @param _moduleFactory is the address of the module factory to be registered */ function registerModule(address _moduleFactory) external returns(bool); /** * @notice Use to get all the tags releated to the functionality of the Module Factory. * @param _moduleType Type of module */ function getTagByModuleType(uint8 _moduleType) public view returns(bytes32[]); } /** * @title Utility contract to allow pausing and unpausing of certain functions */ contract Pausable { event Pause(uint256 _timestammp); event Unpause(uint256 _timestamp); bool public paused = false; /** * @notice Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @notice Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @notice called by the owner to pause, triggers stopped state */ function _pause() internal { require(!paused); paused = true; emit Pause(now); } /** * @notice called by the owner to unpause, returns to normal state */ function _unpause() internal { require(paused); paused = false; emit Unpause(now); } } /** * @title Interface to be implemented by all Transfer Manager modules */ contract ITransferManager is IModule, Pausable { //If verifyTransfer returns: // FORCE_VALID, the transaction will always be valid, regardless of other TM results // INVALID, then the transfer should not be allowed regardless of other TM results // VALID, then the transfer is valid for this TM // NA, then the result from this TM is ignored enum Result {INVALID, NA, VALID, FORCE_VALID} function verifyTransfer(address _from, address _to, uint256 _amount, bool _isTransfer) public returns(Result); function unpause() onlyOwner public { super._unpause(); } function pause() onlyOwner public { super._pause(); } } /** * @title Interface to be implemented by all permission manager modules */ contract IPermissionManager is IModule { function checkPermission(address _delegate, address _module, bytes32 _perm) public view returns(bool); function changePermission(address _delegate, address _module, bytes32 _perm, bool _valid) public returns(bool); function getDelegateDetails(address _delegate) public view returns(bytes32); } /** * @title Interface for all polymath registry contracts */ contract IRegistry { /** * @notice get the contract address * @param _nameKey is the key for the contract address mapping */ function getAddress(string _nameKey) view public returns(address); /** * @notice change the contract address * @param _nameKey is the key for the contract address mapping * @param _newAddress is the new contract address */ function changeAddress(string _nameKey, address _newAddress) public; /** * @notice pause (overridden function) */ function unpause() public; /** * @notice unpause (overridden function) */ function pause() public; } /** * @title Interface for the token burner contract */ interface ITokenBurner { function burn(address _burner, uint256 _value ) external returns(bool); } /** * @title Security Token contract * @notice SecurityToken is an ERC20 token with added capabilities: * @notice - Implements the ST-20 Interface * @notice - Transfers are restricted * @notice - Modules can be attached to it to control its behaviour * @notice - ST should not be deployed directly, but rather the SecurityTokenRegistry should be used */ contract SecurityToken is ISecurityToken { using SafeMath for uint256; bytes32 public securityTokenVersion = "0.0.1"; // Reference to token burner contract ITokenBurner public tokenBurner; // Use to halt all the transactions bool public freeze = false; // Reference to STR contract address public securityTokenRegistry; struct ModuleData { bytes32 name; address moduleAddress; } // Structures to maintain checkpoints of balances for governance / dividends struct Checkpoint { uint256 checkpointId; uint256 value; } mapping (address => Checkpoint[]) public checkpointBalances; Checkpoint[] public checkpointTotalSupply; bool public mintingFinished = false; mapping (bytes4 => bool) transferFunctions; // Module list should be order agnostic! mapping (uint8 => ModuleData[]) public modules; mapping (uint8 => bool) public modulesLocked; uint8 public constant MAX_MODULES = 20; mapping (address => bool) public investorListed; // Emit at the time when module get added event LogModuleAdded( uint8 indexed _type, bytes32 _name, address _moduleFactory, address _module, uint256 _moduleCost, uint256 _budget, uint256 _timestamp ); // Emit when the token details get updated event LogUpdateTokenDetails(string _oldDetails, string _newDetails); // Emit when the granularity get changed event LogGranularityChanged(uint256 _oldGranularity, uint256 _newGranularity); // Emit when Module get removed from the securityToken event LogModuleRemoved(uint8 indexed _type, address _module, uint256 _timestamp); // Emit when the budget allocated to a module is changed event LogModuleBudgetChanged(uint8 indexed _moduleType, address _module, uint256 _budget); // Emit when all the transfers get freeze event LogFreezeTransfers(bool _freeze, uint256 _timestamp); // Emit when new checkpoint created event LogCheckpointCreated(uint256 indexed _checkpointId, uint256 _timestamp); // Emit when the minting get finished event LogFinishedMinting(uint256 _timestamp); // Emit when a module type is locked event LogModuleLocked(uint8 indexed _moduleType, address _locker); // Change the STR address in the event of a upgrade event LogChangeSTRAddress(address indexed _oldAddress, address indexed _newAddress); //if _fallback is true, then we only allow the module if it is set, if it is not set we only allow the owner modifier onlyModule(uint8 _moduleType, bool _fallback) { //Loop over all modules of type _moduleType bool isModuleType = false; for (uint8 i = 0; i < modules[_moduleType].length; i++) { isModuleType = isModuleType || (modules[_moduleType][i].moduleAddress == msg.sender); } if (_fallback && !isModuleType) { require(msg.sender == owner, "Sender is not owner"); } else { require(isModuleType, "Sender is not correct module type"); } _; } modifier checkGranularity(uint256 _amount) { require(_amount.div(granularity).mul(granularity) == _amount, "Unable to modify token balances at this granularity"); _; } /** * @notice Constructor * @param _name Name of the SecurityToken * @param _symbol Symbol of the Token * @param _decimals Decimals for the securityToken * @param _granularity granular level of the token * @param _tokenDetails Details of the token that are stored off-chain (IPFS hash) * @param _securityTokenRegistry Contract address of the security token registry */ constructor ( string _name, string _symbol, uint8 _decimals, uint256 _granularity, string _tokenDetails, address _securityTokenRegistry ) public DetailedERC20(_name, _symbol, _decimals) { //When it is created, the owner is the STR securityTokenRegistry = _securityTokenRegistry; tokenDetails = _tokenDetails; granularity = _granularity; transferFunctions[bytes4(keccak256("transfer(address,uint256)"))] = true; transferFunctions[bytes4(keccak256("transferFrom(address,address,uint256)"))] = true; transferFunctions[bytes4(keccak256("mint(address,uint256)"))] = true; transferFunctions[bytes4(keccak256("burn(uint256)"))] = true; } /** * @notice Function used by issuer to lock a specific module type * @param _moduleType module type to be locked */ function lockModule(uint8 _moduleType) external onlyOwner { require(!modulesLocked[_moduleType]); modulesLocked[_moduleType] = true; emit LogModuleLocked(_moduleType, msg.sender); } /** * @notice Function used to attach the module in security token * @param _moduleFactory Contract address of the module factory that needs to be attached * @param _data Data used for the intialization of the module factory variables * @param _maxCost Maximum cost of the Module factory * @param _budget Budget of the Module factory * @param _locked whether or not the module is supposed to be locked */ function addModule( address _moduleFactory, bytes _data, uint256 _maxCost, uint256 _budget, bool _locked ) external onlyOwner { _addModule(_moduleFactory, _data, _maxCost, _budget, _locked); } /** * @notice _addModule handles the attachment (or replacement) of modules for the ST * @dev E.G.: On deployment (through the STR) ST gets a TransferManager module attached to it * @dev to control restrictions on transfers. * @dev You are allowed to add a new moduleType if: * @dev - there is no existing module of that type yet added * @dev - the last member of the module list is replacable * @param _moduleFactory is the address of the module factory to be added * @param _data is data packed into bytes used to further configure the module (See STO usage) * @param _maxCost max amount of POLY willing to pay to module. (WIP) * @param _locked whether or not the module is supposed to be locked */ function _addModule(address _moduleFactory, bytes _data, uint256 _maxCost, uint256 _budget, bool _locked) internal { //Check that module exists in registry - will throw otherwise IModuleRegistry(IRegistry(securityTokenRegistry).getAddress("ModuleRegistry")).useModule(_moduleFactory); IModuleFactory moduleFactory = IModuleFactory(_moduleFactory); require(modules[moduleFactory.getType()].length < MAX_MODULES, "Limit of MAX MODULES is reached"); uint256 moduleCost = moduleFactory.setupCost(); require(moduleCost <= _maxCost, "Max Cost is always be greater than module cost"); //Check that this module has not already been set as locked require(!modulesLocked[moduleFactory.getType()], "Module has already been set as locked"); //Approve fee for module require(ERC20(IRegistry(securityTokenRegistry).getAddress("PolyToken")).approve(_moduleFactory, moduleCost), "Not able to approve the module cost"); //Creates instance of module from factory address module = moduleFactory.deploy(_data); //Approve ongoing budget require(ERC20(IRegistry(securityTokenRegistry).getAddress("PolyToken")).approve(module, _budget), "Not able to approve the budget"); //Add to SecurityToken module map modules[moduleFactory.getType()].push(ModuleData(moduleFactory.getName(), module)); modulesLocked[moduleFactory.getType()] = _locked; //Emit log event emit LogModuleAdded(moduleFactory.getType(), moduleFactory.getName(), _moduleFactory, module, moduleCost, _budget, now); } /** * @notice Removes a module attached to the SecurityToken * @param _moduleType is which type of module we are trying to remove * @param _moduleIndex is the index of the module within the chosen type */ function removeModule(uint8 _moduleType, uint8 _moduleIndex) external onlyOwner { require(_moduleIndex < modules[_moduleType].length, "Module index doesn't exist as per the choosen module type"); require(modules[_moduleType][_moduleIndex].moduleAddress != address(0), "Module contract address should not be 0x"); require(!modulesLocked[_moduleType], "Module should not be locked"); //Take the last member of the list, and replace _moduleIndex with this, then shorten the list by one emit LogModuleRemoved(_moduleType, modules[_moduleType][_moduleIndex].moduleAddress, now); modules[_moduleType][_moduleIndex] = modules[_moduleType][modules[_moduleType].length - 1]; modules[_moduleType].length = modules[_moduleType].length - 1; } /** * @notice Returns module list for a module type * @param _moduleType is which type of module we are trying to get * @param _moduleIndex is the index of the module within the chosen type * @return bytes32 * @return address * @return bool */ function getModule(uint8 _moduleType, uint _moduleIndex) public view returns (bytes32, address, bool) { if (modules[_moduleType].length > 0) { return ( modules[_moduleType][_moduleIndex].name, modules[_moduleType][_moduleIndex].moduleAddress, modulesLocked[_moduleType] ); } else { return ("", address(0), false); } } /** * @notice returns module list for a module name - will return first match * @param _moduleType is which type of module we are trying to get * @param _name is the name of the module within the chosen type * @return bytes32 * @return address * @return bool */ function getModuleByName(uint8 _moduleType, bytes32 _name) public view returns (bytes32, address, bool) { if (modules[_moduleType].length > 0) { for (uint256 i = 0; i < modules[_moduleType].length; i++) { if (modules[_moduleType][i].name == _name) { return ( modules[_moduleType][i].name, modules[_moduleType][i].moduleAddress, modulesLocked[_moduleType] ); } } return ("", address(0), false); } else { return ("", address(0), false); } } /** * @notice allows the owner to withdraw unspent POLY stored by them on the ST. * @dev Owner can transfer POLY to the ST which will be used to pay for modules that require a POLY fee. * @param _amount amount of POLY to withdraw */ function withdrawPoly(uint256 _amount) public onlyOwner { require(ERC20(IRegistry(securityTokenRegistry).getAddress("PolyToken")).transfer(owner, _amount), "In-sufficient balance"); } /** * @notice allows owner to approve more POLY to one of the modules * @param _moduleType module type * @param _moduleIndex module index * @param _budget new budget */ function changeModuleBudget(uint8 _moduleType, uint8 _moduleIndex, uint256 _budget) public onlyOwner { require(_moduleType != 0, "Module type cannot be zero"); require(_moduleIndex < modules[_moduleType].length, "Incorrrect module index"); require(ERC20(IRegistry(securityTokenRegistry).getAddress("PolyToken")).approve(modules[_moduleType][_moduleIndex].moduleAddress, _budget), "Insufficient balance to approve"); emit LogModuleBudgetChanged(_moduleType, modules[_moduleType][_moduleIndex].moduleAddress, _budget); } /** * @notice change the tokenDetails * @param _newTokenDetails New token details */ function updateTokenDetails(string _newTokenDetails) public onlyOwner { emit LogUpdateTokenDetails(tokenDetails, _newTokenDetails); tokenDetails = _newTokenDetails; } /** * @notice allows owner to change token granularity * @param _granularity granularity level of the token */ function changeGranularity(uint256 _granularity) public onlyOwner { require(_granularity != 0, "Granularity can not be 0"); emit LogGranularityChanged(granularity, _granularity); granularity = _granularity; } /** * @notice keeps track of the number of non-zero token holders * @param _from sender of transfer * @param _to receiver of transfer * @param _value value of transfer */ function adjustInvestorCount(address _from, address _to, uint256 _value) internal { if ((_value == 0) || (_from == _to)) { return; } // Check whether receiver is a new token holder if ((balanceOf(_to) == 0) && (_to != address(0))) { investorCount = investorCount.add(1); } // Check whether sender is moving all of their tokens if (_value == balanceOf(_from)) { investorCount = investorCount.sub(1); } //Also adjust investor list if (!investorListed[_to] && (_to != address(0))) { investors.push(_to); investorListed[_to] = true; } } /** * @notice removes addresses with zero balances from the investors list * @param _start Index in investor list at which to start removing zero balances * @param _iters Max number of iterations of the for loop * NB - pruning this list will mean you may not be able to iterate over investors on-chain as of a historical checkpoint */ function pruneInvestors(uint256 _start, uint256 _iters) public onlyOwner { for (uint256 i = _start; i < Math.min256(_start.add(_iters), investors.length); i++) { if ((i < investors.length) && (balanceOf(investors[i]) == 0)) { investorListed[investors[i]] = false; investors[i] = investors[investors.length - 1]; investors.length--; } } } /** * @notice gets length of investors array * NB - this length may differ from investorCount if list has not been pruned of zero balance investors * @return length */ function getInvestorsLength() public view returns(uint256) { return investors.length; } /** * @notice freeze all the transfers */ function freezeTransfers() public onlyOwner { require(!freeze); freeze = true; emit LogFreezeTransfers(freeze, now); } /** * @notice un-freeze all the transfers */ function unfreezeTransfers() public onlyOwner { require(freeze); freeze = false; emit LogFreezeTransfers(freeze, now); } /** * @notice adjust totalsupply at checkpoint after minting or burning tokens */ function adjustTotalSupplyCheckpoints() internal { adjustCheckpoints(checkpointTotalSupply, totalSupply()); } /** * @notice adjust token holder balance at checkpoint after a token transfer * @param _investor address of the token holder affected */ function adjustBalanceCheckpoints(address _investor) internal { adjustCheckpoints(checkpointBalances[_investor], balanceOf(_investor)); } /** * @notice store the changes to the checkpoint objects * @param _checkpoints the affected checkpoint object array * @param _newValue the new value that needs to be stored */ function adjustCheckpoints(Checkpoint[] storage _checkpoints, uint256 _newValue) internal { //No checkpoints set yet if (currentCheckpointId == 0) { return; } //No previous checkpoint data - add current balance against checkpoint if (_checkpoints.length == 0) { _checkpoints.push( Checkpoint({ checkpointId: currentCheckpointId, value: _newValue }) ); return; } //No new checkpoints since last update if (_checkpoints[_checkpoints.length - 1].checkpointId == currentCheckpointId) { return; } //New checkpoint, so record balance _checkpoints.push( Checkpoint({ checkpointId: currentCheckpointId, value: _newValue }) ); } /** * @notice Overloaded version of the transfer function * @param _to receiver of transfer * @param _value value of transfer * @return bool success */ function transfer(address _to, uint256 _value) public returns (bool success) { adjustInvestorCount(msg.sender, _to, _value); require(verifyTransfer(msg.sender, _to, _value), "Transfer is not valid"); adjustBalanceCheckpoints(msg.sender); adjustBalanceCheckpoints(_to); require(super.transfer(_to, _value)); return true; } /** * @notice Overloaded version of the transferFrom function * @param _from sender of transfer * @param _to receiver of transfer * @param _value value of transfer * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { adjustInvestorCount(_from, _to, _value); require(verifyTransfer(_from, _to, _value), "Transfer is not valid"); adjustBalanceCheckpoints(_from); adjustBalanceCheckpoints(_to); require(super.transferFrom(_from, _to, _value)); return true; } /** * @notice validate transfer with TransferManager module if it exists * @dev TransferManager module has a key of 2 * @param _from sender of transfer * @param _to receiver of transfer * @param _amount value of transfer * @return bool */ function verifyTransfer(address _from, address _to, uint256 _amount) public checkGranularity(_amount) returns (bool) { if (!freeze) { bool isTransfer = false; if (transferFunctions[getSig(msg.data)]) { isTransfer = true; } if (modules[TRANSFERMANAGER_KEY].length == 0) { return true; } bool isInvalid = false; bool isValid = false; bool isForceValid = false; for (uint8 i = 0; i < modules[TRANSFERMANAGER_KEY].length; i++) { ITransferManager.Result valid = ITransferManager(modules[TRANSFERMANAGER_KEY][i].moduleAddress).verifyTransfer(_from, _to, _amount, isTransfer); if (valid == ITransferManager.Result.INVALID) { isInvalid = true; } if (valid == ITransferManager.Result.VALID) { isValid = true; } if (valid == ITransferManager.Result.FORCE_VALID) { isForceValid = true; } } return isForceValid ? true : (isInvalid ? false : isValid); } return false; } /** * @notice End token minting period permanently */ function finishMinting() public onlyOwner { mintingFinished = true; emit LogFinishedMinting(now); } /** * @notice mints new tokens and assigns them to the target _investor. * @dev Can only be called by the STO attached to the token (Or by the ST owner if there's no STO attached yet) * @param _investor Address to whom the minted tokens will be dilivered * @param _amount Number of tokens get minted * @return success */ function mint(address _investor, uint256 _amount) public onlyModule(STO_KEY, true) checkGranularity(_amount) returns (bool success) { require(!mintingFinished, "Minting is finished, not able to mint additional tokens"); adjustInvestorCount(address(0), _investor, _amount); require(verifyTransfer(address(0), _investor, _amount), "Transfer is not valid"); adjustBalanceCheckpoints(_investor); adjustTotalSupplyCheckpoints(); totalSupply_ = totalSupply_.add(_amount); balances[_investor] = balances[_investor].add(_amount); emit Minted(_investor, _amount); emit Transfer(address(0), _investor, _amount); return true; } /** * @notice mints new tokens and assigns them to the target _investor. * Can only be called by the STO attached to the token (Or by the ST owner if there's no STO attached yet) * @param _investors A list of addresses to whom the minted tokens will be dilivered * @param _amounts A list of number of tokens get minted and transfer to corresponding address of the investor from _investor[] list * @return success */ function mintMulti(address[] _investors, uint256[] _amounts) public onlyModule(STO_KEY, true) returns (bool success) { require(_investors.length == _amounts.length, "Mis-match in the length of the arrays"); for (uint256 i = 0; i < _investors.length; i++) { mint(_investors[i], _amounts[i]); } return true; } /** * @notice Validate permissions with PermissionManager if it exists, If no Permission return false * @dev Note that IModule withPerm will allow ST owner all permissions anyway * @dev this allows individual modules to override this logic if needed (to not allow ST owner all permissions) * @param _delegate address of delegate * @param _module address of PermissionManager module * @param _perm the permissions * @return success */ function checkPermission(address _delegate, address _module, bytes32 _perm) public view returns(bool) { if (modules[PERMISSIONMANAGER_KEY].length == 0) { return false; } for (uint8 i = 0; i < modules[PERMISSIONMANAGER_KEY].length; i++) { if (IPermissionManager(modules[PERMISSIONMANAGER_KEY][i].moduleAddress).checkPermission(_delegate, _module, _perm)) { return true; } } } /** * @notice used to set the token Burner address. It only be called by the owner * @param _tokenBurner Address of the token burner contract */ function setTokenBurner(address _tokenBurner) public onlyOwner { tokenBurner = ITokenBurner(_tokenBurner); } /** * @notice Burn function used to burn the securityToken * @param _value No. of token that get burned */ function burn(uint256 _value) checkGranularity(_value) public { adjustInvestorCount(msg.sender, address(0), _value); require(tokenBurner != address(0), "Token Burner contract address is not set yet"); require(verifyTransfer(msg.sender, address(0), _value), "Transfer is not valid"); require(_value <= balances[msg.sender], "Value should no be greater than the balance of msg.sender"); adjustBalanceCheckpoints(msg.sender); adjustTotalSupplyCheckpoints(); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[msg.sender] = balances[msg.sender].sub(_value); require(tokenBurner.burn(msg.sender, _value), "Token burner process is not validated"); totalSupply_ = totalSupply_.sub(_value); emit Burnt(msg.sender, _value); emit Transfer(msg.sender, address(0), _value); } /** * @notice Get function signature from _data * @param _data passed data * @return bytes4 sig */ function getSig(bytes _data) internal pure returns (bytes4 sig) { uint len = _data.length < 4 ? _data.length : 4; for (uint i = 0; i < len; i++) { sig = bytes4(uint(sig) + uint(_data[i]) * (2 ** (8 * (len - 1 - i)))); } } /** * @notice set a new Security Token Registry contract address in case of upgrade * @param _newAddress is address of new contract */ function changeSecurityTokenRegistryAddress(address _newAddress) public onlyOwner { require(_newAddress != securityTokenRegistry && _newAddress != address(0)); emit LogChangeSTRAddress(securityTokenRegistry, _newAddress); securityTokenRegistry = _newAddress; } /** * @notice Creates a checkpoint that can be used to query historical balances / totalSuppy * @return uint256 */ function createCheckpoint() public onlyModule(CHECKPOINT_KEY, true) returns(uint256) { require(currentCheckpointId < 2**256 - 1); currentCheckpointId = currentCheckpointId + 1; emit LogCheckpointCreated(currentCheckpointId, now); return currentCheckpointId; } /** * @notice Queries totalSupply as of a defined checkpoint * @param _checkpointId Checkpoint ID to query * @return uint256 */ function totalSupplyAt(uint256 _checkpointId) public view returns(uint256) { return getValueAt(checkpointTotalSupply, _checkpointId, totalSupply()); } /** * @notice Queries value at a defined checkpoint * @param checkpoints is array of Checkpoint objects * @param _checkpointId Checkpoint ID to query * @param _currentValue Current value of checkpoint * @return uint256 */ function getValueAt(Checkpoint[] storage checkpoints, uint256 _checkpointId, uint256 _currentValue) internal view returns(uint256) { require(_checkpointId <= currentCheckpointId); //Checkpoint id 0 is when the token is first created - everyone has a zero balance if (_checkpointId == 0) { return 0; } if (checkpoints.length == 0) { return _currentValue; } if (checkpoints[0].checkpointId >= _checkpointId) { return checkpoints[0].value; } if (checkpoints[checkpoints.length - 1].checkpointId < _checkpointId) { return _currentValue; } if (checkpoints[checkpoints.length - 1].checkpointId == _checkpointId) { return checkpoints[checkpoints.length - 1].value; } uint256 min = 0; uint256 max = checkpoints.length - 1; while (max > min) { uint256 mid = (max + min) / 2; if (checkpoints[mid].checkpointId == _checkpointId) { max = mid; break; } if (checkpoints[mid].checkpointId < _checkpointId) { min = mid + 1; } else { max = mid; } } return checkpoints[max].value; } /** * @notice Queries balances as of a defined checkpoint * @param _investor Investor to query balance for * @param _checkpointId Checkpoint ID to query as of */ function balanceOfAt(address _investor, uint256 _checkpointId) public view returns(uint256) { return getValueAt(checkpointBalances[_investor], _checkpointId, balanceOf(_investor)); } } /** * @title SecurityToken V2 * @notice Mockup of how an upgrade of SecurityToken would look like */ contract SecurityTokenV2 is SecurityToken { bytes32 public securityTokenVersion = "0.0.2"; /** * @notice Constructor * @param _name Name of the SecurityToken * @param _symbol Symbol of the Token * @param _decimals Decimals for the securityToken * @param _granularity granular level of the token * @param _tokenDetails Details of the token that are stored offchain (IPFS hash) * @param _securityTokenRegistry Contract address of the security token registry */ constructor ( string _name, string _symbol, uint8 _decimals, uint256 _granularity, string _tokenDetails, address _securityTokenRegistry ) public SecurityToken( _name, _symbol, _decimals, _granularity, _tokenDetails, _securityTokenRegistry) { } }
* @notice returns module list for a module name - will return first match @param _moduleType is which type of module we are trying to get @param _name is the name of the module within the chosen type @return bytes32 @return address @return bool/
function getModuleByName(uint8 _moduleType, bytes32 _name) public view returns (bytes32, address, bool) { if (modules[_moduleType].length > 0) { for (uint256 i = 0; i < modules[_moduleType].length; i++) { if (modules[_moduleType][i].name == _name) { return ( modules[_moduleType][i].name, modules[_moduleType][i].moduleAddress, modulesLocked[_moduleType] ); } } return ("", address(0), false); return ("", address(0), false); } }
13,046,589
[ 1, 6154, 1605, 666, 364, 279, 1605, 508, 300, 903, 327, 1122, 845, 225, 389, 2978, 559, 353, 1492, 618, 434, 1605, 732, 854, 8374, 358, 336, 225, 389, 529, 353, 326, 508, 434, 326, 1605, 3470, 326, 10447, 618, 327, 1731, 1578, 327, 1758, 327, 1426, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11251, 5911, 12, 11890, 28, 389, 2978, 559, 16, 1731, 1578, 389, 529, 13, 1071, 1476, 1135, 261, 3890, 1578, 16, 1758, 16, 1426, 13, 288, 203, 3639, 309, 261, 6400, 63, 67, 2978, 559, 8009, 2469, 405, 374, 13, 288, 203, 5411, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 4381, 63, 67, 2978, 559, 8009, 2469, 31, 277, 27245, 288, 203, 7734, 309, 261, 6400, 63, 67, 2978, 559, 6362, 77, 8009, 529, 422, 389, 529, 13, 288, 203, 5375, 327, 261, 203, 8227, 4381, 63, 67, 2978, 559, 6362, 77, 8009, 529, 16, 203, 8227, 4381, 63, 67, 2978, 559, 6362, 77, 8009, 2978, 1887, 16, 203, 8227, 4381, 8966, 63, 67, 2978, 559, 65, 203, 5375, 11272, 203, 7734, 289, 203, 5411, 289, 203, 5411, 327, 7566, 3113, 1758, 12, 20, 3631, 629, 1769, 203, 5411, 327, 7566, 3113, 1758, 12, 20, 3631, 629, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.13; import { DSTest } from "ds-test/test.sol"; import { ERC20 } from "@rari-capital/solmate/src/tokens/ERC20.sol"; import { Shrine } from "../Shrine.sol"; import { MockERC20 } from "./mocks/MockERC20.t.sol"; import { ShrineFactory } from "../ShrineFactory.sol"; import { MerkleTreeGenerator } from "./lib/MerkleTreeGenerator.t.sol"; contract ShrineTest is DSTest, MerkleTreeGenerator { uint256 constant EXAMPLE_TOTAL_SHARES = 1e18; uint256 constant EXAMPLE_USER_SHARES = 7e16; ShrineFactory factory; MockERC20 exampleToken; Shrine exampleShrine; bytes32[] exampleProof; function setUp() public { Shrine template = new Shrine(); factory = new ShrineFactory(template); exampleToken = new MockERC20("Test Token", "TOK", 18); // generate example Merkle tree (bytes32 root, bytes32[] memory proof) = generateMerkleTree( keccak256(abi.encodePacked(address(this), EXAMPLE_USER_SHARES)), 10, keccak256(abi.encodePacked(block.timestamp)) ); exampleProof = proof; // generate example shrine exampleShrine = factory.createShrine( address(this), Shrine.Ledger({ merkleRoot: root, totalShares: EXAMPLE_TOTAL_SHARES }), "QmaCiEF9RzXrFGVoKtLFUrK6MUhUFgEm1dxpxoqDRFzENC" ); // mint mock tokens to self exampleToken.mint(type(uint256).max); // set token approvals exampleToken.approve(address(exampleShrine), type(uint256).max); // offer example token exampleShrine.offer(exampleToken, type(uint128).max); } /// ------------------------------------------------------------------- /// Gas benchmarking /// ------------------------------------------------------------------- function testGas_offer(uint128 amount) public { exampleShrine.offer(exampleToken, amount); } function testGas_claim() public { Shrine.ClaimInfo memory claimInfo = Shrine.ClaimInfo({ version: Shrine.Version.wrap(1), token: exampleToken, champion: Shrine.Champion.wrap(address(this)), shares: EXAMPLE_USER_SHARES, merkleProof: exampleProof }); exampleShrine.claim(address(this), claimInfo); } /// ------------------------------------------------------------------- /// Correctness tests /// ------------------------------------------------------------------- function testCorrectness_offerAndClaim( uint128 offerAmount, uint128 userShareAmount, uint8 treeHeightMinusOne, bytes32 randomness ) public { if (offerAmount == 0) offerAmount = 1; if (treeHeightMinusOne == 0) treeHeightMinusOne = 1; if (userShareAmount == 0) userShareAmount = 1; // setup (bytes32 root, bytes32[] memory proof) = generateMerkleTree( keccak256(abi.encodePacked(address(this), uint256(userShareAmount))), treeHeightMinusOne, randomness ); Shrine shrine = factory.createShrine( address(this), Shrine.Ledger({ merkleRoot: root, totalShares: userShareAmount }), "" ); MockERC20 testToken = new MockERC20("Test Token", "TOK", 18); // mint and offer tokens testToken.mint(offerAmount); testToken.approve(address(shrine), offerAmount); shrine.offer(testToken, offerAmount); // claim tokens Shrine.ClaimInfo memory claimInfo = Shrine.ClaimInfo({ version: Shrine.Version.wrap(1), token: testToken, champion: Shrine.Champion.wrap(address(this)), shares: userShareAmount, merkleProof: proof }); uint256 claimedTokenAmount = shrine.claim(address(this), claimInfo); // verify tokens claimed assertEq(testToken.balanceOf(address(this)), offerAmount); assertEq(claimedTokenAmount, offerAmount); // try claiming again claimedTokenAmount = shrine.claim(address(this), claimInfo); // verify tokens claimed assertEq(testToken.balanceOf(address(this)), offerAmount); assertEq(claimedTokenAmount, 0); } function testCorrectness_offerAndClaimMultipleTokensForChampion( uint128[] calldata offerAmountList, uint128 userShareAmount, uint8 treeHeightMinusOne, bytes32 randomness ) public { if (offerAmountList.length == 0) return; if (treeHeightMinusOne == 0) treeHeightMinusOne = 1; if (userShareAmount == 0) userShareAmount = 1; // setup (bytes32 root, bytes32[] memory proof) = generateMerkleTree( keccak256(abi.encodePacked(address(this), uint256(userShareAmount))), treeHeightMinusOne, randomness ); Shrine shrine = factory.createShrine( address(this), Shrine.Ledger({ merkleRoot: root, totalShares: userShareAmount }), "" ); ERC20[] memory testTokenList = new ERC20[](offerAmountList.length); for (uint256 i = 0; i < offerAmountList.length; i++) { MockERC20 testToken = new MockERC20("Test Token", "TOK", 18); testTokenList[i] = ERC20(address(testToken)); // mint and offer tokens testToken.mint(offerAmountList[i]); testTokenList[i].approve(address(shrine), offerAmountList[i]); shrine.offer(testTokenList[i], offerAmountList[i]); } // claim tokens uint256[] memory claimedTokenAmountList = shrine .claimMultipleTokensForChampion( address(this), Shrine.Version.wrap(1), testTokenList, Shrine.Champion.wrap(address(this)), userShareAmount, proof ); // verify tokens claimed for (uint256 i = 0; i < offerAmountList.length; i++) { assertEq(testTokenList[i].balanceOf(address(this)), offerAmountList[i]); assertEq(claimedTokenAmountList[i], offerAmountList[i]); } // try claiming again claimedTokenAmountList = shrine.claimMultipleTokensForChampion( address(this), Shrine.Version.wrap(1), testTokenList, Shrine.Champion.wrap(address(this)), userShareAmount, proof ); // verify tokens claimed for (uint256 i = 0; i < offerAmountList.length; i++) { assertEq(testTokenList[i].balanceOf(address(this)), offerAmountList[i]); assertEq(claimedTokenAmountList[i], 0); } } function testCorrectness_offerAndClaimFromMetaShrine( uint128 offerAmount, uint128 userShareAmount, uint8 treeHeightMinusOne, bytes32 randomness ) public { if (offerAmount == 0) offerAmount = 1; if (treeHeightMinusOne == 0) treeHeightMinusOne = 1; if (userShareAmount == 0) userShareAmount = 1; // setup (bytes32 root, bytes32[] memory proof) = generateMerkleTree( keccak256(abi.encodePacked(address(this), uint256(userShareAmount))), treeHeightMinusOne, randomness ); Shrine shrine = factory.createShrine( address(this), Shrine.Ledger({ merkleRoot: root, totalShares: userShareAmount }), "" ); (bytes32 metaRoot, bytes32[] memory metaProof) = generateMerkleTree( keccak256(abi.encodePacked(address(shrine), uint256(userShareAmount))), treeHeightMinusOne, randomness ); Shrine metaShrine = factory.createShrine( address(this), Shrine.Ledger({ merkleRoot: metaRoot, totalShares: userShareAmount }), "" ); MockERC20 testToken = new MockERC20("Test Token", "TOK", 18); // mint and offer tokens to meta shrine testToken.mint(offerAmount); testToken.approve(address(metaShrine), offerAmount); metaShrine.offer(testToken, offerAmount); // claim tokens from meta shrine to shrine Shrine.MetaShrineClaimInfo memory metaClaimInfo = Shrine .MetaShrineClaimInfo({ metaShrine: metaShrine, version: Shrine.Version.wrap(1), token: testToken, shares: userShareAmount, merkleProof: metaProof }); shrine.claimFromMetaShrine(metaClaimInfo); // claim tokens from shrine Shrine.ClaimInfo memory claimInfo = Shrine.ClaimInfo({ version: Shrine.Version.wrap(1), token: testToken, champion: Shrine.Champion.wrap(address(this)), shares: userShareAmount, merkleProof: proof }); uint256 claimedTokenAmount = shrine.claim(address(this), claimInfo); // verify tokens claimed assertEq(testToken.balanceOf(address(this)), offerAmount); assertEq(claimedTokenAmount, offerAmount); } }
setup mint and offer tokens to meta shrine claim tokens from meta shrine to shrine claim tokens from shrine
function testCorrectness_offerAndClaimFromMetaShrine( uint128 offerAmount, uint128 userShareAmount, uint8 treeHeightMinusOne, bytes32 randomness ) public { if (offerAmount == 0) offerAmount = 1; if (treeHeightMinusOne == 0) treeHeightMinusOne = 1; if (userShareAmount == 0) userShareAmount = 1; (bytes32 root, bytes32[] memory proof) = generateMerkleTree( keccak256(abi.encodePacked(address(this), uint256(userShareAmount))), treeHeightMinusOne, randomness ); Shrine shrine = factory.createShrine( address(this), "" ); (bytes32 metaRoot, bytes32[] memory metaProof) = generateMerkleTree( keccak256(abi.encodePacked(address(shrine), uint256(userShareAmount))), treeHeightMinusOne, randomness ); Shrine metaShrine = factory.createShrine( address(this), "" ); MockERC20 testToken = new MockERC20("Test Token", "TOK", 18); testToken.mint(offerAmount); testToken.approve(address(metaShrine), offerAmount); metaShrine.offer(testToken, offerAmount); Shrine.MetaShrineClaimInfo memory metaClaimInfo = Shrine .MetaShrineClaimInfo({ metaShrine: metaShrine, version: Shrine.Version.wrap(1), token: testToken, shares: userShareAmount, merkleProof: metaProof }); shrine.claimFromMetaShrine(metaClaimInfo); Shrine.ClaimInfo memory claimInfo = Shrine.ClaimInfo({ version: Shrine.Version.wrap(1), token: testToken, champion: Shrine.Champion.wrap(address(this)), shares: userShareAmount, merkleProof: proof }); uint256 claimedTokenAmount = shrine.claim(address(this), claimInfo); assertEq(claimedTokenAmount, offerAmount); }
13,079,220
[ 1, 8401, 312, 474, 471, 10067, 2430, 358, 2191, 699, 86, 558, 7516, 2430, 628, 2191, 699, 86, 558, 358, 699, 86, 558, 7516, 2430, 628, 699, 86, 558, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1842, 16147, 4496, 67, 23322, 1876, 9762, 1265, 2781, 1555, 86, 558, 12, 203, 565, 2254, 10392, 10067, 6275, 16, 203, 565, 2254, 10392, 729, 9535, 6275, 16, 203, 565, 2254, 28, 2151, 2686, 18434, 3335, 16, 203, 565, 1731, 1578, 2744, 4496, 203, 225, 262, 1071, 288, 203, 565, 309, 261, 23322, 6275, 422, 374, 13, 10067, 6275, 273, 404, 31, 203, 565, 309, 261, 3413, 2686, 18434, 3335, 422, 374, 13, 2151, 2686, 18434, 3335, 273, 404, 31, 203, 565, 309, 261, 1355, 9535, 6275, 422, 374, 13, 729, 9535, 6275, 273, 404, 31, 203, 203, 565, 261, 3890, 1578, 1365, 16, 1731, 1578, 8526, 3778, 14601, 13, 273, 2103, 8478, 15609, 2471, 12, 203, 1377, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 2867, 12, 2211, 3631, 2254, 5034, 12, 1355, 9535, 6275, 3719, 3631, 203, 1377, 2151, 2686, 18434, 3335, 16, 203, 1377, 2744, 4496, 203, 565, 11272, 203, 565, 2638, 86, 558, 699, 86, 558, 273, 3272, 18, 2640, 1555, 86, 558, 12, 203, 1377, 1758, 12, 2211, 3631, 203, 1377, 1408, 203, 565, 11272, 203, 565, 261, 3890, 1578, 2191, 2375, 16, 1731, 1578, 8526, 3778, 2191, 20439, 13, 273, 2103, 8478, 15609, 2471, 12, 203, 1377, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 2867, 12, 674, 86, 558, 3631, 2254, 5034, 12, 1355, 9535, 6275, 3719, 3631, 203, 1377, 2151, 2686, 18434, 3335, 16, 203, 1377, 2744, 4496, 203, 565, 11272, 203, 565, 2638, 86, 558, 2191, 1555, 2 ]
./full_match/1/0xd15563162301EcD765bFB54eBd0809b21932C506/sources/contracts/openzeppelin/Initializable.sol
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized to any version. It is recommended to use this to lock implementation contracts that are designed to be called through proxies./
function _disableInitializers() internal virtual { _setInitializedVersion(type(uint8).max); }
3,876,987
[ 1, 19159, 326, 6835, 16, 5309, 310, 1281, 3563, 283, 6769, 1588, 18, 1220, 2780, 506, 1087, 434, 392, 12562, 745, 18, 21020, 333, 316, 326, 3885, 434, 279, 6835, 903, 5309, 716, 6835, 628, 3832, 6454, 578, 283, 13227, 358, 1281, 1177, 18, 2597, 353, 14553, 358, 999, 333, 358, 2176, 4471, 20092, 716, 854, 26584, 358, 506, 2566, 3059, 13263, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 8394, 4435, 8426, 1435, 2713, 5024, 288, 203, 565, 389, 542, 11459, 1444, 12, 723, 12, 11890, 28, 2934, 1896, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * Imports */ import "./GSN/Context.sol"; import "./token/EIP20/IEIP20.sol"; import "./token/EIP20/SafeEIP20.sol"; import "./utils/ReentrancyGuard.sol"; /** * Smart contract implementing an investment fund logic. */ contract InvestmentFund is Context, ReentrancyGuard { using SafeEIP20 for IEIP20; /* * Constants */ // Unlimited amount uint256 constant UNLIMITED_AMOUNT = 2**256 - 1; // Multiplier decimals uint256 constant MULTIPLIER_DECIMALS = 1e12; // Minimum multiplier uint256 constant MIN_MULTIPLIER = 1e12; // Contract states uint8 constant STATE_INITIAL = 0; uint8 constant STATE_BEFORE_INVESTMENT = 1; uint8 constant STATE_DURING_INVESTMENT = 2; uint8 constant STATE_AFTER_INVESTMENT = 3; /* * Structures */ /// Investor deposit structure struct InvestorDeposit { uint256 amount; // Amount of deposit uint256 index; // Investor index in array } /* * Variables */ /// Fund manager address address public fundManager; /// Pending fund manager address address public pendingFundManager; /// Token accepted by the fund IEIP20 public fundToken; /// Current state uint8 public currState; /// Force the deposit to be multiple of the specified value uint256 public depositMultipleOf; /// Minimum investor deposit uint256 public minInvestorDeposit; /// Maximum investor deposit uint256 public maxInvestorDeposit; /// Initial amount before investing uint256 public totalAmountBeforeInvestment; /// Final amount after investing uint256 public totalAmountAfterInvestment; /// Multiplier (final amount / initial amount) uint256 public investmentMultiplier; /// Address for storing funds that were not withdrawn address public remainingFundsAddr; /// List of investors deposits mapping (address => InvestorDeposit) public investorDeposits; /// List of investors addresses address[] public investors; /* * Modifiers */ /// Check if the caller is the fund manager modifier onlyFundManager() { require(fundManager == _msgSender(), "InvestmentFund: caller is not the fund manager"); _; } /// Check if the state is initial modifier onlyInitialState() { require(currState == STATE_INITIAL, "InvestmentFund: operation not allowed in current state"); _; } /// Check if the state is before investment modifier onlyBeforeInvestment() { require(currState == STATE_BEFORE_INVESTMENT, "InvestmentFund: operation not allowed in current state"); _; } /// Check if the state is during investment modifier onlyDuringInvestment() { require(currState == STATE_DURING_INVESTMENT, "InvestmentFund: operation not allowed in current state"); _; } /// Check if the state is after investment modifier onlyAfterInvestment() { require(currState == STATE_AFTER_INVESTMENT, "InvestmentFund: operation not allowed in current state"); _; } /// Check if the state is before or after investment modifier onlyBeforeOrAfterInvestment() { require((currState == STATE_BEFORE_INVESTMENT) || (currState == STATE_AFTER_INVESTMENT), "InvestmentFund: operation not allowed in current state"); _; } /* * Events */ /// Events for funds deposited by investor event InvestorFundsDeposited(address indexed investor, uint256 amount); /// Events for funds withdrawn by investor event InvestorAllFundsWithdrawn(address indexed investor, uint256 amount); /// Events for funds deposited by fund manager during investment event FundManagerFundsDeposited(address indexed owner, uint256 amount); /// Events for funds withdrawn by fund manager during investment event FundManagerFundsWithdrawn(address indexed owner, uint256 amount); /// Events for funds returned by fund manager to a specific investor after investment event FundManagerFundsReturnedToInvestor(address indexed investor, uint256 amount); /// Events for funds returned by fund manager to all investors after investment event FundManagerFundsReturnedToAllInvestors(); /// Events for setting a pending fund manager event FundManagerPendingSet(address indexed pendingAddress); /// Events for changing the fund manager event FundManagerChanged(address indexed oldAddress, address indexed newAddress); /// Events for changing the remaining funds address event RemainingFundsAddressChanged(address oldAddress, address newAddress); /// Events for changing the fund token event FundTokenChanged(address oldToken, address newToken); /// Events for changing the minimum investor deposit event DepositMultipleOfChanged(uint256 oldValue, uint256 newValue); /// Events for changing the maximum investor deposit event MinInvestorDepositChanged(uint256 oldAmount, uint256 newAmount); /// Events for changing the maximum investor deposit event MaxInvestorDepositChanged(uint256 oldAmount, uint256 newAmount); /// Events for starting investor deposit event InvestorsDepositStarted(); /// Events for stopping investor deposit event InvestorsDepositStopped(); /// Events for starting investor withdraw event InvestorsWithdrawStarted(); /// Events for stopping investor withdraw event InvestorsWithdrawStopped(); /* * Public functions (for all) */ /** * Initialize the contract. * @param fundToken_ Contract address of the token to be used for depositing/withdrawing funds (e.g. BUSD, BNB, ...) */ constructor(address fundToken_) { require(fundToken_ != address(0), "InvestmentFund: token address shall not be zero"); fundToken = IEIP20(fundToken_); fundManager = _msgSender(); pendingFundManager = address(0); remainingFundsAddr = _msgSender(); depositMultipleOf = 1; minInvestorDeposit = 1; maxInvestorDeposit = UNLIMITED_AMOUNT; _resetState(); } /** * Get the total number of investors. * @return investor_num Total number of investors */ function numberOfInvestors() external view returns (uint256 investor_num) { investor_num = investors.length; } /** * Get the total amount of deposited funds. * @return total_deposit Total amount deposited funds */ function totalDepositedFunds() public view returns (uint256 total_deposit) { total_deposit = fundToken.balanceOf(address(this)); } /** * Called by investor to deposit the specified amount before investment is started. * @param amount Amount to deposit */ function investorDeposit(uint256 amount) public onlyBeforeInvestment nonReentrant { require(amount != 0, "InvestmentFund: amount shall not be zero"); require(amount >= minInvestorDeposit, "InvestmentFund: amount shall be higher than minimum deposit"); require(amount <= maxInvestorDeposit, "InvestmentFund: amount shall be lower than maximum deposit"); require((amount % depositMultipleOf) == 0, "InvestmentFund: amount shall be multiple of depositMultipleOf"); // Get investor deposit InvestorDeposit storage investor_deposit = investorDeposits[_msgSender()]; // Update it if (investor_deposit.amount == 0) { investors.push(_msgSender()); investor_deposit.index = investors.length - 1; } investor_deposit.amount += amount; // Transfer tokens fundToken.safeTransferFrom(_msgSender(), address(this), amount); emit InvestorFundsDeposited(_msgSender(), amount); } /** * Called by investor to withdraw all the funds before of after the investment. */ function investorWithdrawAll() public onlyBeforeOrAfterInvestment nonReentrant { // Get investor deposit InvestorDeposit storage investor_deposit = investorDeposits[_msgSender()]; // Check amount require(investor_deposit.amount != 0, "InvestmentFund: no funds to withdraw"); // Compute amount uint256 withdraw_amount = _computeAmountToWithdraw(investor_deposit.amount); // Update it investor_deposit.amount = 0; // Delete investor _deleteInvestor(investor_deposit.index); // Transfer token fundToken.safeTransfer(_msgSender(), withdraw_amount); emit InvestorAllFundsWithdrawn(_msgSender(), withdraw_amount); } /* * Public functions (only owner) */ /** * Called by the owner to set a pending fund manager. * @param newFundManager Fund manager address */ function setPendingFundManager(address newFundManager) public onlyFundManager onlyInitialState { require(newFundManager != address(0), "InvestmentFund: address shall not be zero"); require(newFundManager != fundManager, "InvestmentFund: fund manager shall be different from the current one"); pendingFundManager = newFundManager; emit FundManagerPendingSet(newFundManager); } /** * Called by the pending fund manager to accept the role. */ function acceptFundManager() public onlyInitialState { require(_msgSender() == pendingFundManager, "InvestmentFund: address shall be the pending fund manager"); address old_fund_manager = fundManager; fundManager = pendingFundManager; remainingFundsAddr = pendingFundManager; pendingFundManager = address(0); emit FundManagerChanged(old_fund_manager, _msgSender()); } /* * Public functions (only fund manager) */ /** * Called by the fund manager to deposit funds during investment. * @param amount Amount to deposit */ function fundManagerDeposit(uint256 amount) public onlyFundManager onlyDuringInvestment { require(amount != 0, "InvestmentFund: amount shall not be zero"); fundToken.safeTransferFrom(_msgSender(), address(this), amount); emit FundManagerFundsDeposited(_msgSender(), amount); } /** * Called by the fund manager to withdraw the specified amount of funds during investment. * @param amount Amount to withdraw */ function fundManagerWithdraw(uint256 amount) public onlyFundManager onlyDuringInvestment { require(amount != 0, "InvestmentFund: amount shall not be zero"); fundToken.safeTransfer(_msgSender(), amount); emit FundManagerFundsWithdrawn(_msgSender(), amount); } /** * Called by the fund manager to withdraw all funds during investment. */ function fundManagerWithdrawAll() public onlyFundManager onlyDuringInvestment { fundManagerWithdraw(totalDepositedFunds()); } /** * Called by the fund manager to return funds to a specific investor after investment. * Useful for forcing the withdraw of funds to a specific investor. * @param investor Investor address */ function fundManagerReturnFundsToInvestor(address investor) public onlyFundManager onlyAfterInvestment { // Get investor deposit InvestorDeposit storage investor_deposit = investorDeposits[investor]; // Check amount require(investor_deposit.amount != 0, "InvestmentFund: no funds to withdraw"); // Compute amount uint256 withdraw_amount = _computeAmountToWithdraw(investor_deposit.amount); // Reset deposit investor_deposit.amount = 0; // Transfer token fundToken.safeTransfer(investor, withdraw_amount); // Delete investor _deleteInvestor(investor_deposit.index); emit FundManagerFundsReturnedToInvestor(investor, withdraw_amount); } /** * Called by the fund manager to return all funds to investors after investment. * Useful for forcing the withdraw of funds to all investors. * @dev It can be expensive in terms of gas, it's better to call it only if there are few investors remaining */ function fundManagerReturnFundsToAllInvestors() public onlyFundManager onlyAfterInvestment { require(investors.length != 0, "InvestmentFund: no investors left"); // Withdraw to all investors for (uint256 i = 0; i < investors.length; i++) { // Get investor deposit address investor_addr = investors[i]; InvestorDeposit storage investor_deposit = investorDeposits[investor_addr]; if (investor_deposit.amount != 0) { // Compute amount uint256 withdraw_amount = _computeAmountToWithdraw(investor_deposit.amount); // Reset deposit investor_deposit.amount = 0; // Transfer token fundToken.safeTransfer(investor_addr, withdraw_amount); } } // Delete all investors delete investors; emit FundManagerFundsReturnedToAllInvestors(); } /** * Called by the fund manager to set the address to withdraw remaining funds. * @param remainingFundsAddr_ Address to withdraw remaining funds */ function setRemainingFundsAddress(address remainingFundsAddr_) public onlyFundManager onlyInitialState { require(remainingFundsAddr_ != address(0), "InvestmentFund: address shall not be zero"); address old_addr = remainingFundsAddr; remainingFundsAddr = remainingFundsAddr_; emit RemainingFundsAddressChanged(old_addr, remainingFundsAddr_); } /** * Called by the fund manager to set the fund token address. * @param fundToken_ Fund token address */ function setFundToken(address fundToken_) public onlyFundManager onlyInitialState { require(fundToken_ != address(0), "InvestmentFund: fund token shall not be the zero address"); address old_token = address(fundToken); fundToken = IEIP20(fundToken_); emit FundTokenChanged(old_token, fundToken_); } /** * Called by the fund manager to set the deposit multiple of. * @param value Deposit multiple of */ function setDepositMultipleOf(uint256 value) public onlyFundManager onlyInitialState { require(value != 0, "InvestmentFund: value shall not be zero"); uint256 old_value = depositMultipleOf; depositMultipleOf = value; emit DepositMultipleOfChanged(old_value, value); } /** * Called by the fund manager to set the minimum investor deposit. * @param amount Minimum investor deposit amount */ function setMinInvestorDeposit(uint256 amount) public onlyFundManager onlyInitialState { require(amount != 0, "InvestmentFund: minimum amount shall not be zero"); require(amount < maxInvestorDeposit, "InvestmentFund: minimum amount shall be lower than the maximum one"); require((amount % depositMultipleOf) == 0, "InvestmentFund: amount shall be multiple of depositMultipleOf"); uint256 old_value = minInvestorDeposit; minInvestorDeposit = amount; emit MinInvestorDepositChanged(old_value, amount); } /** * Called by the fund manager to set the maximum investor deposit. * @param amount Maximum investor deposit amount */ function setMaxInvestorDeposit(uint256 amount) public onlyFundManager onlyInitialState { require(amount != 0, "InvestmentFund: maximum amount shall not be zero"); require(amount > minInvestorDeposit, "InvestmentFund: maximum amount shall be higher than the minimum one"); require((amount % depositMultipleOf) == 0, "InvestmentFund: amount shall be multiple of depositMultipleOf"); uint256 old_value = maxInvestorDeposit; maxInvestorDeposit = amount; emit MaxInvestorDepositChanged(old_value, amount); } /** * Called by the fund manager to start investors deposit. */ function startInvestorsDeposit() public onlyFundManager onlyInitialState { currState = STATE_BEFORE_INVESTMENT; emit InvestorsDepositStarted(); } /** * Called by the fund manager to stop investors deposit. */ function stopInvestorsDeposit() public onlyFundManager onlyBeforeInvestment { // Update state currState = STATE_DURING_INVESTMENT; // Get initial amount before investment totalAmountBeforeInvestment = totalDepositedFunds(); emit InvestorsDepositStopped(); } /** * Called by the fund manager to start investors withdraw. */ function startInvestorsWithdraw() public onlyFundManager onlyDuringInvestment { // Update state currState = STATE_AFTER_INVESTMENT; // Get final amount after investment totalAmountAfterInvestment = totalDepositedFunds(); // Compute multiplier investmentMultiplier = _computeMultiplier(); emit InvestorsWithdrawStarted(); } /** * Called by the fund manager to stop investors withdraw. */ function stopInvestorsWithdraw() public onlyFundManager onlyAfterInvestment { // Withdraw any remaining funds _withdrawRemainingFunds(); // Delete all investors _deleteAllInvestors(); // Reset state _resetState(); emit InvestorsWithdrawStopped(); } /* * Internal functions */ /** * Compute the investment multiplier. * @return multiplier Investment multiplier */ function _computeMultiplier() internal view returns (uint256 multiplier) { multiplier = ((totalAmountAfterInvestment * MULTIPLIER_DECIMALS) / totalAmountBeforeInvestment); } /** * Compute the amount to withdraw after investment. * @param initialAmount Initial amount * @return amount Amount to withdraw after investment */ function _computeAmountToWithdraw(uint256 initialAmount) internal view returns (uint256 amount) { amount = ((initialAmount * investmentMultiplier) / MULTIPLIER_DECIMALS); } /** * Withdraw remaining funds. */ function _withdrawRemainingFunds() internal { uint256 remaining_funds = totalDepositedFunds(); if (remaining_funds != 0) { fundToken.safeTransfer(remainingFundsAddr, remaining_funds); } } /** * Delete the specified investor. * @param index Investor index in array * @dev Since order doesn't matter, the last element is copied to the element do be deleted. * If investor index doesn't exist, nothing is done. */ function _deleteInvestor(uint256 index) internal { if (index >= investors.length) return; address last_investor = investors[investors.length - 1]; investors[index] = last_investor; investors.pop(); // Update the index of investor that has been just moved investorDeposits[last_investor].index = index; } /** * Delete all investors deposits. */ function _deleteAllInvestors() internal { if (investors.length != 0) { // Reset deposit amounts for (uint i = 0; i < investors.length; i++) { investorDeposits[investors[i]].amount = 0; } // Delete investor array delete investors; } } /** * Reset state. */ function _resetState() internal { currState = STATE_INITIAL; totalAmountBeforeInvestment = 0; totalAmountAfterInvestment = 0; investmentMultiplier = MIN_MULTIPLIER; } }
* Called by the fund manager to stop investors withdraw./ Withdraw any remaining funds Delete all investors Reset state
function stopInvestorsWithdraw() public onlyFundManager onlyAfterInvestment { _withdrawRemainingFunds(); _deleteAllInvestors(); _resetState(); emit InvestorsWithdrawStopped(); }
14,116,134
[ 1, 8185, 635, 326, 284, 1074, 3301, 358, 2132, 2198, 395, 1383, 598, 9446, 18, 19, 3423, 9446, 1281, 4463, 284, 19156, 2504, 777, 2198, 395, 1383, 7151, 919, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2132, 3605, 395, 1383, 1190, 9446, 1435, 1071, 1338, 42, 1074, 1318, 1338, 4436, 3605, 395, 475, 288, 203, 3639, 389, 1918, 9446, 11429, 42, 19156, 5621, 203, 3639, 389, 3733, 1595, 3605, 395, 1383, 5621, 203, 3639, 389, 6208, 1119, 5621, 203, 203, 3639, 3626, 5454, 395, 1383, 1190, 9446, 15294, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; pragma experimental ABIEncoderV2; import "chainlink/contracts/ChainlinkClient.sol"; import "./Shared.sol"; /** * The PredictEvent contract is one Event, where people can bet on outcome of some api */ contract PredictEvent is ChainlinkClient { // Orderbook to trade each possible outcome struct Order { uint amount; uint price; address owner; uint filled; bool isBuy; uint marketID; } // Que of all orders at that level struct OrderbookLevel{ Order[] BuyOrdersQueue; uint unfilledBuyOrdersPointer; uint unffilledBuys; Order[] SellOrdersQueue; uint unfilledSellOrdersPointer; uint unffilledSells; uint sellLen; uint buyLen; } uint256 constant private ORACLE_PAYMENT = 1 * LINK; event logs(string agg,uint a); event lord( uint amount, uint price, address owner, uint filled, bool isBuy, uint marketID ); function showOrder (uint a,uint b, uint c, bool isBuy) constant public returns(Order res) { if(isBuy){ return Orderbooks[a][b].BuyOrdersQueue[c]; }else{ return Orderbooks[a][b].SellOrdersQueue[c]; } } function getOutcomes () constant public returns(Shared.Outcome[] res) { return Event.possibleOutcomes; } // Event result -> price of asset -> orderbooklevel mapping(uint => mapping(uint => OrderbookLevel)) public Orderbooks; uint[] public highest_limit_buy; uint[] public lowest_limit_sell; Shared.Event public Event; uint public eventFinalResult; uint public rslt; bool public finalized; bool public initialized; mapping (address => uint) public toPay; address[] public addressesToPay; mapping (address => uint) public deposited; address[] public depositedA; address constant public oracleAdd = 0xbd8524180968A12dcBE5C881E21DDAbd1Ba7F4a1; bool locked; uint maximumBumberOfOrders; // to prevent stalling contract bytes32 CHAINLINKERRORCONST = bytes32("CHAINLING NODE ERROR"); // magical value, returned by adapter when error occurs uint constant weekInSeconds = 7*24*3600; address finalizer; constructor() public { setChainlinkToken(0x20fe562d797a42dcb3399062ae9546cd06f63280); } function showBooks() constant returns(uint[100][2][10] res) { for(uint a =0; a<10;a++){ for(uint x =0; x<100;x++){ res[a][0][x] = Orderbooks[a][x].unffilledBuys; res[a][1][x] = Orderbooks[a][x].unffilledSells; } } return res; } function showBook(uint a) constant returns(uint[100][2][10] res) { for(uint x =0; x<100;x++){ res[a][0][x] = Orderbooks[a][x].unffilledBuys; res[a][1][x] = Orderbooks[a][x].unffilledSells; } return res; } function computeLimits (uint _EventID) constant returns(uint buy, uint sell) { buy = 0; sell = 100; for(uint x =0; x<100;x++){ if(Orderbooks[_EventID][x].unffilledBuys > 0){ buy = x; } if(Orderbooks[_EventID][99-x].unffilledSells > 0){ sell = 99-x; } } return (buy,sell); } function placeOrder( uint _price, uint _amount, bool _isBuy, uint _EventID ) public payable { require (_price > 0 && _price < 100); require (_EventID < Event.possibleOutcomes.length && _EventID >=0 ); require (_amount > 0); if(_isBuy){ require (msg.value >= _price * _amount); }else{ require (msg.value >= (100 - _price) * _amount); } (highest_limit_buy[_EventID], lowest_limit_sell[_EventID]) = computeLimits(_EventID); if (_isBuy){ emit logs("BUY ORDER",0); placeBuyOrder(_price,_amount,msg.sender,_EventID); } else{ emit logs("SELL ORDER",0); placeSellOrder(_price,_amount,msg.sender,_EventID); } (highest_limit_buy[_EventID], lowest_limit_sell[_EventID]) = computeLimits(_EventID); if(deposited[msg.sender] == 0){ depositedA.push(msg.sender); } deposited[msg.sender] += msg.value*9/10; } function placeBuyOrder( uint _price, uint _amount, address _owner, uint result) internal { if (_price < lowest_limit_sell[result]) { // Limit buy order emit logs("BUY LIMIT ORDER",0); Order memory order = Order({ amount : _amount, price : _price, owner : _owner, marketID : result, isBuy : true, filled : 0 }); Orderbooks[result][_price].BuyOrdersQueue.push(order); Orderbooks[result][_price].unffilledBuys +=_amount; emit lord(_amount,_price,_owner,0,true,result); } else{ // Event order, will fill some limit sell orders emit logs("BUY Event ORDER",0); uint remaining_amount = _amount; uint matchprice = lowest_limit_sell[result]; for (; remaining_amount >0 && matchprice <= _price; matchprice++ ){ // we go from best price to higher price emit logs("If for cycle, price:" , matchprice); uint filledThisLevel = 0; uint priceLevelOrderCount = Orderbooks[result][matchprice].SellOrdersQueue.length; uint unfilledSellOrdersPointer = Orderbooks[result][matchprice].unfilledSellOrdersPointer; emit logs("ordercount " , priceLevelOrderCount); emit logs("unfilpointer " , unfilledSellOrdersPointer); // for one price, we iterate through all sell orders of that price for (uint i=unfilledSellOrdersPointer; i<priceLevelOrderCount && remaining_amount > 0; i++) { Order storage sellOrder = Orderbooks[result][matchprice].SellOrdersQueue[i]; // Our order is bigger that limit order, we fill it if (remaining_amount >= sellOrder.amount - sellOrder.filled){ remaining_amount -= (sellOrder.amount - sellOrder.filled); // my remaining amount to fill Orderbooks[result][matchprice].unfilledSellOrdersPointer++; // move pointer filledThisLevel += (sellOrder.amount - sellOrder.filled); // amount we filled on this level sellOrder.filled = sellOrder.amount; // fill sell order } else{ // we can just partially fill the order // Orderbooks[result][matchprice].unfilledSellOrdersPointer++; order is not filled sellOrder.filled += remaining_amount; filledThisLevel += remaining_amount; remaining_amount = 0; } } order = Order({ amount : filledThisLevel, owner : _owner, price : matchprice, isBuy : true, filled : filledThisLevel, marketID : result }); emit lord(filledThisLevel,matchprice,_owner,filledThisLevel,true,result); Orderbooks[result][matchprice].BuyOrdersQueue.push(order); Orderbooks[result][matchprice].unfilledBuyOrdersPointer++; Orderbooks[result][matchprice].unffilledSells -=filledThisLevel; if ( remaining_amount > 0 && matchprice == _price ){ // we will go for another level, just insert filled order here order = Order({ amount : remaining_amount, marketID : result, owner : _owner, price : matchprice, isBuy : true, filled : 0 }); emit lord(remaining_amount,matchprice,_owner,0,true,result); Orderbooks[result][matchprice].BuyOrdersQueue.push(order); Orderbooks[result][matchprice].unffilledBuys +=remaining_amount; } } } } function placeSellOrder( uint _price, uint _amount, address _owner, uint result) internal { if (_price > highest_limit_buy[result]) { // Limit sell order emit logs("SELL LIMIT ORDER",0); Order memory order = Order({ amount : _amount, owner : _owner, isBuy : false, price : _price, marketID : result, filled : 0 }); Orderbooks[result][_price].SellOrdersQueue.push(order); Orderbooks[result][_price].unffilledSells +=_amount; emit lord(_amount,_price,_owner,0,false,result); } else{ // Event order, will fill some limit buy orders uint remaining_amount = _amount; uint matchprice = highest_limit_buy[result]; for (; remaining_amount >0 && matchprice >= _price; matchprice-- ){ // we go from best price to higher price uint filledThisLevel = 0; uint priceLevelOrderCount = Orderbooks[result][matchprice].BuyOrdersQueue.length; uint unfilledBuyOrdersPointer = Orderbooks[result][matchprice].unfilledBuyOrdersPointer; // for one price, we iterate through all sell orders of that price for (uint i=unfilledBuyOrdersPointer; i<priceLevelOrderCount && remaining_amount > 0; i++) { Order storage buyOrder = Orderbooks[result][matchprice].BuyOrdersQueue[i]; // Our order is bigger that limit order, we fill it if (remaining_amount >= buyOrder.amount - buyOrder.filled){ remaining_amount -= (buyOrder.amount - buyOrder.filled); // my remaining amount to fill Orderbooks[result][matchprice].unfilledBuyOrdersPointer++; // move pointer filledThisLevel += (buyOrder.amount - buyOrder.filled); // amount we filled on this level buyOrder.filled = buyOrder.amount; // fill sell order } else{ // we can just partially fill the order // Orderbooks[result][matchprice].unfilledbuyOrdersPointer++; order is not filled buyOrder.filled += remaining_amount; filledThisLevel += remaining_amount; remaining_amount = 0; } } order = Order({ amount : filledThisLevel, owner : _owner, price : matchprice, marketID : result, isBuy : false, filled : filledThisLevel }); emit lord(filledThisLevel,matchprice,_owner,filledThisLevel,false,result); Orderbooks[result][matchprice].SellOrdersQueue.push(order); Orderbooks[result][matchprice].unfilledSellOrdersPointer++; Orderbooks[result][matchprice].unffilledBuys -=filledThisLevel; // we compute how much we filled and append filled order into sellorders. // There could be multiple filled sell orders from the past if ( remaining_amount > 0 && matchprice == _price ){ // we will go for another level, just insert filled order here order = Order({ amount : remaining_amount, owner : _owner, price : matchprice, isBuy : false, marketID : result, filled : 0 }); emit lord(remaining_amount,matchprice,_owner,0,false,result); Orderbooks[result][matchprice].SellOrdersQueue.push(order); Orderbooks[result][matchprice].unffilledSells +=remaining_amount; } } } } function initialize (Shared.Event _Event ) public { // require (!initialized); initialized = true; setPublicChainlinkToken; Event.name = _Event.name; Event.eventResolutionTimestamp = _Event.eventResolutionTimestamp; Event.request = _Event.request; Event.description = _Event.description; // Event = _Event; for (uint x = 0; x < _Event.possibleOutcomes.length; x++) { highest_limit_buy.push(0); lowest_limit_sell.push(100); Event.possibleOutcomes.push(_Event.possibleOutcomes[x]); } } event InvalidChainlinkRequest(address finalizer); address public last_finalizer; modifier noReentrancy() { require( !locked, "Reentrant call." ); locked = true; _; locked = false; } function finalize(string auth_token) public noReentrancy { require (now > Event.eventResolutionTimestamp); require (!finalized); finalizer = msg.sender; if (now > Event.eventResolutionTimestamp + weekInSeconds // week passed after end of Event && !finalized){ // and not finalized // doInvalidTransactions(); // emit logs("invalidated",0); // finalized = true; // return; } getChainlinkResult(auth_token); } function getChainlinkResult (string auth_token) public { bytes32 jobId = 0x3836313963653230336365623438643238386161323463383861653430346135; Shared.ApiRequest storage r = Event.request; // newRequest takes a JobID, a callback address, and callback function as input Chainlink.Request memory req = buildChainlinkRequest(jobId, this, this.fulfill.selector); req.add("apiPath", r.apiPath); req.add("httpPostOrGet", r.httpPostOrGet); if(bytes(r.getData).length>0){ req.add("getData", r.getData); } if(bytes(r.postData).length >0){ req.add("postData", r.postData); } req.add("jsonRegexString", r.jsonRegexString); req.add("auth_token", auth_token); req.add("copyPath", "data"); // req.addInt("times",1000); sendChainlinkRequestTo(oracleAdd, req, ORACLE_PAYMENT); } function evf (uint e) public { eventFinalResult = e; } function fulfill(bytes32 _requestId, uint256 _result) public // Use recordChainlinkFulfillment to ensure only the requesting oracle can fulfill recordChainlinkFulfillment(_requestId) { rslt = _result; eventFinalResult = result_to_index(rslt); // eventFinalResult is index of Event, that won computeWinners(); sendEtherToWinners(); finalized=true; } function sendEtherToWinners () public returns(bool res) { finalized = true; for(uint x=0; x<addressesToPay.length;x++){ address add = addressesToPay[x]; string memory z = toString(add); uint amount = toPay[add]; emit logs("Paying",amount); emit logs(z,amount); require(add.send(amount)); } return true; // to trigger noReentry } function substring (string memory what, string memory where) internal returns(bool res) { bytes memory whatBytes = bytes (what); bytes memory whereBytes = bytes (where); bool found = false; for (uint i = 0; i < whereBytes.length - whatBytes.length; i++) { bool flag = true; for (uint j = 0; j < whatBytes.length; j++) if (whereBytes [i + j] != whatBytes [j]) { flag = false; break; } if (flag) { found = true; break; } } } function bytes32ToStr(bytes32 _bytes32) public pure returns (string) { // string memory str = string(_bytes32); // TypeError: Explicit type conversion not allowed from "bytes32" to "string storage pointer" // thus we should fist convert bytes32 to bytes (to dynamically-sized byte array) bytes memory bytesArray = new bytes(32); for (uint256 i; i < 32; i++) { bytesArray[i] = _bytes32[i]; } return string(bytesArray); } function result_to_index (uint uResult) internal returns(uint ret) { for(uint x=0;x<Event.possibleOutcomes.length;x++){ // all price levels Shared.Outcome storage outcome = Event.possibleOutcomes[x]; if(outcome.minValue <= uResult && outcome.maxValue >= uResult){ return x; } } return 2**255-1; } function computeWinners () public returns(bool res) { require (!finalized); Order[] memory queue; for(uint outcome=0;outcome<Event.possibleOutcomes.length;outcome++){ for(uint price=0;price<100;price++){ // all price levels if(outcome == eventFinalResult){ queue = Orderbooks[outcome][price].BuyOrdersQueue; }else{ queue = Orderbooks[outcome][price].SellOrdersQueue; } for(uint z=0;z<queue.length;z++){ emit logs("queue:z",z ); emit logs("price",price ); emit logs("outcome",outcome ); address owner = queue[z].owner; uint amount = queue[z].filled*100; emit logs("amount",amount ); if(toPay[owner] == 0){ addressesToPay.push(owner); } toPay[owner]+=amount; emit lord( amount, price, owner, queue[z].filled, queue[z].isBuy, outcome ); } } } } function toString(address x) returns (string) { bytes memory b = new bytes(20); for (uint i = 0; i < 20; i++) b[i] = byte(uint8(uint(x) / (2**(8*(19 - i))))); return string(b); } function doInvalidTransactions () internal returns(bool res) { require (!finalized); finalized = true; for(uint x=0; x<depositedA.length;x++){ address add = depositedA[x]; string memory z = toString(add); uint amount = deposited[add]; emit logs("PLATIM",amount); emit logs(z,amount); require(add.send(amount)); } return true; // to trigger noReentry } }
amount we filled on this level
filledThisLevel += (sellOrder.amount - sellOrder.filled);
5,541,493
[ 1, 8949, 732, 6300, 603, 333, 1801, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 13491, 6300, 2503, 2355, 1011, 261, 87, 1165, 2448, 18, 8949, 300, 357, 80, 2448, 18, 13968, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` 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 from, address to, 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); } // File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: Vault.sol pragma solidity ^0.8.6; /** * @title Vault Contract */ contract Vault is Ownable, ReentrancyGuard { using Address for address; using SafeERC20 for IERC20; /// @notice Event emitted on construction. event VaultDeployed(); /// @notice Event emitted when new teller is added to vault. event NewTellerAdded(address newTeller, uint256 priority); /// @notice Event emitted when current priority is changed. event TellerPriorityChanged(address teller, uint256 newPriority); /// @notice Event emitted when tokens are paid to provider. event ProviderPaid(address indexed provider, uint256 indexed rewardAmount); /// @notice Event emitted when token rate is calculated. event RewardRateCalculated(uint256 rewardRate); IERC20 public Reward; mapping(address => bool) public teller; mapping(address => uint256) public tellerPriority; mapping(address => uint256) public priorityFreeze; uint256 public totalPriority; uint256 public rewardRate; uint256 public timeToCalculateRate; uint256 public totalDistributed; modifier onlyTeller() { require(teller[msg.sender], "Vault: Caller is not a teller."); _; } /** * @dev Constructor function * @param _Reward Interface of Reward token => Sample"Vidya"(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30) */ constructor(IERC20 _Reward) { Reward = _Reward; emit VaultDeployed(); } /** * @dev External function to add a teller. This function can be called only by the owner. * @param _teller Address of teller * @param _priority Priority of teller */ function addTeller(address _teller, uint256 _priority) external onlyOwner { require( _teller.isContract() == true, "Vault: Address is not a contract." ); require(!teller[_teller], "Vault: Caller is already a teller."); require(_priority > 0, "Vault: Priority should be greater than zero."); teller[_teller] = true; tellerPriority[_teller] = _priority; totalPriority += _priority; priorityFreeze[_teller] = block.timestamp + 7 days; emit NewTellerAdded(_teller, _priority); } /** * @dev External function to change the priority of a teller. This function can be called only by the owner. * @param _teller Address of teller * @param _newPriority New priority of teller */ function changePriority(address _teller, uint256 _newPriority) external onlyOwner { require( _teller.isContract() == true, "Vault: Address is not a contract." ); require(teller[_teller], "Vault: Provided address is not a teller."); require( priorityFreeze[_teller] <= block.timestamp, "Vault: Priority freeze is still in effect." ); uint256 _oldPriority = tellerPriority[_teller]; totalPriority = (totalPriority - _oldPriority) + _newPriority; tellerPriority[_teller] = _newPriority; priorityFreeze[_teller] = block.timestamp + 1 weeks; emit TellerPriorityChanged(_teller, _newPriority); } /** * @dev External function to pay depositors. This function can be called only by a teller. * @param _provider Address of provider * @param _providerTimeWeight Weight time of provider * @param _totalWeight Sum of provider weight */ function payProvider( address _provider, uint256 _providerTimeWeight, uint256 _totalWeight ) external onlyTeller { uint256 numerator = rewardRate * _providerTimeWeight * tellerPriority[msg.sender]; uint256 denominator = _totalWeight * totalPriority; uint256 amount; if (denominator != 0) { amount = numerator / denominator; } if (timeToCalculateRate <= block.timestamp) { _calculateRate(); } totalDistributed += amount; Reward.safeTransfer(_provider, amount); emit ProviderPaid(_provider, amount); } /** * @dev Internal function to calculate the token Rate. */ function _calculateRate() internal { rewardRate = Reward.balanceOf(address(this)) / 26 weeks; // 6 months timeToCalculateRate = block.timestamp + 1 weeks; emit RewardRateCalculated(rewardRate); } /** * @dev External function to calculate the token Rate. */ function calculateRate() external nonReentrant { require( timeToCalculateRate <= block.timestamp, "Vault: Rate calculation not yet possible." ); _calculateRate(); } }
* @dev Internal function to calculate the token Rate./
function _calculateRate() internal { timeToCalculateRate = block.timestamp + 1 weeks; emit RewardRateCalculated(rewardRate); }
4,799,832
[ 1, 3061, 445, 358, 4604, 326, 1147, 13025, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 11162, 4727, 1435, 2713, 288, 203, 3639, 23813, 8695, 4727, 273, 1203, 18, 5508, 397, 404, 17314, 31, 203, 203, 3639, 3626, 534, 359, 1060, 4727, 4844, 690, 12, 266, 2913, 4727, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xdac4585B741E5b6625CEc460D2A255fB3FBE0D47/sources/contracts/RariFundPriceConsumer.sol
Set prices[5] to sUSD
prices[5] = prices[0];
3,925,111
[ 1, 694, 19827, 63, 25, 65, 358, 272, 3378, 40, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 19827, 63, 25, 65, 273, 19827, 63, 20, 15533, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; /** * Contrato que representa um sensor DHT11. Este contrato é responsável por receber, armazenar e monitorar todas as leituras * do sensor DHT11, de tal forma que, se um valor exceder o máximo predefinido, este gera um evento que pode ser recuperado * por uma aplicação exterior para tomar uma decisão. * * VARIÁVEIS DO CONTRATO * owner: Dono do contrato, que será o produtor * manager: Gerenciador do contrato, que será o Middleware * name: Nome do sensor * ids: Id do sensor (relacionado com o Banco de Dados) * max_temperature: A temperatura máxima. Caso a captura ultrapasse superiormente esse valor, o código gera um evento (temperatureOverflow); * min_temperature: A temperatura mínima. Caso a captura ultrapasse inferiormente esse valor, o código gera um evento (temperatureUnderflow); * max_humidity: A umidade máxima. Caso a captura ultrapasse superiormente esse valor, o código gera um evento (humidityOverflow); * min_humidity: A umidade mínima. Caso a captura ultrapasse inferiormente esse valor, o código gera um evento (humidityUnderflow); * temperatures: Um array para armazenar todas as capturas de temperatura ambiente; * temperatures_count: Conta a quantidade de capturas de temperatura salvas na lista "tempereatures" * humidities: Um array para armazenar todas as capturas de umidade ambiente; * humidities_count: Conta a quantidade de capturas de umidade salvas na lista "humidities" * * EVENTOS * temperatureOverflow: É gerado quando uma captura de temperatura ultrapassa superiormente seu valor máximo (max_temperature); * temperatureUnderflow: É gerado quando uma captura de temperatura ultrapassa inferiormente seu valor mínimo (min_temperature); * humidityOverflow: É gerado quando uma captura de umidade ultrapassa superiormente seu valor máximo (max_humidity) * humidityUnderflow: É gerado quando uma captura de umidade ultrapassa inferiormente seu valor mínimo (min_humidity) **/ contract DHT11{ //DADOS DE IDENTIFICAÇÃO address public owner; address public manager; string public name; uint public ids; //ESTRUTURA PARA ARMAZENAR MEDIDAS struct T_Measures { uint[] temperatures; uint[] humidities; } mapping(uint => T_Measures) private fermentations; // VALORES PARA CONTROLE uint public max_temperature; uint public min_temperature; uint public max_humidity; uint public min_humidity; //LISTAS PARA ARMAZENAR LEITURAS // uint[] public temperature; // uint temperatures_count; // uint[] public humiditie; // uint humidities_count; //EVENTOS event temperatureOverflow(uint temperature, uint max_temperature); event temperatureUnderflow(uint temperature, uint min_temperature); event humidityOverflow(uint humidity, uint max_humidity); event humidityUnderflow(uint humidity, uint min_humidity); /*MODIFICADORES*/ /** * Nome do Modificador: onlyOwnerOrManager * * Autor: Levy Santiago * * Descrição: Utilizado para restringir acesso somente ao dono e gerenciador do contrato em determinadas funções * * Parâmetros: * - address _owner: Um endereço. Este será válido somente se for o endereço do dono ou do gerenciador de contrato. * * Retorno: * - null **/ modifier onlyOwnerOrManager(address _address){ require(_address == manager || _address == owner); _; } /** * Nome da Função: constructor * * Autor: Levy Santiago * * Descrição: Primeira função a ser chamada ao implementar o contrato na rede Ethereum. Esta inicializa o gerenciador (dono) do contrato, * o nome e valores iniciais para valores máximos e mínimos, os quais podem ser alterados pelo dono do contrato. * * Escopo: public * * Parâmetros: * - address _owner: O endereço do dono do contrato. * * Retorno: * - null **/ constructor(address _owner) public { owner = _owner; manager = msg.sender; name = 'DHT11'; max_temperature = 10; min_temperature = 0; max_humidity = 10; min_humidity = 0; } /*FUNÇÕES SET CONDICIONAIS*/ /** * Nome da Função: setTemperature * * Autor: Levy Santiago * * Descrição: Recebe um novo valor de temperatura, adiciona na lista de temperaturas capturadas e verifica se o valor recebido * ultrapassa superiormente ou inferiormente o mínimo e máximo. * * Escopo: public * * Parâmetros: * - _temperature: A nova leitura de temperatura obtida. * * Retorno: * null * * Eventos: * Pode gerar os eventos "temperatureOverflow" ou "temperatureUnderflow" * - temperatureOverflow: É gerado quando "_temperature" ultrapassa superiormente "max_temperature"; * - temperatureUnderflow: É gerado quando "_temperature" ultrapassa inferiormente "min_temperature". * * Restrição: * - onlyOwnerOrManager: Somente o dono ou gerenciador do contrato pode realizar esta operação **/ function setTemperature(uint _temperature, uint _fermentation_id) public onlyOwnerOrManager(msg.sender) { uint[] storage temperatures = fermentations[_fermentation_id].temperatures; temperatures.push(_temperature); if(_temperature >= max_temperature){ emit temperatureOverflow(_temperature, max_temperature); } else if(_temperature <= min_temperature){ emit temperatureUnderflow(_temperature, min_temperature); } } /** * Nome da Função: setHumidity * * Autor: Levy Santiago * * Descrição: Recebe um novo valor de umidade, adiciona na lista de umidades capturadas e verifica se o valor recebido * ultrapassa superiormente ou inferiormente o mínimo e máximo. * * Escopo: public * * Parâmetros: * - _humidity: A nova leitura de umidade obtida. * * Retorno: * null * * Eventos: * Pode gerar os eventos "humidityOverflow" ou "humidityUnderflow" * - humidityOverflow: É gerado quando "_humidity" ultrapassa superiormente "max_humidity"; * - humidityUnderflow: É gerado quando "_humidity" ultrapassa inferiormente "min_humidity". * * Restrição: * - onlyOwnerOrManager: Somente o dono ou gerenciador do contrato pode realizar esta operação **/ function setHumidity(uint _humidity, uint _fermentation_id) public onlyOwnerOrManager(msg.sender) { uint[] storage humidities = fermentations[_fermentation_id].humidities; humidities.push(_humidity); if(_humidity >= max_humidity){ emit humidityOverflow(_humidity, max_humidity); } else if(_humidity <= min_humidity){ emit humidityUnderflow(_humidity, min_humidity); } } /** FUNÇÕES SET **/ /** * Nome da Função: setName * * Autor: Levy Santiago * * Descrição: Atualiza o nome do contrato * * Escopo: public * * Parâmetros: * - _name: O novo nome do contrato. * - msg.sender: O endereço de quem está invocando a função * * Retorno: * null * * Restrição: * - onlyOwnerOrManager: Somente o dono ou gerenciador do contrato pode realizar esta operação **/ function setName(string _name) public onlyOwnerOrManager(msg.sender){ name = _name; } /** * Nome da Função: setIds * * Autor: Levy Santiago * * Descrição: Atualiza o Id do sensor que o contrato representa * * Escopo: public * * Parâmetros: * - _ids: O novo ID do sensor; * - msg.sender: O endereço de quem está invocando a função * * Retorno: * null * * Restrição: * - onlyOwnerOrManager: Somente o dono ou gerenciador do contrato pode realizar esta operação **/ function setIds(uint _ids) public onlyOwnerOrManager(msg.sender){ ids = _ids; } /** * Nome da Função: setMaxHumidity * * Autor: Levy Santiago * * Descrição: Atualiza o valor máximo da umidade para invocar futuramente um evento * * Escopo: public * * Parâmetros: * - _max_humidity: O novo valor máximo de umidade. * * Retorno: * null * * Restrição: * - onlyOwnerOrManager: Somente o dono ou gerenciador do contrato pode realizar esta operação **/ function setMaxHumidity(uint _max_humidity) public onlyOwnerOrManager(msg.sender){ assert(_max_humidity > 0 && _max_humidity > min_humidity); max_humidity = _max_humidity; } /** * Nome da Função: setMaxTemperature * * Autor: Levy Santiago * * Descrição: Atualiza o valor máximo da temperatura para invocar futuramente um evento * * Escopo: public * * Parâmetros: * - _max_temperature: O novo valor máximo de temperatura. * * Retorno: * null * * Restrição: * - onlyOwnerOrManager: Somente o dono ou gerenciador do contrato pode realizar esta operação **/ function setMaxTemperature(uint _max_temperature) public onlyOwnerOrManager(msg.sender){ assert(_max_temperature > 0 && _max_temperature > min_temperature); max_temperature = _max_temperature; } /** * Nome da Função: setMinHumidity * * Autor: Levy Santiago * * Descrição: Atualiza o valor mínimo da umidade para invocar futuramente um evento * * Escopo: public * * Parâmetros: * - _min_humidity: O novo valor mínimo de umidade. * * Retorno: * null * * Restrição: * - onlyOwnerOrManager: Somente o dono ou gerenciador do contrato pode realizar esta operação **/ function setMinHumidity(uint _min_humidity) public onlyOwnerOrManager(msg.sender){ assert(_min_humidity >= 0 && _min_humidity < max_temperature); min_humidity = _min_humidity; } /** * Nome da Função: setMinTemperature * * Autor: Levy Santiago * * Descrição: Atualiza o valor mínimo da temperatura para invocar futuramente um evento * * Escopo: public * * Parâmetros: * - _min_humidity: O novo valor mínimo de temperatura. * * Retorno: * null * * Restrição: * - onlyOwnerOrManager: Somente o dono ou gerenciador do contrato pode realizar esta operação **/ function setMinTemperature(uint _min_temperature) public onlyOwnerOrManager(msg.sender){ assert(_min_temperature >= 0 && _min_temperature < max_temperature); min_temperature = _min_temperature; } /** FUNÇÕES GET **/ /** * Nome da Função: getLastValues * * Autor: Levy Santiago * * Descrição: Retorna os últimos valores lidos de temperatura e umidade (temperature e humidity) * * Escopo: public * * Parâmetros: * null * * Retorno: * - uint temperature: A última temperatura recebida pelo contrato; * - uint humidity: A última umidade recebida pelo contrato; **/ function getLastValues(uint _fermentation_id) public view returns(uint, uint){ uint[] memory temperatures = fermentations[_fermentation_id].temperatures; uint[] memory humidities = fermentations[_fermentation_id].humidities; uint temperatures_count = temperatures.length; uint humidities_count = humidities.length; assert(temperatures_count > 0 && humidities_count > 0); return (temperatures[temperatures_count-1], humidities[humidities_count-1]); } /** * Nome da Função: getTemperatures * * Autor: Levy Santiago * * Descrição: Retorna a lista de temperaturas capturadas (temperatures) * * Escopo: public * * Parâmetros: * null * * Retorno: * - uint[] temperatures: A lista de temperaturas capturadas **/ function getTemperatures(uint _fermentation_id) public view returns(uint []){ return fermentations[_fermentation_id].temperatures; } /** * Nome da Função: getHumidities * * Autor: Levy Santiago * * Descrição: Retorna a lista de umidades capturadas (humidities) * * Escopo: public * * Parâmetros: * null * * Retorno: * - uint[] humidities: A lista de umidades capturadas **/ function getHumidities(uint _fermentation_id) public view returns(uint []){ return fermentations[_fermentation_id].humidities; } }
* Nome da Função: setHumidity Autor: Levy Santiago Descrição: Recebe um novo valor de umidade, adiciona na lista de umidades capturadas e verifica se o valor recebido ultrapassa superiormente ou inferiormente o mínimo e máximo. Escopo: public Parâmetros: - _humidity: A nova leitura de umidade obtida. Retorno: null Eventos: Pode gerar os eventos "humidityOverflow" ou "humidityUnderflow" - humidityOverflow: É gerado quando "_humidity" ultrapassa superiormente "max_humidity"; - humidityUnderflow: É gerado quando "_humidity" ultrapassa inferiormente "min_humidity". Restrição: - onlyOwnerOrManager: Somente o dono ou gerenciador do contrato pode realizar esta operação/
function setHumidity(uint _humidity, uint _fermentation_id) public onlyOwnerOrManager(msg.sender) { uint[] storage humidities = fermentations[_fermentation_id].humidities; humidities.push(_humidity); if(_humidity >= max_humidity){ emit humidityOverflow(_humidity, max_humidity); } else if(_humidity <= min_humidity){ emit humidityUnderflow(_humidity, min_humidity); } }
6,488,768
[ 1, 50, 1742, 5248, 478, 318, 132, 105, 132, 101, 83, 30, 444, 44, 379, 24237, 432, 3408, 30, 3519, 29139, 348, 970, 8852, 83, 463, 1052, 132, 105, 132, 101, 83, 30, 9797, 2196, 9570, 1158, 12307, 23325, 443, 9570, 30681, 16, 1261, 335, 285, 69, 9583, 17822, 443, 9570, 350, 16601, 9656, 295, 361, 345, 425, 1924, 1507, 69, 695, 320, 23325, 2637, 19773, 83, 7493, 27170, 428, 69, 2240, 9659, 475, 73, 16694, 12455, 9659, 475, 73, 320, 312, 132, 260, 82, 381, 83, 425, 312, 132, 99, 92, 381, 83, 18, 512, 1017, 556, 83, 30, 1071, 2280, 132, 100, 10578, 6973, 30, 300, 389, 76, 379, 24237, 30, 432, 1158, 15304, 884, 305, 21401, 443, 9570, 30681, 3768, 18081, 69, 18, 17100, 280, 2135, 30, 446, 2587, 538, 30, 453, 390, 314, 264, 297, 1140, 871, 538, 315, 76, 379, 24237, 15526, 6, 16694, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 444, 44, 379, 24237, 12, 11890, 389, 76, 379, 24237, 16, 2254, 389, 586, 475, 367, 67, 350, 13, 1071, 1338, 5541, 1162, 1318, 12, 3576, 18, 15330, 13, 288, 203, 3639, 2254, 8526, 2502, 29303, 350, 1961, 273, 284, 264, 475, 1012, 63, 67, 586, 475, 367, 67, 350, 8009, 76, 379, 350, 1961, 31, 203, 3639, 29303, 350, 1961, 18, 6206, 24899, 76, 379, 24237, 1769, 203, 3639, 309, 24899, 76, 379, 24237, 1545, 943, 67, 76, 379, 24237, 15329, 203, 5411, 3626, 29303, 24237, 15526, 24899, 76, 379, 24237, 16, 943, 67, 76, 379, 24237, 1769, 203, 3639, 289, 203, 3639, 469, 309, 24899, 76, 379, 24237, 1648, 1131, 67, 76, 379, 24237, 15329, 203, 5411, 3626, 29303, 24237, 14655, 2426, 24899, 76, 379, 24237, 16, 1131, 67, 76, 379, 24237, 1769, 203, 3639, 289, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x2E0e58Ec25cD275Ce7C24A7F7876057F09A31461/sources/src/WETHGateway.sol
@inheritdoc IWETHGateway
function refreshAllowance(address zeroliquid) external onlyOwner { WETH.approve(zeroliquid, type(uint256).max); }
2,864,638
[ 1, 36, 10093, 467, 59, 1584, 44, 5197, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4460, 7009, 1359, 12, 2867, 24910, 355, 18988, 350, 13, 3903, 1338, 5541, 288, 203, 3639, 678, 1584, 44, 18, 12908, 537, 12, 24355, 355, 18988, 350, 16, 618, 12, 11890, 5034, 2934, 1896, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT /** * @title Cover FlashBorrower * @author alan */ // File contracts/interfaces/IProtocol.sol pragma solidity ^0.8.0; interface IProtocol { function coverMap(address _collateral, uint48 _expirationTimestamp) external view returns (address); function addCover(address _collateral, uint48 _timestamp, uint256 _amount) external returns (bool); } // File contracts/interfaces/IERC3156FlashBorrower.sol pragma solidity ^0.8.0; interface IERC3156FlashBorrower { /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external returns (bytes32); } // File contracts/ERC20/IERC20.sol pragma solidity ^0.8.0; /** * @title Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; } // File contracts/interfaces/ICover.sol pragma solidity ^0.8.0; interface ICover { function claimCovToken() external view returns (IERC20); function noclaimCovToken() external view returns (IERC20); function redeemCollateral(uint256 _amount) external; } // File contracts/interfaces/IBPool.sol pragma solidity ^0.8.0; interface IBPool { function swapExactAmountIn( address tokenIn, uint256 tokenAmountIn, address tokenOut, uint256 minAmountOut, uint256 maxPrice ) external returns (uint256 tokenAmountOut, uint256 spotPriceAfter); function swapExactAmountOut( address tokenIn, uint256 maxAmountIn, address tokenOut, uint256 tokenAmountOut, uint256 maxPrice ) external returns (uint256 tokenAmountIn, uint256 spotPriceAfter); function calcOutGivenIn( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountIn, uint256 swapFee ) external view returns (uint256 tokenAmountOut); function calcInGivenOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountOut, uint256 swapFee ) external view returns (uint256 tokenAmountIn); function getNormalizedWeight(address token) external view returns (uint256); function getBalance(address token) external view returns (uint256); function getSwapFee() external view returns (uint256); } // File contracts/interfaces/IFlashBorrower.sol pragma solidity ^0.8.0; interface IFlashBorrower is IERC3156FlashBorrower { /// @notice emit when a new flashlender is set event NewFlashLender(address flashLender); struct FlashLoanData { bool isBuy; IBPool bpool; IProtocol protocol; address caller; address collateral; uint48 timestamp; uint256 amount; uint256 limit; } struct Permit { uint256 nonce; uint256 expiry; bool allowed; uint8 v; bytes32 r; bytes32 s; } function flashBuyClaim( IBPool _bpool, IProtocol _protocol, address _collateral, uint48 _timestamp, uint256 _amountToBuy, uint256 _maxAmountToSpend ) external; function flashBuyClaimPermit( IBPool _bpool, IProtocol _protocol, address _collateral, uint48 _timestamp, uint256 _amountToBuy, uint256 _maxAmountToSpend, Permit calldata permit ) external; function flashSellClaim( IBPool _bpool, IProtocol _protocol, address _collateral, uint48 _timestamp, uint256 _amountToSell, uint256 _minAmountToReturn ) external; function getBuyClaimCost( IBPool _bpool, IProtocol _protocol, address _collateral, uint48 _timestamp, uint256 _amountToBuy ) external view returns (uint256 totalCost); function getSellClaimReturn( IBPool _bpool, IProtocol _protocol, address _collateral, uint48 _timestamp, uint256 _amountToSell, uint256 _redeemFeeNumerator ) external view returns (uint256 totalReturn); function setFlashLender(address _flashLender) external; function collect(IERC20 _token) external; } // File contracts/interfaces/IERC3156FlashLender.sol pragma solidity ^0.8.0; interface IERC3156FlashLender { /** * @dev The amount of currency available to be lended. * @param token The loan currency. * @return The amount of `token` that can be borrowed. */ function maxFlashLoan( address token ) external view returns (uint256); /** * @dev The fee to be charged for a given loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @return The amount of `token` to be charged for the loan, on top of the returned principal. */ function flashFee( address token, uint256 amount ) external view returns (uint256); /** * @dev Initiate a flash loan. * @param receiver The receiver of the tokens in the loan, and the receiver of the callback. * @param token The loan currency. * @param amount The amount of tokens lent. * @param data Arbitrary data structure, intended to contain user-defined parameters. */ function flashLoan( address receiver, address token, uint256 amount, bytes calldata data ) external; } // File contracts/ERC20/IYERC20.sol pragma solidity ^0.8.0; interface IYERC20 is IERC20 { function deposit(uint256 _amount) external; function withdraw(uint256 _shares) external; function getPricePerFullShare() external view returns (uint256); } // File contracts/utils/Address.sol pragma solidity ^0.8.0; library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File contracts/ERC20/SafeERC20.sol pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/utils/Context.sol pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File contracts/utils/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File contracts/CoverFlashBorrower.sol pragma solidity ^0.8.0; contract CoverFlashBorrower is Ownable, IFlashBorrower { using SafeERC20 for IERC20; IERC3156FlashLender public flashLender; IERC20 public immutable dai; IYERC20 public immutable ydai; modifier onlySupportedCollaterals(address _collateral) { require(_collateral == address(dai) || _collateral == address(ydai), "only supports DAI and yDAI collaterals"); _; } constructor (IERC3156FlashLender _flashLender, IERC20 _dai, IYERC20 _ydai) { flashLender = _flashLender; dai = _dai; ydai = _ydai; } /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external override returns(bytes32) { require(msg.sender == address(flashLender), "CoverFlashBorrower: Untrusted lender"); require(initiator == address(this), "CoverFlashBorrower: Untrusted loan initiator"); require(token == address(dai), "!dai"); // For v1, can only flashloan DAI uint256 amountOwed = amount + fee; FlashLoanData memory flashLoanData = abi.decode(data, (FlashLoanData)); if (flashLoanData.isBuy) { _onFlashLoanBuyClaim(flashLoanData, amount, amountOwed); } else { _onFlashLoanSellClaim(flashLoanData, amount, amountOwed); } return keccak256("ERC3156FlashBorrower.onFlashLoan"); } /** * @dev Flash loan the amount of collateral needed to mint `_amountCovTokens` covTokens * - If collateral is yDAI, `_amountCovTokens` is scaled by current price of yDAI to flash borrow enough DAI */ function flashBuyClaim( IBPool _bpool, IProtocol _protocol, address _collateral, uint48 _timestamp, uint256 _amountToBuy, uint256 _maxAmountToSpend ) public override onlySupportedCollaterals(_collateral) { bytes memory data = abi.encode(FlashLoanData({ isBuy: true, bpool: _bpool, protocol: _protocol, caller: msg.sender, collateral: _collateral, timestamp: _timestamp, amount: _amountToBuy, limit: _maxAmountToSpend })); uint256 amountDaiNeeded; if (_collateral == address(dai)) { amountDaiNeeded = _amountToBuy; } else if (_collateral == address(ydai)) { amountDaiNeeded = _amountToBuy * ydai.getPricePerFullShare() / 1e18; } require(amountDaiNeeded <= flashLender.maxFlashLoan(address(dai)), "_amount > lender reserves"); uint256 _allowance = dai.allowance(address(this), address(flashLender)); uint256 _fee = flashLender.flashFee(address(dai), amountDaiNeeded); uint256 _repayment = amountDaiNeeded + _fee; _approve(dai, address(flashLender), _allowance + _repayment); flashLender.flashLoan(address(this), address(dai), amountDaiNeeded, data); } function flashBuyClaimPermit( IBPool _bpool, IProtocol _protocol, address _collateral, uint48 _timestamp, uint256 _amountToBuy, uint256 _maxAmountToSpend, Permit calldata permit ) external override { require(_collateral == address(dai), "only DAI permit is supported"); IERC20(_collateral).permit(msg.sender, address(this), permit.nonce, permit.expiry, permit.allowed, permit.v, permit.r, permit.s); flashBuyClaim(_bpool, _protocol, _collateral, _timestamp, _amountToBuy, _maxAmountToSpend); } /** * @dev Flash loan the amount of DAI needed to buy enough NOCLAIM to redeem with CLAIM tokens */ function flashSellClaim( IBPool _bpool, IProtocol _protocol, address _collateral, uint48 _timestamp, uint256 _amountToSell, uint256 _minAmountToReturn ) external override onlySupportedCollaterals(_collateral) { bytes memory data = abi.encode(FlashLoanData({ isBuy: false, bpool: _bpool, protocol: _protocol, caller: msg.sender, collateral: _collateral, timestamp: _timestamp, amount: _amountToSell, limit: _minAmountToReturn })); (, IERC20 noclaimToken) = _getCovTokenAddresses(_protocol, _collateral, _timestamp); uint256 amountDaiNeeded = _calcInGivenOut(_bpool, address(dai), address(noclaimToken), _amountToSell); require(amountDaiNeeded <= flashLender.maxFlashLoan(address(dai)), "_amount > lender reserves"); uint256 _allowance = dai.allowance(address(this), address(flashLender)); uint256 _fee = flashLender.flashFee(address(dai), amountDaiNeeded); uint256 _repayment = amountDaiNeeded + _fee; _approve(dai, address(flashLender), _allowance + _repayment); flashLender.flashLoan(address(this), address(dai), amountDaiNeeded, data); } function setFlashLender(address _flashLender) external override onlyOwner { require(_flashLender != address(0), "_flashLender is 0"); flashLender = IERC3156FlashLender(_flashLender); emit NewFlashLender(_flashLender); } /// @notice Tokens that are accidentally sent to this contract can be recovered function collect(IERC20 _token) external override onlyOwner { uint256 balance = _token.balanceOf(address(this)); require(balance > 0, "_token balance is 0"); _token.safeTransfer(msg.sender, balance); } function getBuyClaimCost( IBPool _bpool, IProtocol _protocol, address _collateral, uint48 _timestamp, uint256 _amountToBuy ) external override view onlySupportedCollaterals(_collateral) returns (uint256 totalCost) { uint256 amountDaiNeeded = _amountToBuy; if (_collateral == address(ydai)) { amountDaiNeeded = amountDaiNeeded * ydai.getPricePerFullShare() / 1e18; } uint256 flashFee = flashLender.flashFee(address(dai), amountDaiNeeded); uint256 daiReceivedFromSwap; { (, IERC20 noclaimToken) = _getCovTokenAddresses(_protocol, _collateral, _timestamp); daiReceivedFromSwap = _calcOutGivenIn(_bpool, address(noclaimToken), _amountToBuy, address(dai)); } if (amountDaiNeeded + flashFee < daiReceivedFromSwap) { totalCost = 0; } else { totalCost = amountDaiNeeded + flashFee - daiReceivedFromSwap; } } /// @notice redeem fee denominator is assumed to be 10000 function getSellClaimReturn( IBPool _bpool, IProtocol _protocol, address _collateral, uint48 _timestamp, uint256 _amountToSell, uint256 _redeemFeeNumerator ) external override view onlySupportedCollaterals(_collateral) returns (uint256 totalReturn) { require(_redeemFeeNumerator <= 10000, "fee > 10000"); (, IERC20 noclaimToken) = _getCovTokenAddresses(_protocol, _collateral, _timestamp); uint256 amountDaiNeeded = _calcInGivenOut(_bpool, address(dai), address(noclaimToken), _amountToSell); uint256 flashFee = flashLender.flashFee(address(dai), amountDaiNeeded); uint256 daiReceivedFromRedeem; if (_collateral == address(dai)) { daiReceivedFromRedeem = _amountToSell; } else if (_collateral == address(ydai)) { // Adjust for price of yDAI daiReceivedFromRedeem = _amountToSell * ydai.getPricePerFullShare() / 1e18; } // Adjust for redemption fee daiReceivedFromRedeem = daiReceivedFromRedeem * (10000 - _redeemFeeNumerator) / 10000; if (daiReceivedFromRedeem < amountDaiNeeded + flashFee) { totalReturn = 0; } else { totalReturn = daiReceivedFromRedeem - amountDaiNeeded - flashFee; } } /** * - If collateral is yDAI, wrap borrowed DAI * - Deposit collateral for covTokens * - Sell NOCLAIM tokens on Balancer to receive DAI * - Calculate amount user needs to pay to repay loan + slippage + fee * - Send minted CLAIM tokens to user */ function _onFlashLoanBuyClaim(FlashLoanData memory data, uint256 amount, uint256 amountOwed) internal { uint256 mintAmount; // Wrap DAI to yDAI if necessary if (data.collateral == address(dai)) { mintAmount = amount; _approve(dai, address(data.protocol), mintAmount); } else if (data.collateral == address(ydai)) { _approve(dai, address(ydai), amount); uint256 ydaiBalBefore = ydai.balanceOf(address(this)); ydai.deposit(amount); mintAmount = ydai.balanceOf(address(this)) - ydaiBalBefore; _approve(ydai, address(data.protocol), mintAmount); } // Mint claim and NOCLAIM tokens using collateral require(mintAmount > 0, "mintAmount is 0"); data.protocol.addCover(data.collateral, data.timestamp, mintAmount); (IERC20 claimToken, IERC20 noclaimToken) = _getCovTokenAddresses( data.protocol, data.collateral, data.timestamp ); // Swap exact number of NOCLAIM tokens for DAI on Balancer _approve(noclaimToken, address(data.bpool), mintAmount); (uint256 daiReceived, ) = data.bpool.swapExactAmountIn( address(noclaimToken), mintAmount, address(dai), 0, type(uint256).max ); require(daiReceived > 0, "received 0 DAI from swap"); // Make sure cost is not greater than limit require(amountOwed <= data.limit + daiReceived, "cost exceeds limit"); // User pays for slippage + flash loan fee if (amountOwed > daiReceived) { dai.safeTransferFrom(data.caller, address(this), amountOwed - daiReceived); } // Transfer claim tokens to caller claimToken.safeTransfer(data.caller, mintAmount); } /** * - Sell DAI for NOCLAIM tokens * - Transfer CLAIM tokens from user to this contract * - Redeem CLAIM and NOCLAIM tokens for collateral * - If collateral is yDAI, unwrap to DAI * - Calculate amount user needs to repay loan + slippage + fee * - Send leftover DAI to user */ function _onFlashLoanSellClaim(FlashLoanData memory data, uint256 amount, uint256 amountOwed) internal { uint256 daiAvailable = amount; _approve(dai, address(data.bpool), amount); (IERC20 claimToken, IERC20 noclaimToken) = _getCovTokenAddresses( data.protocol, data.collateral, data.timestamp ); // Swap DAI for exact number of NOCLAIM tokens (uint256 daiSpent, ) = data.bpool.swapExactAmountOut( address(dai), amount, address(noclaimToken), data.amount, type(uint256).max ); daiAvailable = daiAvailable - daiSpent; // Need an equal number of CLAIM and NOCLAIM tokens claimToken.safeTransferFrom(data.caller, address(this), data.amount); // Redeem CLAIM and NOCLAIM tokens for collateral uint256 collateralBalBefore = IERC20(data.collateral).balanceOf(address(this)); address cover = data.protocol.coverMap(data.collateral, data.timestamp); ICover(cover).redeemCollateral(data.amount); uint256 collateralReceived = IERC20(data.collateral).balanceOf(address(this)) - collateralBalBefore; // Unwrap yDAI to DAI if necessary if (data.collateral == address(dai)) { daiAvailable = daiAvailable + collateralReceived; } else if (data.collateral == address(ydai)) { _approve(ydai, address(ydai), collateralReceived); uint256 daiBalBefore = dai.balanceOf(address(this)); ydai.withdraw(collateralReceived); uint256 daiReceived = dai.balanceOf(address(this)) - daiBalBefore; daiAvailable = daiAvailable + daiReceived; } // Make sure return is not less than limit require(daiAvailable >= data.limit + amountOwed, "returns are less than limit"); // Transfer leftover DAI to caller if (daiAvailable > amountOwed) { dai.safeTransfer(data.caller, daiAvailable - amountOwed); } } function _calcInGivenOut(IBPool _bpool, address _tokenIn, address _tokenOut, uint256 _tokenAmountOut) internal view returns (uint256 tokenAmountIn) { uint256 tokenBalanceIn = _bpool.getBalance(_tokenIn); uint256 tokenWeightIn = _bpool.getNormalizedWeight(_tokenIn); uint256 tokenBalanceOut = _bpool.getBalance(_tokenOut); uint256 tokenWeightOut = _bpool.getNormalizedWeight(_tokenOut); uint256 swapFee = _bpool.getSwapFee(); tokenAmountIn = _bpool.calcInGivenOut( tokenBalanceIn, tokenWeightIn, tokenBalanceOut, tokenWeightOut, _tokenAmountOut, swapFee ); } function _calcOutGivenIn(IBPool _bpool, address _tokenIn, uint256 _tokenAmountIn, address _tokenOut) internal view returns (uint256 tokenAmountOut) { uint256 tokenBalanceIn = _bpool.getBalance(_tokenIn); uint256 tokenWeightIn = _bpool.getNormalizedWeight(_tokenIn); uint256 tokenBalanceOut = _bpool.getBalance(_tokenOut); uint256 tokenWeightOut = _bpool.getNormalizedWeight(_tokenOut); uint256 swapFee = _bpool.getSwapFee(); tokenAmountOut = _bpool.calcOutGivenIn( tokenBalanceIn, tokenWeightIn, tokenBalanceOut, tokenWeightOut, _tokenAmountIn, swapFee ); } function _getCovTokenAddresses( IProtocol _protocol, address _collateral, uint48 _timestamp ) internal view returns (IERC20 claimToken, IERC20 noclaimToken) { address cover = _protocol.coverMap(_collateral, _timestamp); claimToken = ICover(cover).claimCovToken(); noclaimToken = ICover(cover).noclaimCovToken(); } function _approve(IERC20 _token, address _spender, uint256 _amount) internal { if (_token.allowance(address(this), _spender) < _amount) { _token.safeApprove(_spender, type(uint256).max); } } }
@notice emit when a new flashlender is set
struct FlashLoanData { bool isBuy; IBPool bpool; IProtocol protocol; address caller; address collateral; uint48 timestamp; uint256 amount; uint256 limit; }
331,333
[ 1, 18356, 1347, 279, 394, 9563, 80, 2345, 353, 444, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 15014, 1504, 304, 751, 288, 203, 3639, 1426, 27057, 9835, 31, 203, 3639, 23450, 2864, 324, 6011, 31, 203, 3639, 467, 5752, 1771, 31, 203, 3639, 1758, 4894, 31, 203, 3639, 1758, 4508, 2045, 287, 31, 203, 3639, 2254, 8875, 2858, 31, 203, 3639, 2254, 5034, 3844, 31, 203, 3639, 2254, 5034, 1800, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-02-09 */ // SPDX-License-Identifier: MIT pragma solidity 0.8.11; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IDexPair { function sync() external; } 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. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string public _name; string public _symbol; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } function _createInitialSupply(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() external virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) external virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IDexRouter { function factory() external pure returns (address); function WETH() external pure returns (address); function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); } interface IDexFactory { function createPair(address tokenA, address tokenB) external returns (address pair); } contract BlazeInu is ERC20, Ownable { IDexRouter public dexRouter; address public lpPair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 private blockPenalty; uint256 public tradingActiveBlock = 0; // 0 means trading is not active uint256 public maxTxnAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public amountForAutoBuyBack = 0.2 ether; bool public autoBuyBackEnabled = true; uint256 public autoBuyBackFrequency = 3600 seconds; uint256 public lastAutoBuyBackTime; uint256 public percentForLPBurn = 100; // 100 = 1% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 1 hours; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferBlock; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyBuyBackFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellBuyBackFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForBuyBack; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedmaxTxnAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event MarketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event DevWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(uint256 amount); event ManualNukeLP(uint256 amount); event BuyBackTriggered(uint256 amount); event OwnerForcedSwapBack(uint256 timestamp); constructor() ERC20("", "") payable { uint256 _buyMarketingFee = 3; uint256 _buyLiquidityFee = 3; uint256 _buyBuyBackFee = 1; uint256 _buyDevFee = 1; uint256 _sellMarketingFee = 10; uint256 _sellLiquidityFee = 14; uint256 _sellBuyBackFee = 4; uint256 _sellDevFee = 2; uint256 totalSupply = 10 * 1e12 * 1e18; maxTxnAmount = totalSupply * 5 / 1000; maxWallet = totalSupply * 1 / 100; // 1% maxWallet swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap amount buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyBuyBackFee = _buyBuyBackFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBuyBackFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellBuyBackFee = _sellBuyBackFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBuyBackFee + sellDevFee; marketingWallet = address(0xb24d88c9671A505fDC7126EC42D3bB651bea1886); // set as marketing wallet devWallet = address(msg.sender); // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(marketingWallet, true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromFees(0x67469f99D1db2D2EE86589e8Bff95a4a91e28B48, true); // future owner wallet excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(marketingWallet, true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromMaxTransaction(0x67469f99D1db2D2EE86589e8Bff95a4a91e28B48, true); /* _createInitialSupply is an internal function that is only called here, and CANNOT be called ever again */ _createInitialSupply(0x67469f99D1db2D2EE86589e8Bff95a4a91e28B48, totalSupply*20/100); _createInitialSupply(address(this), totalSupply*80/100); } receive() external payable { } // remove limits after token is stable function removeLimits() external onlyOwner { limitsInEffect = false; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner { transferDelayEnabled = false; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxTxnAmount lower than 0.5%"); maxTxnAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 100)/1e18, "Cannot set maxWallet lower than 1%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedmaxTxnAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _buyBackFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyBuyBackFee = _buyBackFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBuyBackFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _buyBackFee, uint256 _devFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellBuyBackFee = _buyBackFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBuyBackFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != lpPair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit MarketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit DevWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping && !_isExcludedFromFees[to] && !_isExcludedFromFees[from] ){ // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferBlock[tx.origin] < block.number - 1 && _holderLastTransferBlock[to] < block.number - 1, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferBlock[tx.origin] = block.number; _holderLastTransferBlock[to] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedmaxTxnAmount[to]) { require(amount <= maxTxnAmount, "Buy transfer amount exceeds the maxTxnAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedmaxTxnAmount[from]) { require(amount <= maxTxnAmount, "Sell transfer amount exceeds the maxTxnAmount."); } else if (!_isExcludedmaxTxnAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } if(!swapping && automatedMarketMakerPairs[to] && autoBuyBackEnabled && block.timestamp >= lastAutoBuyBackTime + autoBuyBackFrequency && !_isExcludedFromFees[from] && address(this).balance >= amountForAutoBuyBack){ autoBuyBack(amountForAutoBuyBack); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // bot/sniper penalty. Tokens get transferred to marketing wallet to allow potential refund. if(isPenaltyActive() && automatedMarketMakerPairs[from]){ fees = amount * 99 / 100; tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForBuyBack += fees * sellBuyBackFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; } // on sell else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount * sellTotalFees / 100; tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForBuyBack += fees * sellBuyBackFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 100; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForBuyBack += fees * buyBuyBackFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = dexRouter.WETH(); _approve(address(this), address(dexRouter), tokenAmount); // make the swap dexRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(dexRouter), tokenAmount); // add the liquidity dexRouter.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForBuyBack + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance - liquidityTokens; uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance - initialETHBalance; uint256 ethForMarketing = ethBalance * tokensForMarketing / (totalTokensToSwap - (tokensForLiquidity/2)); uint256 ethForBuyBack = ethBalance * tokensForBuyBack / (totalTokensToSwap - (tokensForLiquidity/2)); uint256 ethForDev = ethBalance * tokensForDev / (totalTokensToSwap - (tokensForLiquidity/2)); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForBuyBack - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForBuyBack = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); (success,) = address(marketingWallet).call{value: ethForMarketing}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } // keep leftover ETH for buyback } // force Swap back if slippage issues. function forceSwapBack() external onlyOwner { require(balanceOf(address(this)) >= swapTokensAtAmount, "Can only swap when token amount is at or higher than restriction"); swapping = true; swapBack(); swapping = false; emit OwnerForcedSwapBack(block.timestamp); } // useful for buybacks or to reclaim any ETH on the contract in a way that helps holders. function buyBackTokens(uint256 amountInWei) external onlyOwner { require(amountInWei <= 10 ether, "May not buy more than 10 ETH in a single buy to reduce sandwich attacks"); address[] memory path = new address[](2); path[0] = dexRouter.WETH(); path[1] = address(this); // make the swap dexRouter.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amountInWei}( 0, // accept any amount of Ethereum path, address(0xdead), block.timestamp ); emit BuyBackTriggered(amountInWei); } function setAutoBuyBackSettings(uint256 _frequencyInSeconds, uint256 _buyBackAmount, bool _autoBuyBackEnabled) external onlyOwner { require(_frequencyInSeconds >= 30, "cannot set buyback more often than every 30 seconds"); require(_buyBackAmount <= 2 ether && _buyBackAmount >= 0.05 ether, "Must set auto buyback amount between .05 and 2 ETH"); autoBuyBackFrequency = _frequencyInSeconds; amountForAutoBuyBack = _buyBackAmount; autoBuyBackEnabled = _autoBuyBackEnabled; } function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 1% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } // automated buyback function autoBuyBack(uint256 amountInWei) internal { lastAutoBuyBackTime = block.timestamp; address[] memory path = new address[](2); path[0] = dexRouter.WETH(); path[1] = address(this); // make the swap dexRouter.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amountInWei}( 0, // accept any amount of Ethereum path, address(0xdead), block.timestamp ); emit BuyBackTriggered(amountInWei); } function isPenaltyActive() public view returns (bool) { return tradingActiveBlock >= block.number - blockPenalty; } function autoBurnLiquidityPairTokens() internal{ lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(lpPair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance * percentForLPBurn / 10000; if (amountToBurn > 0){ super._transfer(lpPair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IDexPair pair = IDexPair(lpPair); pair.sync(); emit AutoNukeLP(amountToBurn); } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner { require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(lpPair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance * percent / 10000; if (amountToBurn > 0){ super._transfer(lpPair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IDexPair pair = IDexPair(lpPair); pair.sync(); emit ManualNukeLP(amountToBurn); } function launch(uint256 _blockPenalty) external onlyOwner { require(!tradingActive, "Trading is already active, cannot relaunch."); blockPenalty = _blockPenalty; //update name/ticker _name = "Blaze Inu"; _symbol = "BLAZE"; //standard enable trading tradingActive = true; swapEnabled = true; tradingActiveBlock = block.number; lastLpBurnTime = block.timestamp; // initialize router IDexRouter _dexRouter = IDexRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); dexRouter = _dexRouter; // create pair lpPair = IDexFactory(_dexRouter.factory()).createPair(address(this), _dexRouter.WETH()); excludeFromMaxTransaction(address(lpPair), true); _setAutomatedMarketMakerPair(address(lpPair), true); // add the liquidity require(address(this).balance > 0, "Must have ETH on contract to launch"); require(balanceOf(address(this)) > 0, "Must have Tokens on contract to launch"); _approve(address(this), address(dexRouter), balanceOf(address(this))); dexRouter.addLiquidityETH{value: address(this).balance}( address(this), balanceOf(address(this)), 0, // slippage is unavoidable 0, // slippage is unavoidable 0x67469f99D1db2D2EE86589e8Bff95a4a91e28B48, block.timestamp ); } // withdraw ETH if stuck before launch function withdrawStuckETH() external onlyOwner { require(!tradingActive, "Can only withdraw if trading hasn't started"); bool success; (success,) = address(msg.sender).call{value: address(this).balance}(""); } }
exclude from paying fees or having max transaction amount
constructor() ERC20("", "") payable { uint256 _buyMarketingFee = 3; uint256 _buyLiquidityFee = 3; uint256 _buyBuyBackFee = 1; uint256 _buyDevFee = 1; uint256 _sellMarketingFee = 10; uint256 _sellLiquidityFee = 14; uint256 _sellBuyBackFee = 4; uint256 _sellDevFee = 2; uint256 totalSupply = 10 * 1e12 * 1e18; maxTxnAmount = totalSupply * 5 / 1000; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyBuyBackFee = _buyBuyBackFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBuyBackFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellBuyBackFee = _sellBuyBackFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBuyBackFee + sellDevFee; devWallet = address(msg.sender); excludeFromFees(owner(), true); excludeFromFees(marketingWallet, true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(marketingWallet, true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromMaxTransaction(0x67469f99D1db2D2EE86589e8Bff95a4a91e28B48, true); _createInitialSupply is an internal function that is only called here, and CANNOT be called ever again _createInitialSupply(0x67469f99D1db2D2EE86589e8Bff95a4a91e28B48, totalSupply*20/100); _createInitialSupply(address(this), totalSupply*80/100);
10,981,018
[ 1, 10157, 628, 8843, 310, 1656, 281, 578, 7999, 943, 2492, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 4232, 39, 3462, 2932, 3113, 1408, 13, 8843, 429, 288, 203, 1171, 203, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 890, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 890, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 38, 9835, 2711, 14667, 273, 404, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 8870, 14667, 273, 404, 31, 203, 203, 3639, 2254, 5034, 389, 87, 1165, 3882, 21747, 14667, 273, 1728, 31, 203, 3639, 2254, 5034, 389, 87, 1165, 48, 18988, 24237, 14667, 273, 5045, 31, 203, 3639, 2254, 5034, 389, 87, 1165, 38, 9835, 2711, 14667, 273, 1059, 31, 203, 3639, 2254, 5034, 389, 87, 1165, 8870, 14667, 273, 576, 31, 203, 540, 203, 3639, 2254, 5034, 2078, 3088, 1283, 273, 1728, 380, 404, 73, 2138, 380, 404, 73, 2643, 31, 203, 540, 203, 3639, 943, 13789, 6275, 273, 2078, 3088, 1283, 380, 1381, 342, 4336, 31, 203, 203, 3639, 30143, 3882, 21747, 14667, 273, 389, 70, 9835, 3882, 21747, 14667, 31, 203, 3639, 30143, 48, 18988, 24237, 14667, 273, 389, 70, 9835, 48, 18988, 24237, 14667, 31, 203, 3639, 30143, 38, 9835, 2711, 14667, 273, 389, 70, 9835, 38, 9835, 2711, 14667, 31, 203, 3639, 30143, 8870, 14667, 273, 389, 70, 9835, 8870, 14667, 31, 203, 3639, 30143, 5269, 2954, 281, 273, 30143, 3882, 21747, 14667, 397, 30143, 48, 18988, 24237, 14667, 397, 30143, 38, 9835, 2711, 14667, 397, 30143, 8870, 14667, 31, 203, 540, 203, 3639, 357, 80, 3882, 21747, 14667, 2 ]
pragma solidity ^0.4.19; interface ERC20 { function name() public constant returns (string _name); function symbol() public constant returns (string _symbol); function decimals() public constant returns (uint8 _decimals); function totalSupply() public constant returns (uint _totalSupply); function balanceOf(address _owner) public constant returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint remaining); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } interface CrowdsaleRegistry { function isApproved(address _participant) public constant returns (bool); } interface DAC { event Profit(address indexed _from, uint _value, uint _totalProfit, uint _profitInContract); function pay() external payable; } contract BlockLeaseDAC is ERC20, DAC { struct Proposal { uint tokensForSale; uint tokensPerEth; uint bonusPool; uint operatorPool; uint votingBlockCount; uint blockNumber; uint totalVotes; } /** * Operators **/ mapping (address => bool) public operators; /** * ERC20 state **/ mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowances; /** * Customizable variables by proposal **/ uint public tokensForSale; uint public tokensPerEth; uint public bonusPool; uint public operatorPool; uint public votingBlockCount; /** * Token state variables **/ uint public tokensSold; uint public bonusTokensDistributed; uint public operatorTokensDistributed; uint public proposalNumber; Proposal[] public proposals; mapping (uint => mapping (address => uint)) votesPerProposal; bool public lastProposalApplied; /** * Total profit ever received (in wei). **/ uint public totalProfit; /** * Total profit that has yet to be withdrawn (in wei). **/ uint public profitInContract; /** * The last totalProfit value that was paid out to the address. * * Every time an address token balance changes this is updated. **/ mapping (address => uint) lastTotalProfitCredited; /** * Profits available for withdrawal **/ mapping (address => uint) profitBalances; /** * The address of the crowdsale registry contract * * @TODO implement **/ address public crowdsaleRegistry; modifier operatorOnly() { require(operators[msg.sender]); _; } /** * Constructor **/ function BlockLeaseDAC(/* address _crowdsaleRegistry */) public { operators[msg.sender] = true; /* crowdsaleRegistry = _crowdsaleRegistry; */ lastProposalApplied = true; tokensPerEth = totalSupply(); votingBlockCount = 3; proposals.push( Proposal(tokensForSale, tokensPerEth, bonusPool, operatorPool, votingBlockCount, 0, 0) ); balances[0x0] = totalSupply(); _transferFrom(0x0, this, totalSupply()); } /** * Withdraw funds from the contract for use **/ function withdraw(address _target, uint _amount) public operatorOnly { // First throw if amount is greater than balance to avoid sign issues require(this.balance >= _amount); // Then ensure we never overdraw on profit held by token owners require(this.balance - _amount >= profitInContract); _target.transfer(_amount); } /** * Create a proposal to modify certain state variables **/ function createProposal( uint _tokensForSale, uint _tokensPerEth, uint _bonusPool, uint _operatorPool, uint _votingBlockCount ) public operatorOnly { if (!lastProposalApplied) applyProposal(); require(!isVoteActive()); require(_tokensForSale >= tokensForSale); require(_tokensPerEth <= tokensPerEth); require(_bonusPool >= bonusPool); require(_operatorPool >= operatorPool); require(_tokensForSale + _bonusPool + _operatorPool <= totalSupply()); require(_votingBlockCount > 1); proposalNumber++; proposals.push(Proposal(_tokensForSale, _tokensPerEth, _bonusPool, _operatorPool, _votingBlockCount, block.number, 0)); lastProposalApplied = false; } /** * Apply a voted upon proposal **/ function applyProposal() public operatorOnly { require(!isVoteActive()); require(!lastProposalApplied); if (proposals[proposalNumber].totalVotes >= circulatingSupply() / 2) { tokensForSale = proposals[proposalNumber].tokensForSale; tokensPerEth = proposals[proposalNumber].tokensPerEth; bonusPool = proposals[proposalNumber].bonusPool; operatorPool = proposals[proposalNumber].operatorPool; votingBlockCount = proposals[proposalNumber].votingBlockCount; } lastProposalApplied = true; } function isVoteActive() public constant returns (bool) { return ( block.number >= proposals[proposalNumber].blockNumber && block.number < proposals[proposalNumber].blockNumber + votingBlockCount ); } function vote() public { require(isVoteActive()); uint previousVote = votesPerProposal[proposalNumber][msg.sender]; proposals[proposalNumber].totalVotes -= previousVote; votesPerProposal[proposalNumber][msg.sender] = balances[msg.sender]; proposals[proposalNumber].totalVotes += balances[msg.sender]; } function updateVotes(address _from) public { if (!isVoteActive()) return; if (votesPerProposal[proposalNumber][_from] <= balances[_from]) return; votesPerProposal[proposalNumber][_from] = balances[_from]; } /** * Crowdfunding events happen here. **/ function () public payable { /* require(CrowdsaleRegistry(crowdsaleRegistry).isApproved(msg.sender)); */ require(msg.value >= minimumPurchaseWei()); uint tokenCount = tokensPerEth * msg.value / 10**18; require(tokensSold + tokenCount <= tokensForSale); _transferFrom(this, msg.sender, tokenCount); } /** * The minimum purchase is the cost of 1 token, in wei **/ function minimumPurchaseWei() public constant returns (uint) { require(tokensPerEth > 0); return 10**18 / tokensPerEth; } /** * BlockLeaseDAC profits are received here. **/ function pay() external payable { totalProfit += msg.value; profitInContract += msg.value; Profit(msg.sender, msg.value, totalProfit, profitInContract); if (bonusTokensDistributed >= bonusPool) return; uint bonusTokens = tokensPerEth / 100 * msg.value * 10**18; if (bonusTokensDistributed + bonusTokens > bonusPool) { // The edge case of bonus distribution finishing // Pay out the remainder of the bonus pool uint actualBonus = bonusPool - bonusTokensDistributed; _transferFrom(this, msg.sender, actualBonus); bonusTokensDistributed = bonusPool; } else { _transferFrom(this, msg.sender, bonusTokens); bonusTokensDistributed += bonusTokens; } } /** * Update the profit for a given address based on the total sent to the profit * function. * * This should be called prior to every token transfer to ensure that profit * is continuously proportionately settled to token holders. **/ function updateProfitBalance(address _user) public { if (lastTotalProfitCredited[_user] >= totalProfit) return; profitBalances[_user] = latestProfitBalance(_user); lastTotalProfitCredited[_user] = totalProfit; } /** * Retrieve the up to date profit balance without mutating state **/ function latestProfitBalance(address _user) public constant returns (uint) { uint owedBalance = (totalProfit - lastTotalProfitCredited[_user]) * balances[_user] / circulatingSupply(); return profitBalances[_user] + owedBalance; } /** * Helper method to withdraw **/ function withdrawProfit() public returns (bool) { return _withdrawProfit(msg.sender); } /** * Withdraw Ethereum dividends **/ function _withdrawProfit(address _from) public returns (bool) { updateProfitBalance(_from); if (profitBalances[_from] <= 0) return true; uint balance = profitBalances[_from]; profitInContract -= balance; profitBalances[_from] -= balance; _from.transfer(balance); return true; } function circulatingSupply() public constant returns (uint) { return tokensSold + bonusTokensDistributed + operatorTokensDistributed; } /** * ERC20 Implementation **/ function name() public constant returns (string) { return 'BlockLease'; } function symbol() public constant returns (string) { return 'LEASE'; } function decimals() public constant returns (uint8) { return 8; } function totalSupply() public constant returns (uint) { return 1000000000; } function balanceOf(address _owner) public constant returns (uint) { return balances[_owner]; } function transfer(address _to, uint _value) public returns (bool) { return _transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public returns (bool) { require(allowances[_from][msg.sender] >= _value); allowances[_from][msg.sender] -= _value; return _transferFrom(_from, _to, _value); } function _transferFrom(address _from, address _to, uint _value) private returns (bool) { require(balances[_from] >= _value); updateProfitBalance(_from); updateProfitBalance(_to); balances[_from] -= _value; balances[_to] += _value; Transfer(_from, _to, _value); updateVotes(_from); updateVotes(_to); return true; } function approve(address _spender, uint _value) public returns (bool) { allowances[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint) { return allowances[_owner][_spender]; } }
* BlockLeaseDAC profits are received here./ The edge case of bonus distribution finishing Pay out the remainder of the bonus pool
function pay() external payable { totalProfit += msg.value; profitInContract += msg.value; Profit(msg.sender, msg.value, totalProfit, profitInContract); if (bonusTokensDistributed >= bonusPool) return; uint bonusTokens = tokensPerEth / 100 * msg.value * 10**18; if (bonusTokensDistributed + bonusTokens > bonusPool) { uint actualBonus = bonusPool - bonusTokensDistributed; _transferFrom(this, msg.sender, actualBonus); bonusTokensDistributed = bonusPool; _transferFrom(this, msg.sender, bonusTokens); bonusTokensDistributed += bonusTokens; } }
15,860,563
[ 1, 1768, 17746, 40, 2226, 9214, 1282, 854, 5079, 2674, 18, 19, 1021, 3591, 648, 434, 324, 22889, 7006, 4076, 310, 13838, 596, 326, 10022, 434, 326, 324, 22889, 2845, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 8843, 1435, 3903, 8843, 429, 288, 203, 565, 2078, 626, 7216, 1011, 1234, 18, 1132, 31, 203, 565, 450, 7216, 382, 8924, 1011, 1234, 18, 1132, 31, 203, 565, 1186, 7216, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 16, 2078, 626, 7216, 16, 450, 7216, 382, 8924, 1769, 203, 565, 309, 261, 18688, 407, 5157, 1669, 11050, 1545, 324, 22889, 2864, 13, 327, 31, 203, 565, 2254, 324, 22889, 5157, 273, 2430, 2173, 41, 451, 342, 2130, 380, 1234, 18, 1132, 380, 1728, 636, 2643, 31, 203, 565, 309, 261, 18688, 407, 5157, 1669, 11050, 397, 324, 22889, 5157, 405, 324, 22889, 2864, 13, 288, 203, 1377, 2254, 3214, 38, 22889, 273, 324, 22889, 2864, 300, 324, 22889, 5157, 1669, 11050, 31, 203, 1377, 389, 13866, 1265, 12, 2211, 16, 1234, 18, 15330, 16, 3214, 38, 22889, 1769, 203, 1377, 324, 22889, 5157, 1669, 11050, 273, 324, 22889, 2864, 31, 203, 1377, 389, 13866, 1265, 12, 2211, 16, 1234, 18, 15330, 16, 324, 22889, 5157, 1769, 203, 1377, 324, 22889, 5157, 1669, 11050, 1011, 324, 22889, 5157, 31, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xeBaA927c0E9e863b5850cB03154A2bE1648A0320/sources/RegisterDirectMint.sol
* @dev Throws if called by any account but owner or registered minter./
modifier onlyOwnerOrMinter() { require(_owner == msg.sender || _minters[msg.sender] == true, 'Can only be called by owner or minter.'); _; }
2,827,501
[ 1, 21845, 309, 2566, 635, 1281, 2236, 1496, 3410, 578, 4104, 1131, 387, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 9606, 1338, 5541, 1162, 49, 2761, 1435, 288, 203, 565, 2583, 24899, 8443, 422, 1234, 18, 15330, 747, 389, 1154, 5432, 63, 3576, 18, 15330, 65, 422, 638, 16, 296, 2568, 1338, 506, 2566, 635, 3410, 578, 1131, 387, 1093, 1769, 203, 565, 389, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x3321d7Df33C3159c53861c24535Ce790Cd0b866E/sources/browser/ExchangeNFT.sol
Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw() onlyOwner public { uint256 eth_amount = address(this).balance; uint256 erc20_amount = quoteErc20.balanceOf(address(this)); if(eth_amount > 0) msg.sender.transfer(eth_amount); if(erc20_amount > 0) quoteErc20.transfer(msg.sender, erc20_amount); }
3,168,349
[ 1, 1190, 9446, 2887, 5926, 310, 2973, 283, 6397, 18, 7141, 654, 16652, 16068, 20747, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 377, 445, 801, 24530, 1190, 9446, 1435, 1338, 5541, 1071, 288, 203, 540, 2254, 5034, 13750, 67, 8949, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 540, 2254, 5034, 6445, 71, 3462, 67, 8949, 273, 3862, 41, 1310, 3462, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 540, 309, 12, 546, 67, 8949, 405, 374, 13, 203, 1171, 1234, 18, 15330, 18, 13866, 12, 546, 67, 8949, 1769, 203, 540, 309, 12, 12610, 3462, 67, 8949, 405, 374, 13, 203, 1171, 3862, 41, 1310, 3462, 18, 13866, 12, 3576, 18, 15330, 16, 6445, 71, 3462, 67, 8949, 1769, 203, 377, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x4823429dbda52f05f66a2670852b28bd7999e810 //Contract name: KStarCoin //Balance: 0 Ether //Verification Date: 3/2/2018 //Transacion Count: 19 // CODE STARTS HERE pragma solidity ^0.4.18; //>> Reference to https://github.com/Arachnid/solidity-stringutils library strings { struct slice { uint _len; uint _ptr; } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string self) internal pure returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice self) internal pure returns (bool) { return self._len == 0; } } //<< Reference to https://github.com/Arachnid/solidity-stringutils //>> Reference to https://github.com/OpenZeppelin/zeppelin-solidity /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** @title ERC827 interface, an extension of ERC20 token standard Interface of a ERC827 token, following the ERC20 standard with extra methods to transfer value and data and execute calls in transfers and approvals. */ contract ERC827 is ERC20 { function approve( address _spender, uint256 _value, bytes _data ) public returns (bool); function transfer( address _to, uint256 _value, bytes _data ) public returns (bool); function transferFrom( address _from, address _to, uint256 _value, bytes _data ) public returns (bool); } /** @title ERC827, an extension of ERC20 token standard Implementation the ERC827, following the ERC20 standard with extra methods to transfer value and data and execute calls in transfers and approvals. Uses OpenZeppelin StandardToken. */ contract ERC827Token is ERC827, StandardToken { /** @dev Addition to ERC20 token methods. It allows to approve the transfer of value and execute a call with the sent data. Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 @param _spender The address that will spend the funds. @param _value The amount of tokens to be spent. @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function approve(address _spender, uint256 _value, bytes _data) public returns (bool) { require(_spender != address(this)); super.approve(_spender, _value); require(_spender.call(_data)); return true; } /** @dev Addition to ERC20 token methods. Transfer tokens to a specified address and execute a call with the sent data on the same transaction @param _to address The address which you want to transfer to @param _value uint256 the amout of tokens to be transfered @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); super.transfer(_to, _value); require(_to.call(_data)); return true; } /** @dev Addition to ERC20 token methods. Transfer tokens from one address to another and make a contract call on the same transaction @param _from The address which you want to send tokens from @param _to The address which you want to transfer to @param _value The amout of tokens to be transferred @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); super.transferFrom(_from, _to, _value); require(_to.call(_data)); return true; } /** * @dev Addition to StandardToken methods. Increase the amount of tokens that * an owner allowed to a spender and execute a call with the sent data. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function increaseApproval(address _spender, uint _addedValue, bytes _data) public returns (bool) { require(_spender != address(this)); super.increaseApproval(_spender, _addedValue); require(_spender.call(_data)); return true; } /** * @dev Addition to StandardToken methods. Decrease the amount of tokens that * an owner allowed to a spender and execute a call with the sent data. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function decreaseApproval(address _spender, uint _subtractedValue, bytes _data) public returns (bool) { require(_spender != address(this)); super.decreaseApproval(_spender, _subtractedValue); require(_spender.call(_data)); return true; } } //<< Reference to https://github.com/OpenZeppelin/zeppelin-solidity /** * @title MultiOwnable */ contract MultiOwnable { address public root; mapping (address => address) public owners; // owner => parent of owner /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function MultiOwnable() public { root= msg.sender; owners[root]= root; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owners[msg.sender] != 0); _; } /** * @dev Adding new owners */ function newOwner(address _owner) onlyOwner public returns (bool) { require(_owner != 0); owners[_owner]= msg.sender; return true; } /** * @dev Deleting owners */ function deleteOwner(address _owner) onlyOwner public returns (bool) { require(owners[_owner] == msg.sender || (owners[_owner] != 0 && msg.sender == root)); owners[_owner]= 0; return true; } } /** * @title KStarCoinBasic */ contract KStarCoinBasic is ERC827Token, MultiOwnable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; using strings for *; // KStarCoin Distribution // - Crowdsale : 9%(softcap) ~ 45%(hardcap) // - Reserve: 15% // - Team: 10% // - Advisors & Partners: 5% // - Bounty Program + Ecosystem : 25% ~ 61% uint256 public capOfTotalSupply; uint256 public constant INITIAL_SUPPLY= 30e6 * 1 ether; // Reserve(15) + Team(10) + Advisors&Patners(5) uint256 public crowdsaleRaised; uint256 public constant CROWDSALE_HARDCAP= 45e6 * 1 ether; // Crowdsale(Max 45) /** * @dev Function to increase capOfTotalSupply in the next phase of KStarCoin's ecosystem */ function increaseCap(uint256 _addedValue) onlyOwner public returns (bool) { require(_addedValue >= 100e6 * 1 ether); capOfTotalSupply = capOfTotalSupply.add(_addedValue); return true; } /** * @dev Function to check whether the current supply exceeds capOfTotalSupply */ function checkCap(uint256 _amount) public view returns (bool) { return (totalSupply_.add(_amount) <= capOfTotalSupply); } //> for ERC20 function transfer(address _to, uint256 _value) public returns (bool) { require(super.transfer(_to, _value)); KSC_Send(msg.sender, _to, _value, ""); KSC_Receive(_to, msg.sender, _value, ""); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(super.transferFrom(_from, _to, _value)); KSC_SendTo(_from, _to, _value, ""); KSC_ReceiveFrom(_to, _from, _value, ""); return true; } function approve(address _to, uint256 _value) public returns (bool) { require(super.approve(_to, _value)); KSC_Approve(msg.sender, _to, _value, ""); return true; } // additional StandardToken method of zeppelin-solidity function increaseApproval(address _to, uint _addedValue) public returns (bool) { require(super.increaseApproval(_to, _addedValue)); KSC_ApprovalInc(msg.sender, _to, _addedValue, ""); return true; } // additional StandardToken method of zeppelin-solidity function decreaseApproval(address _to, uint _subtractedValue) public returns (bool) { require(super.decreaseApproval(_to, _subtractedValue)); KSC_ApprovalDec(msg.sender, _to, _subtractedValue, ""); return true; } //< //> for ERC827 function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { return transfer(_to, _value, _data, ""); } function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) { return transferFrom(_from, _to, _value, _data, ""); } function approve(address _to, uint256 _value, bytes _data) public returns (bool) { return approve(_to, _value, _data, ""); } // additional StandardToken method of zeppelin-solidity function increaseApproval(address _to, uint _addedValue, bytes _data) public returns (bool) { return increaseApproval(_to, _addedValue, _data, ""); } // additional StandardToken method of zeppelin-solidity function decreaseApproval(address _to, uint _subtractedValue, bytes _data) public returns (bool) { return decreaseApproval(_to, _subtractedValue, _data, ""); } //< //> notation for ERC827 function transfer(address _to, uint256 _value, bytes _data, string _note) public returns (bool) { require(super.transfer(_to, _value, _data)); KSC_Send(msg.sender, _to, _value, _note); KSC_Receive(_to, msg.sender, _value, _note); return true; } function transferFrom(address _from, address _to, uint256 _value, bytes _data, string _note) public returns (bool) { require(super.transferFrom(_from, _to, _value, _data)); KSC_SendTo(_from, _to, _value, _note); KSC_ReceiveFrom(_to, _from, _value, _note); return true; } function approve(address _to, uint256 _value, bytes _data, string _note) public returns (bool) { require(super.approve(_to, _value, _data)); KSC_Approve(msg.sender, _to, _value, _note); return true; } function increaseApproval(address _to, uint _addedValue, bytes _data, string _note) public returns (bool) { require(super.increaseApproval(_to, _addedValue, _data)); KSC_ApprovalInc(msg.sender, _to, _addedValue, _note); return true; } function decreaseApproval(address _to, uint _subtractedValue, bytes _data, string _note) public returns (bool) { require(super.decreaseApproval(_to, _subtractedValue, _data)); KSC_ApprovalDec(msg.sender, _to, _subtractedValue, _note); return true; } //< /** * @dev Function to mint coins * @param _to The address that will receive the minted coins. * @param _amount The amount of coins to mint. * @return A boolean that indicates if the operation was successful. * @dev reference : https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/MintableToken.sol */ function mint(address _to, uint256 _amount) onlyOwner internal returns (bool) { require(_to != address(0)); require(checkCap(_amount)); totalSupply_= totalSupply_.add(_amount); balances[_to]= balances[_to].add(_amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to mint coins * @param _to The address that will receive the minted coins. * @param _amount The amount of coins to mint. * @param _note The notation for ethereum blockchain event log system * @return A boolean that indicates if the operation was successful. * @dev reference : https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/MintableToken.sol */ function mint(address _to, uint256 _amount, string _note) onlyOwner public returns (bool) { require(mint(_to, _amount)); KSC_Mint(_to, msg.sender, _amount, _note); return true; } /** * @dev Burns a specific amount of coins. * @param _to The address that will be burned the coins. * @param _amount The amount of coins to be burned. * @return A boolean that indicates if the operation was successful. * @dev reference : https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/BurnableToken.sol */ function burn(address _to, uint256 _amount) onlyOwner internal returns (bool) { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[_to]= balances[_to].sub(_amount); totalSupply_= totalSupply_.sub(_amount); return true; } /** * @dev Burns a specific amount of coins. * @param _to The address that will be burned the coins. * @param _amount The amount of coins to be burned. * @param _note The notation for ethereum blockchain event log system * @return A boolean that indicates if the operation was successful. * @dev reference : https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/BurnableToken.sol */ function burn(address _to, uint256 _amount, string _note) onlyOwner public returns (bool) { require(burn(_to, _amount)); KSC_Burn(_to, msg.sender, _amount, _note); return true; } // for crowdsale /** * @dev Function which allows users to buy KStarCoin during the crowdsale period * @param _to The address that will receive the coins. * @param _value The amount of coins to sell. * @param _note The notation for ethereum blockchain event log system * @return A boolean that indicates if the operation was successful. */ function sell(address _to, uint256 _value, string _note) onlyOwner public returns (bool) { require(crowdsaleRaised.add(_value) <= CROWDSALE_HARDCAP); require(mint(_to, _value)); crowdsaleRaised= crowdsaleRaised.add(_value); KSC_Buy(_to, msg.sender, _value, _note); return true; } // for buyer with cryptocurrency other than ETH /** * @dev This function is occured when owner mint coins to users as they buy with cryptocurrency other than ETH. * @param _to The address that will receive the coins. * @param _value The amount of coins to mint. * @param _note The notation for ethereum blockchain event log system * @return A boolean that indicates if the operation was successful. */ function mintToOtherCoinBuyer(address _to, uint256 _value, string _note) onlyOwner public returns (bool) { require(mint(_to, _value)); KSC_BuyOtherCoin(_to, msg.sender, _value, _note); return true; } // for bounty program /** * @dev Function to reward influencers with KStarCoin * @param _to The address that will receive the coins. * @param _value The amount of coins to mint. * @param _note The notation for ethereum blockchain event log system * @return A boolean that indicates if the operation was successful. */ function mintToInfluencer(address _to, uint256 _value, string _note) onlyOwner public returns (bool) { require(mint(_to, _value)); KSC_GetAsInfluencer(_to, msg.sender, _value, _note); return true; } // for KSCPoint (KStarLive ecosystem point) /** * @dev Function to exchange KSCPoint to KStarCoin * @param _to The address that will receive the coins. * @param _value The amount of coins to mint. * @param _note The notation for ethereum blockchain event log system * @return A boolean that indicates if the operation was successful. */ function exchangePointToCoin(address _to, uint256 _value, string _note) onlyOwner public returns (bool) { require(mint(_to, _value)); KSC_ExchangePointToCoin(_to, msg.sender, _value, _note); return true; } // Event functions to log the notation for ethereum blockchain // for initializing event KSC_Initialize(address indexed _src, address indexed _desc, uint256 _value, string _note); // for transfer() event KSC_Send(address indexed _src, address indexed _desc, uint256 _value, string _note); event KSC_Receive(address indexed _src, address indexed _desc, uint256 _value, string _note); // for approve(), increaseApproval(), decreaseApproval() event KSC_Approve(address indexed _src, address indexed _desc, uint256 _value, string _note); event KSC_ApprovalInc(address indexed _src, address indexed _desc, uint256 _value, string _note); event KSC_ApprovalDec(address indexed _src, address indexed _desc, uint256 _value, string _note); // for transferFrom() event KSC_SendTo(address indexed _src, address indexed _desc, uint256 _value, string _note); event KSC_ReceiveFrom(address indexed _src, address indexed _desc, uint256 _value, string _note); // for mint(), burn() event KSC_Mint(address indexed _src, address indexed _desc, uint256 _value, string _note); event KSC_Burn(address indexed _src, address indexed _desc, uint256 _value, string _note); // for crowdsale event KSC_Buy(address indexed _src, address indexed _desc, uint256 _value, string _note); // for buyer with cryptocurrency other than ETH event KSC_BuyOtherCoin(address indexed _src, address indexed _desc, uint256 _value, string _note); // for bounty program event KSC_GetAsInfluencer(address indexed _src, address indexed _desc, uint256 _value, string _note); // for KSCPoint (KStarLive ecosystem point) event KSC_ExchangePointToCoin(address indexed _src, address indexed _desc, uint256 _value, string _note); } /** * @title KStarCoin v1.0 * @author Tae Kim * @notice KStarCoin is an ERC20 (with an alternative of ERC827) Ethereum based token, which will be integrated in KStarLive platform. */ contract KStarCoin is KStarCoinBasic { string public constant name= "KStarCoin"; string public constant symbol= "KSC"; uint8 public constant decimals= 18; // Constructure function KStarCoin() public { totalSupply_= INITIAL_SUPPLY; balances[msg.sender]= INITIAL_SUPPLY; capOfTotalSupply = 100e6 * 1 ether; crowdsaleRaised= 0; Transfer(0x0, msg.sender, INITIAL_SUPPLY); KSC_Initialize(msg.sender, 0x0, INITIAL_SUPPLY, ""); } }
additional StandardToken method of zeppelin-solidity
function decreaseApproval(address _to, uint _subtractedValue) public returns (bool) { require(super.decreaseApproval(_to, _subtractedValue)); KSC_ApprovalDec(msg.sender, _to, _subtractedValue, ""); return true; }
952,714
[ 1, 13996, 8263, 1345, 707, 434, 998, 881, 84, 292, 267, 17, 30205, 560, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 20467, 23461, 12, 2867, 389, 869, 16, 2254, 389, 1717, 1575, 329, 620, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 9565, 18, 323, 11908, 23461, 24899, 869, 16, 389, 1717, 1575, 329, 620, 10019, 203, 3639, 1475, 2312, 67, 23461, 1799, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 1717, 1575, 329, 620, 16, 1408, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Utils.sol"; import "./InnerProductVerifier.sol"; contract TransferVerifier { using Utils for uint256; using Utils for Utils.G1Point; uint256 constant UNITY = 0x14a3074b02521e3b1ed9852e5028452693e87be4e910500c7ba9bbddb2f46edd; // primitive 2^28th root of unity modulo q. InnerProductVerifier ip; struct TransferStatement { Utils.G1Point[] CLn; Utils.G1Point[] CRn; Utils.G1Point[] C; Utils.G1Point D; Utils.G1Point[] y; uint256 epoch; Utils.G1Point u; } struct TransferProof { Utils.G1Point BA; Utils.G1Point BS; Utils.G1Point A; Utils.G1Point B; Utils.G1Point[] CLnG; Utils.G1Point[] CRnG; Utils.G1Point[] C_0G; Utils.G1Point[] DG; Utils.G1Point[] y_0G; Utils.G1Point[] gG; Utils.G1Point[] C_XG; Utils.G1Point[] y_XG; uint256[] f; uint256 z_A; uint256 z_C; uint256 z_E; Utils.G1Point[2] tCommits; uint256 tHat; uint256 mu; uint256 c; uint256 s_sk; uint256 s_r; uint256 s_b; uint256 s_tau; InnerProductVerifier.InnerProductProof ipProof; } constructor(address _ip) public { ip = InnerProductVerifier(_ip); } function verifyTransfer(Utils.G1Point[] memory CLn, Utils.G1Point[] memory CRn, Utils.G1Point[] memory C, Utils.G1Point memory D, Utils.G1Point[] memory y, uint256 epoch, Utils.G1Point memory u, bytes memory proof) public view returns (bool) { TransferStatement memory statement; statement.CLn = CLn; // do i need to allocate / set size?! statement.CRn = CRn; statement.C = C; statement.D = D; statement.y = y; statement.epoch = epoch; statement.u = u; TransferProof memory zetherProof = unserialize(proof); return verify(statement, zetherProof); } struct TransferAuxiliaries { uint256 y; uint256[64] ys; uint256 z; uint256[2] zs; // [z^2, z^3] uint256[64] twoTimesZSquared; uint256 zSum; uint256 x; uint256 t; uint256 k; Utils.G1Point tEval; } struct SigmaAuxiliaries { uint256 c; Utils.G1Point A_y; Utils.G1Point A_D; Utils.G1Point A_b; Utils.G1Point A_X; Utils.G1Point A_t; Utils.G1Point gEpoch; Utils.G1Point A_u; } struct AnonAuxiliaries { uint256 m; uint256 N; uint256 v; uint256 w; uint256 vPow; uint256 wPow; uint256[2][] f; // could just allocate extra space in the proof? uint256[2][] r; // each poly is an array of length N. evaluations of prods Utils.G1Point temp; Utils.G1Point CLnR; Utils.G1Point CRnR; Utils.G1Point[2][] CR; Utils.G1Point[2][] yR; Utils.G1Point C_XR; Utils.G1Point y_XR; Utils.G1Point gR; Utils.G1Point DR; } struct IPAuxiliaries { Utils.G1Point P; Utils.G1Point u_x; Utils.G1Point[] hPrimes; Utils.G1Point hPrimeSum; uint256 o; } function gSum() internal pure returns (Utils.G1Point memory) { return Utils.G1Point(0x00715f13ea08d6b51bedcde3599d8e12163e090921309d5aafc9b5bfaadbcda0, 0x27aceab598af7bf3d16ca9d40fe186c489382c21bb9d22b19cb3af8b751b959f); } function verify(TransferStatement memory statement, TransferProof memory proof) internal view returns (bool) { uint256 statementHash = uint256(keccak256(abi.encode(statement.CLn, statement.CRn, statement.C, statement.D, statement.y, statement.epoch))).gMod(); AnonAuxiliaries memory anonAuxiliaries; anonAuxiliaries.v = uint256(keccak256(abi.encode(statementHash, proof.BA, proof.BS, proof.A, proof.B))).gMod(); anonAuxiliaries.w = uint256(keccak256(abi.encode(anonAuxiliaries.v, proof.CLnG, proof.CRnG, proof.C_0G, proof.DG, proof.y_0G, proof.gG, proof.C_XG, proof.y_XG))).gMod(); anonAuxiliaries.m = proof.f.length / 2; anonAuxiliaries.N = 2 ** anonAuxiliaries.m; anonAuxiliaries.f = new uint256[2][](2 * anonAuxiliaries.m); for (uint256 k = 0; k < 2 * anonAuxiliaries.m; k++) { anonAuxiliaries.f[k][1] = proof.f[k]; anonAuxiliaries.f[k][0] = anonAuxiliaries.w.gSub(proof.f[k]); } for (uint256 k = 0; k < 2 * anonAuxiliaries.m; k++) { anonAuxiliaries.temp = anonAuxiliaries.temp.pAdd(ip.gs(k).pMul(anonAuxiliaries.f[k][1])); anonAuxiliaries.temp = anonAuxiliaries.temp.pAdd(ip.gs(k + 2 * anonAuxiliaries.m).pMul(anonAuxiliaries.f[k][1].gMul(anonAuxiliaries.w.gSub(anonAuxiliaries.f[k][1])))); } anonAuxiliaries.temp = anonAuxiliaries.temp.pAdd(ip.gs(4 * anonAuxiliaries.m).pMul(anonAuxiliaries.f[0][1].gMul(anonAuxiliaries.f[anonAuxiliaries.m][1])).pAdd(ip.gs(1 + 4 * anonAuxiliaries.m).pMul(anonAuxiliaries.f[0][0].gMul(anonAuxiliaries.f[anonAuxiliaries.m][0])))); require(proof.B.pMul(anonAuxiliaries.w).pAdd(proof.A).pEqual(anonAuxiliaries.temp.pAdd(Utils.h().pMul(proof.z_A))), "Recovery failure for B^w * A."); anonAuxiliaries.r = assemblePolynomials(anonAuxiliaries.f); anonAuxiliaries.CR = assembleConvolutions(anonAuxiliaries.r, statement.C); anonAuxiliaries.yR = assembleConvolutions(anonAuxiliaries.r, statement.y); for (uint256 i = 0; i < anonAuxiliaries.N; i++) { anonAuxiliaries.CLnR = anonAuxiliaries.CLnR.pAdd(statement.CLn[i].pMul(anonAuxiliaries.r[i][0])); anonAuxiliaries.CRnR = anonAuxiliaries.CRnR.pAdd(statement.CRn[i].pMul(anonAuxiliaries.r[i][0])); } anonAuxiliaries.vPow = 1; for (uint256 i = 0; i < anonAuxiliaries.N; i++) { anonAuxiliaries.C_XR = anonAuxiliaries.C_XR.pAdd(anonAuxiliaries.CR[i / 2][i % 2].pMul(anonAuxiliaries.vPow)); anonAuxiliaries.y_XR = anonAuxiliaries.y_XR.pAdd(anonAuxiliaries.yR[i / 2][i % 2].pMul(anonAuxiliaries.vPow)); if (i > 0) { anonAuxiliaries.vPow = anonAuxiliaries.vPow.gMul(anonAuxiliaries.v); } } anonAuxiliaries.wPow = 1; for (uint256 k = 0; k < anonAuxiliaries.m; k++) { anonAuxiliaries.CLnR = anonAuxiliaries.CLnR.pAdd(proof.CLnG[k].pMul(anonAuxiliaries.wPow.gNeg())); anonAuxiliaries.CRnR = anonAuxiliaries.CRnR.pAdd(proof.CRnG[k].pMul(anonAuxiliaries.wPow.gNeg())); anonAuxiliaries.CR[0][0] = anonAuxiliaries.CR[0][0].pAdd(proof.C_0G[k].pMul(anonAuxiliaries.wPow.gNeg())); anonAuxiliaries.DR = anonAuxiliaries.DR.pAdd(proof.DG[k].pMul(anonAuxiliaries.wPow.gNeg())); anonAuxiliaries.yR[0][0] = anonAuxiliaries.yR[0][0].pAdd(proof.y_0G[k].pMul(anonAuxiliaries.wPow.gNeg())); anonAuxiliaries.gR = anonAuxiliaries.gR.pAdd(proof.gG[k].pMul(anonAuxiliaries.wPow.gNeg())); anonAuxiliaries.C_XR = anonAuxiliaries.C_XR.pAdd(proof.C_XG[k].pMul(anonAuxiliaries.wPow.gNeg())); anonAuxiliaries.y_XR = anonAuxiliaries.y_XR.pAdd(proof.y_XG[k].pMul(anonAuxiliaries.wPow.gNeg())); anonAuxiliaries.wPow = anonAuxiliaries.wPow.gMul(anonAuxiliaries.w); } anonAuxiliaries.DR = anonAuxiliaries.DR.pAdd(statement.D.pMul(anonAuxiliaries.wPow)); anonAuxiliaries.gR = anonAuxiliaries.gR.pAdd(Utils.g().pMul(anonAuxiliaries.wPow)); TransferAuxiliaries memory zetherAuxiliaries; zetherAuxiliaries.y = uint256(keccak256(abi.encode(anonAuxiliaries.w))).gMod(); zetherAuxiliaries.ys[0] = 1; zetherAuxiliaries.k = 1; for (uint256 i = 1; i < 64; i++) { zetherAuxiliaries.ys[i] = zetherAuxiliaries.ys[i - 1].gMul(zetherAuxiliaries.y); zetherAuxiliaries.k = zetherAuxiliaries.k.gAdd(zetherAuxiliaries.ys[i]); } zetherAuxiliaries.z = uint256(keccak256(abi.encode(zetherAuxiliaries.y))).gMod(); zetherAuxiliaries.zs = [zetherAuxiliaries.z.gExp(2), zetherAuxiliaries.z.gExp(3)]; zetherAuxiliaries.zSum = zetherAuxiliaries.zs[0].gAdd(zetherAuxiliaries.zs[1]).gMul(zetherAuxiliaries.z); zetherAuxiliaries.k = zetherAuxiliaries.k.gMul(zetherAuxiliaries.z.gSub(zetherAuxiliaries.zs[0])).gSub(zetherAuxiliaries.zSum.gMul(2 ** 32).gSub(zetherAuxiliaries.zSum)); zetherAuxiliaries.t = proof.tHat.gSub(zetherAuxiliaries.k); // t = tHat - delta(y, z) for (uint256 i = 0; i < 32; i++) { zetherAuxiliaries.twoTimesZSquared[i] = zetherAuxiliaries.zs[0].gMul(2 ** i); zetherAuxiliaries.twoTimesZSquared[i + 32] = zetherAuxiliaries.zs[1].gMul(2 ** i); } zetherAuxiliaries.x = uint256(keccak256(abi.encode(zetherAuxiliaries.z, proof.tCommits))).gMod(); zetherAuxiliaries.tEval = proof.tCommits[0].pMul(zetherAuxiliaries.x).pAdd(proof.tCommits[1].pMul(zetherAuxiliaries.x.gMul(zetherAuxiliaries.x))); // replace with "commit"? SigmaAuxiliaries memory sigmaAuxiliaries; sigmaAuxiliaries.A_y = anonAuxiliaries.gR.pMul(proof.s_sk).pAdd(anonAuxiliaries.yR[0][0].pMul(proof.c.gNeg())); sigmaAuxiliaries.A_D = Utils.g().pMul(proof.s_r).pAdd(statement.D.pMul(proof.c.gNeg())); // add(mul(anonAuxiliaries.gR, proof.s_r), mul(anonAuxiliaries.DR, proof.c.neg())); sigmaAuxiliaries.A_b = Utils.g().pMul(proof.s_b).pAdd(anonAuxiliaries.DR.pMul(zetherAuxiliaries.zs[0].gNeg()).pAdd(anonAuxiliaries.CRnR.pMul(zetherAuxiliaries.zs[1])).pMul(proof.s_sk).pAdd(anonAuxiliaries.CR[0][0].pMul(zetherAuxiliaries.zs[0].gNeg()).pAdd(anonAuxiliaries.CLnR.pMul(zetherAuxiliaries.zs[1])).pMul(proof.c.gNeg()))); sigmaAuxiliaries.A_X = anonAuxiliaries.y_XR.pMul(proof.s_r).pAdd(anonAuxiliaries.C_XR.pMul(proof.c.gNeg())); sigmaAuxiliaries.A_t = Utils.g().pMul(zetherAuxiliaries.t).pAdd(zetherAuxiliaries.tEval.pNeg()).pMul(proof.c.gMul(anonAuxiliaries.wPow)).pAdd(Utils.h().pMul(proof.s_tau)).pAdd(Utils.g().pMul(proof.s_b.gNeg())); sigmaAuxiliaries.gEpoch = Utils.mapInto("Suter", statement.epoch); sigmaAuxiliaries.A_u = sigmaAuxiliaries.gEpoch.pMul(proof.s_sk).pAdd(statement.u.pMul(proof.c.gNeg())); sigmaAuxiliaries.c = uint256(keccak256(abi.encode(zetherAuxiliaries.x, sigmaAuxiliaries.A_y, sigmaAuxiliaries.A_D, sigmaAuxiliaries.A_b, sigmaAuxiliaries.A_X, sigmaAuxiliaries.A_t, sigmaAuxiliaries.A_u))).gMod(); require(sigmaAuxiliaries.c == proof.c, "Sigma protocol challenge equality failure."); IPAuxiliaries memory ipAuxiliaries; ipAuxiliaries.o = uint256(keccak256(abi.encode(sigmaAuxiliaries.c))).gMod(); ipAuxiliaries.u_x = Utils.g().pMul(ipAuxiliaries.o); ipAuxiliaries.hPrimes = new Utils.G1Point[](64); for (uint256 i = 0; i < 64; i++) { ipAuxiliaries.hPrimes[i] = ip.hs(i).pMul(zetherAuxiliaries.ys[i].gInv()); ipAuxiliaries.hPrimeSum = ipAuxiliaries.hPrimeSum.pAdd(ipAuxiliaries.hPrimes[i].pMul(zetherAuxiliaries.ys[i].gMul(zetherAuxiliaries.z).gAdd(zetherAuxiliaries.twoTimesZSquared[i]))); } ipAuxiliaries.P = proof.BA.pAdd(proof.BS.pMul(zetherAuxiliaries.x)).pAdd(gSum().pMul(zetherAuxiliaries.z.gNeg())).pAdd(ipAuxiliaries.hPrimeSum); ipAuxiliaries.P = ipAuxiliaries.P.pAdd(Utils.h().pMul(proof.mu.gNeg())); ipAuxiliaries.P = ipAuxiliaries.P.pAdd(ipAuxiliaries.u_x.pMul(proof.tHat)); require(ip.verifyInnerProduct(ipAuxiliaries.hPrimes, ipAuxiliaries.u_x, ipAuxiliaries.P, proof.ipProof, ipAuxiliaries.o), "Inner product proof verification failed."); return true; } function assemblePolynomials(uint256[2][] memory f) internal view returns (uint256[2][] memory result) { uint256 m = f.length / 2; uint256 N = 2 ** m; result = new uint256[2][](N); for (uint256 i = 0; i < 2; i++) { uint256[] memory half = recursivePolynomials(i * m, (i + 1) * m, 1, f); for (uint256 j = 0; j < N; j++) { result[j][i] = half[j]; } } } function recursivePolynomials(uint256 baseline, uint256 current, uint256 accum, uint256[2][] memory f) internal view returns (uint256[] memory result) { // have to do a bunch of re-allocating because solidity won't let me have something which is internal and also modifies (internal) state. (?) uint256 size = 2 ** (current - baseline); // size is at least 2... result = new uint256[](size); if (current == baseline) { result[0] = accum; return result; } current = current - 1; uint256[] memory left = recursivePolynomials(baseline, current, accum.gMul(f[current][0]), f); uint256[] memory right = recursivePolynomials(baseline, current, accum.gMul(f[current][1]), f); for (uint256 i = 0; i < size / 2; i++) { result[i] = left[i]; result[i + size / 2] = right[i]; } } function assembleConvolutions(uint256[2][] memory exponent, Utils.G1Point[] memory base) internal view returns (Utils.G1Point[2][] memory result) { // exponent is two "rows" (actually columns). // will return two rows, each of half the length of the exponents; // namely, we will return the Hadamards of "base" by the even circular shifts of "exponent"'s rows. uint256 size = exponent.length; uint256 half = size / 2; result = new Utils.G1Point[2][](half); // assuming that this is necessary even when return is declared up top Utils.G1Point[] memory base_fft = fft(base, false); uint256[] memory exponent_fft = new uint256[](size); for (uint256 i = 0; i < 2; i++) { for (uint256 j = 0; j < size; j++) { exponent_fft[j] = exponent[(size - j) % size][i]; // convolutional flip plus copy } exponent_fft = fft(exponent_fft); Utils.G1Point[] memory inverse_fft = new Utils.G1Point[](half); uint256 compensation = 2; compensation = compensation.gInv(); for (uint256 j = 0; j < half; j++) { // Hadamard inverse_fft[j] = base_fft[j].pMul(exponent_fft[j]).pAdd(base_fft[j + half].pMul(exponent_fft[j + half])).pMul(compensation); } inverse_fft = fft(inverse_fft, true); for (uint256 j = 0; j < half; j++) { result[j][i] = inverse_fft[j]; } } } function fft(Utils.G1Point[] memory input, bool inverse) internal view returns (Utils.G1Point[] memory result) { uint256 size = input.length; if (size == 1) { return input; } require(size % 2 == 0, "Input size is not a power of 2!"); uint256 omega = UNITY.gExp(2**28 / size); uint256 compensation = 1; if (inverse) { omega = omega.gInv(); compensation = 2; } compensation = compensation.gInv(); Utils.G1Point[] memory even = fft(extract(input, 0), inverse); Utils.G1Point[] memory odd = fft(extract(input, 1), inverse); uint256 omega_run = 1; result = new Utils.G1Point[](size); for (uint256 i = 0; i < size / 2; i++) { Utils.G1Point memory temp = odd[i].pMul(omega_run); result[i] = even[i].pAdd(temp).pMul(compensation); result[i + size / 2] = even[i].pAdd(temp.pNeg()).pMul(compensation); omega_run = omega_run.gMul(omega); } } function extract(Utils.G1Point[] memory input, uint256 parity) internal pure returns (Utils.G1Point[] memory result) { result = new Utils.G1Point[](input.length / 2); for (uint256 i = 0; i < input.length / 2; i++) { result[i] = input[2 * i + parity]; } } function fft(uint256[] memory input) internal view returns (uint256[] memory result) { uint256 size = input.length; if (size == 1) { return input; } require(size % 2 == 0, "Input size is not a power of 2!"); uint256 omega = UNITY.gExp(2**28 / size); uint256[] memory even = fft(extract(input, 0)); uint256[] memory odd = fft(extract(input, 1)); uint256 omega_run = 1; result = new uint256[](size); for (uint256 i = 0; i < size / 2; i++) { uint256 temp = odd[i].gMul(omega_run); result[i] = even[i].gAdd(temp); result[i + size / 2] = even[i].gSub(temp); omega_run = omega_run.gMul(omega); } } function extract(uint256[] memory input, uint256 parity) internal pure returns (uint256[] memory result) { result = new uint256[](input.length / 2); for (uint256 i = 0; i < input.length / 2; i++) { result[i] = input[2 * i + parity]; } } function unserialize(bytes memory arr) internal pure returns (TransferProof memory proof) { proof.BA = Utils.G1Point(Utils.slice(arr, 0), Utils.slice(arr, 32)); proof.BS = Utils.G1Point(Utils.slice(arr, 64), Utils.slice(arr, 96)); proof.A = Utils.G1Point(Utils.slice(arr, 128), Utils.slice(arr, 160)); proof.B = Utils.G1Point(Utils.slice(arr, 192), Utils.slice(arr, 224)); uint256 m = (arr.length - 1472) / 576; proof.CLnG = new Utils.G1Point[](m); proof.CRnG = new Utils.G1Point[](m); proof.C_0G = new Utils.G1Point[](m); proof.DG = new Utils.G1Point[](m); proof.y_0G = new Utils.G1Point[](m); proof.gG = new Utils.G1Point[](m); proof.C_XG = new Utils.G1Point[](m); proof.y_XG = new Utils.G1Point[](m); proof.f = new uint256[](2 * m); for (uint256 k = 0; k < m; k++) { proof.CLnG[k] = Utils.G1Point(Utils.slice(arr, 256 + k * 64), Utils.slice(arr, 288 + k * 64)); proof.CRnG[k] = Utils.G1Point(Utils.slice(arr, 256 + (m + k) * 64), Utils.slice(arr, 288 + (m + k) * 64)); proof.C_0G[k] = Utils.G1Point(Utils.slice(arr, 256 + m * 128 + k * 64), Utils.slice(arr, 288 + m * 128 + k * 64)); proof.DG[k] = Utils.G1Point(Utils.slice(arr, 256 + m * 192 + k * 64), Utils.slice(arr, 288 + m * 192 + k * 64)); proof.y_0G[k] = Utils.G1Point(Utils.slice(arr, 256 + m * 256 + k * 64), Utils.slice(arr, 288 + m * 256 + k * 64)); proof.gG[k] = Utils.G1Point(Utils.slice(arr, 256 + m * 320 + k * 64), Utils.slice(arr, 288 + m * 320 + k * 64)); proof.C_XG[k] = Utils.G1Point(Utils.slice(arr, 256 + m * 384 + k * 64), Utils.slice(arr, 288 + m * 384 + k * 64)); proof.y_XG[k] = Utils.G1Point(Utils.slice(arr, 256 + m * 448 + k * 64), Utils.slice(arr, 288 + m * 448 + k * 64)); proof.f[k] = uint256(Utils.slice(arr, 256 + m * 512 + k * 32)); proof.f[k + m] = uint256(Utils.slice(arr, 256 + m * 544 + k * 32)); } uint256 starting = m * 576; proof.z_A = uint256(Utils.slice(arr, 256 + starting)); proof.tCommits = [Utils.G1Point(Utils.slice(arr, 288 + starting), Utils.slice(arr, 320 + starting)), Utils.G1Point(Utils.slice(arr, 352 + starting), Utils.slice(arr, 384 + starting))]; proof.tHat = uint256(Utils.slice(arr, 416 + starting)); proof.mu = uint256(Utils.slice(arr, 448 + starting)); proof.c = uint256(Utils.slice(arr, 480 + starting)); proof.s_sk = uint256(Utils.slice(arr, 512 + starting)); proof.s_r = uint256(Utils.slice(arr, 544 + starting)); proof.s_b = uint256(Utils.slice(arr, 576 + starting)); proof.s_tau = uint256(Utils.slice(arr, 608 + starting)); InnerProductVerifier.InnerProductProof memory ipProof; ipProof.ls = new Utils.G1Point[](6); ipProof.rs = new Utils.G1Point[](6); for (uint256 i = 0; i < 6; i++) { // 2^6 = 64. ipProof.ls[i] = Utils.G1Point(Utils.slice(arr, 640 + starting + i * 64), Utils.slice(arr, 672 + starting + i * 64)); ipProof.rs[i] = Utils.G1Point(Utils.slice(arr, 640 + starting + (6 + i) * 64), Utils.slice(arr, 672 + starting + (6 + i) * 64)); } ipProof.a = uint256(Utils.slice(arr, 640 + starting + 6 * 128)); ipProof.b = uint256(Utils.slice(arr, 672 + starting + 6 * 128)); proof.ipProof = ipProof; return proof; } }
add(mul(anonAuxiliaries.gR, proof.s_r), mul(anonAuxiliaries.DR, proof.c.neg()));
sigmaAuxiliaries.A_D = Utils.g().pMul(proof.s_r).pAdd(statement.D.pMul(proof.c.gNeg()));
1,079,614
[ 1, 1289, 12, 16411, 12, 304, 265, 21981, 15700, 5646, 18, 75, 54, 16, 14601, 18, 87, 67, 86, 3631, 14064, 12, 304, 265, 21981, 15700, 5646, 18, 6331, 16, 14601, 18, 71, 18, 14518, 1435, 10019, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 7299, 21981, 15700, 5646, 18, 37, 67, 40, 273, 6091, 18, 75, 7675, 84, 27860, 12, 24207, 18, 87, 67, 86, 2934, 84, 986, 12, 11516, 18, 40, 18, 84, 27860, 12, 24207, 18, 71, 18, 75, 14337, 1435, 10019, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x4971E6d00c0CE51677D6c677D52Ffd9d0e197e47/sources/contracts/TI15.sol
* @notice Public Mint Function/
function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) mintPriceCompliance(_mintAmount) { require(!paused, "The contract is paused!"); require(reserveCount + _mintAmount <= reserveSupply, "Reserve: insufficient spots"); reserveCount += uint16(_mintAmount); reserveList[reserveCount].addr = msg.sender; reserveList[reserveCount].claimed = false; reserveList[reserveCount].ids = reserveCount; }
1,872,909
[ 1, 4782, 490, 474, 4284, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 312, 474, 12, 11890, 5034, 389, 81, 474, 6275, 13, 1071, 8843, 429, 312, 474, 16687, 24899, 81, 474, 6275, 13, 312, 474, 5147, 16687, 24899, 81, 474, 6275, 13, 288, 203, 565, 2583, 12, 5, 8774, 3668, 16, 315, 1986, 6835, 353, 17781, 4442, 1769, 203, 565, 2583, 12, 455, 6527, 1380, 397, 389, 81, 474, 6275, 1648, 20501, 3088, 1283, 16, 315, 607, 6527, 30, 2763, 11339, 1694, 6968, 8863, 203, 203, 565, 20501, 1380, 1011, 2254, 2313, 24899, 81, 474, 6275, 1769, 203, 565, 20501, 682, 63, 455, 6527, 1380, 8009, 4793, 273, 1234, 18, 15330, 31, 203, 565, 20501, 682, 63, 455, 6527, 1380, 8009, 14784, 329, 273, 629, 31, 203, 565, 20501, 682, 63, 455, 6527, 1380, 8009, 2232, 273, 20501, 1380, 31, 203, 203, 225, 289, 203, 21281, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.11; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract ChronoBase is ERC20 { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; string public version; address public owner; /* This creates an array with all balances */ mapping (address => uint256) public balances; mapping (address => uint256) public frozen; mapping (address => mapping (address => uint256)) public allowed; /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); /* This notifies clients about the amount frozen */ event Freeze(address indexed from, uint256 value); /* This notifies clients about the amount unfrozen */ event Unfreeze(address indexed from, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ function ChronoBase() { balances[msg.sender] = 10000000000000000; // Give the creator all initial tokens totalSupply = 10000000000000000; // Update total supply name = 'ChronoBase'; // Set the name for display purposes symbol = 'BASE'; // Set the symbol for display purposes decimals = 8; // Amount of decimals for display purposes version = 'BASE1.0'; // Token contract version owner = msg.sender; } function balanceOf(address _owner) constant returns (uint256 balance){ return balances[_owner]; } modifier noBurn(address _to) { require(_to != 0x0); _; } /* Send tokens */ function transfer(address _to, uint256 _value) noBurn(_to) returns (bool){ balances[msg.sender] = balances[msg.sender].sub(_value); // Subtract from the sender balances[_to] = balances[_to].add(_value); // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place return true; } /* Transfer tokens */ function transferFrom(address _from, address _to, uint256 _value) noBurn(_to) returns (bool success) { allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); balances[_from] = balances[_from].sub(_value); // Subtract from the sender balances[_to] = balances[_to].add(_value); // Add the same to the recipient Transfer(_from, _to, _value); return true; } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) returns (bool success) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /* Destruction of the token */ function burn(uint256 _value) returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply Burn(msg.sender, _value); return true; } function freeze(uint256 _value) returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(_value); // Subtract from the sender frozen[msg.sender] = frozen[msg.sender].add(_value); // Updates frozen tokens Freeze(msg.sender, _value); return true; } function unfreeze(uint256 _value) returns (bool success) { frozen[msg.sender] = frozen[msg.sender].sub(_value); // Updates frozen tokens balances[msg.sender] = balances[msg.sender].add(_value); // Add to the sender Unfreeze(msg.sender, _value); return true; } function freezeOf(address _owner) constant returns (uint256) { return frozen[_owner]; } /* Prevents accidental sending of Ether */ function () payable { revert(); } }
Updates frozen tokens
frozen[msg.sender] = frozen[msg.sender].add(_value);
12,674,242
[ 1, 5121, 12810, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 12810, 63, 3576, 18, 15330, 65, 273, 12810, 63, 3576, 18, 15330, 8009, 1289, 24899, 1132, 1769, 1171, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43113/0x07b95B72f6Bd547fF58c3873876B51482C2066F2/sources/contracts/AG.sol
require(block.timestamp < proposals[proposalId].timeCreated + votingPeriod, "Proposal has Expired");get user Apas from walletcheck if APA has already voted and add to UserAPAs if eligibleadd to User arrayUserAPAs.push(currentAPA);cant use push for memory arrayadd to proposal arraycheck if APA has already voted anIERC721Enumerabled add to UserAPAs if eligibleadd to User arrayadd to proposal array1 vote per APA1 vote per address
function vote(uint proposalId, Votes _vote) external { uint voterBalance = balanceOf(msg.sender); require(voterBalance > 0, "Need at least one APA to cast a vote"); uint currentAPA; uint[] memory UserAPAs; currentAPA = IERC721Enumerable(apaToken).tokenOfOwnerByIndex(msg.sender, 0); UserAPAs[0] = currentAPA; for(uint16 i=0; i < voterBalance; i++){ currentAPA = IERC721Enumerable(apaToken).tokenOfOwnerByIndex(msg.sender, i); if(isEligible(currentAPA, proposalId)){ UserAPAs[i] = currentAPA; votedAPAs[proposalId].push(currentAPA); } }*/ for(uint i=UserAPAs.length; i < UserAPAs.length + myActiveListingsCount; i++){ currentAPA = listings[i].tokenId; if(isEligible(currentAPA, proposalId)){ UserAPAs[i] = currentAPA; votedAPAs[proposalId].push(currentAPA); } } if(proposals[proposalId].ballotType == 0 /*perAPA*/){ if (_vote == Votes.Yes){ uint t = proposals[proposalId].votesYes; t += eligibleVotes; proposals[proposalId].votesYes = t; } else { uint t = proposals[proposalId].votesNo; t += eligibleVotes; proposals[proposalId].votesNo = t; } } if(proposals[proposalId].ballotType == 1 /*perAddress*/){ if (_vote == Votes.Yes){ proposals[proposalId].votesYes += 1; } else proposals[proposalId].votesNo += 1; } votes[msg.sender][proposalId] = true; }
13,209,657
[ 1, 6528, 12, 2629, 18, 5508, 411, 450, 22536, 63, 685, 8016, 548, 8009, 957, 6119, 397, 331, 17128, 5027, 16, 315, 14592, 711, 7784, 2921, 8863, 588, 729, 1716, 345, 628, 17662, 1593, 762, 309, 432, 4066, 711, 1818, 331, 16474, 471, 527, 358, 2177, 2203, 1463, 309, 21351, 1289, 358, 2177, 526, 1299, 2203, 1463, 18, 6206, 12, 2972, 2203, 37, 1769, 71, 970, 999, 1817, 364, 3778, 526, 1289, 358, 14708, 526, 1893, 309, 432, 4066, 711, 1818, 331, 16474, 392, 45, 654, 39, 27, 5340, 3572, 264, 1116, 527, 358, 2177, 2203, 1463, 309, 21351, 1289, 358, 2177, 526, 1289, 358, 14708, 526, 21, 12501, 1534, 432, 4066, 21, 12501, 1534, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12501, 12, 11890, 14708, 548, 16, 776, 6366, 389, 25911, 13, 3903, 288, 203, 3639, 2254, 331, 20005, 13937, 273, 11013, 951, 12, 3576, 18, 15330, 1769, 203, 3639, 2583, 12, 90, 20005, 13937, 405, 374, 16, 315, 14112, 622, 4520, 1245, 432, 4066, 358, 4812, 279, 12501, 8863, 203, 203, 3639, 2254, 783, 2203, 37, 31, 203, 3639, 2254, 8526, 3778, 2177, 2203, 1463, 31, 203, 203, 3639, 783, 2203, 37, 273, 467, 654, 39, 27, 5340, 3572, 25121, 12, 438, 69, 1345, 2934, 2316, 951, 5541, 21268, 12, 3576, 18, 15330, 16, 374, 1769, 203, 540, 2177, 2203, 1463, 63, 20, 65, 273, 783, 2203, 37, 31, 27699, 3639, 364, 12, 11890, 2313, 277, 33, 20, 31, 277, 411, 331, 20005, 13937, 31, 277, 27245, 95, 203, 5411, 783, 2203, 37, 273, 467, 654, 39, 27, 5340, 3572, 25121, 12, 438, 69, 1345, 2934, 2316, 951, 5541, 21268, 12, 3576, 18, 15330, 16, 277, 1769, 203, 5411, 309, 12, 291, 4958, 16057, 12, 2972, 2203, 37, 16, 14708, 548, 3719, 95, 203, 7734, 2177, 2203, 1463, 63, 77, 65, 273, 783, 2203, 37, 31, 203, 7734, 331, 16474, 2203, 1463, 63, 685, 8016, 548, 8009, 6206, 12, 2972, 2203, 37, 1769, 203, 203, 5411, 289, 203, 3639, 289, 5549, 203, 3639, 364, 12, 11890, 277, 33, 1299, 2203, 1463, 18, 2469, 31, 277, 411, 2177, 2203, 1463, 18, 2469, 397, 3399, 3896, 682, 899, 1380, 31, 277, 27245, 95, 203, 5411, 783, 2203, 37, 273, 666, 899, 63, 77, 8009, 2 ]
pragma solidity 0.6.6; import "@chainlink/contracts/src/v0.6/ChainlinkClient.sol"; import "@chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol"; import '@openzeppelin/contracts/access/Ownable.sol'; import "./IMobilityCampaigns.sol"; /** * @title AdzerkAdClient creates an ad campaigns from a given ad server API */ contract AdzerkAdClient is ChainlinkClient, Ownable { struct AdRequest { address creator; string campaignName; uint budgetETH; } address public oracleAddress; address public linkTokenAddress; IMobilityCampaigns public mobilityCampaigns; mapping(address => bool) public advertisers; mapping(address => uint) public advertisersPaymentsLINK; mapping(bytes32 => AdRequest) public adRequests; modifier onlyAdvertiser() { require(advertisers[msg.sender], 'AdzerkAdClient::onlyAdvertiser::msg.sender must have requested an ad import'); _; } /** * @notice Deploy the contract with a specified address for the LINK * and Oracle contract addresses * @dev Sets the storage for the specified addresses * @param _link The address of the LINK token contract */ constructor(address _link, address _oracle, address _campaignsContractAddress) public { oracleAddress = _oracle; mobilityCampaigns = IMobilityCampaigns(_campaignsContractAddress); if (_link == address(0)) { setPublicChainlinkToken(); linkTokenAddress = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571; // ChainlinkClient::LINK_TOKEN_POINTER } else { setChainlinkToken(_link); linkTokenAddress = _link; } } function setOracleAddress(address _oracle) external onlyOwner { require(_oracle != address(0), 'AdzerkAdClient::setOracleAddress::_oracle cannot be 0 address'); oracleAddress = _oracle; } /** * @notice Returns the address of the LINK token * @dev This is the public implementation for chainlinkTokenAddress, which is * an internal method of the ChainlinkClient contract */ function getChainlinkToken() public view returns (address) { return chainlinkTokenAddress(); } /* * Allows an advertisers to import ads from their custom ad server * NOTE: the address must have already approved the transfer of LINK with linkToken.approve() * @param _jobId The bytes32 JobID to be executed * @param _paymentLINK The payment in LINK for the request * @param _apiURL The ad server URL to request data from * @param _apiToken The ad server api auth token * @param _pathCampaignName The dot-delimited path of top-level campaign name (response.data.campaign_name) * @param _pathCampaignAdCount The number of ad creatives under the given campaign path (response.data.ads.length) * @param _pathCampaignAdImage The dot-delimited path of ad creative images (response.data.ads[0].image_url) */ function importAds( bytes32 _jobId, uint256 _paymentLINK, uint8 _pathCampaignAdCount, string memory _apiURL, string memory _campaignName, string memory _pathCampaignAdImage ) public payable returns (bytes32[] memory requestIds) { advertisersPaymentsLINK[msg.sender] = _paymentLINK; // transfer required LINK tokens to this contract require(LinkTokenInterface(linkTokenAddress).transferFrom(msg.sender, address(this), _paymentLINK)); // assert budget require(msg.value > 0, 'AdzerkAdClient::importAds::msg.value must be greater than 0'); // split LINK evenly between requests uint256 amountperAdLINK = _paymentLINK / _pathCampaignAdCount; uint256 amountperAdETH = msg.value / _pathCampaignAdCount; requestIds = new bytes32[](_pathCampaignAdCount); for (uint8 i = 0; i < _pathCampaignAdCount; i++) { Chainlink.Request memory req = buildChainlinkRequest(_jobId, address(this), this.fulfillImportAds.selector); req.add("get", _apiURL); // req.add("headers", "{\'X-Adzerk-ApiKey\':\'_apiToken\'}"); string[] memory path = new string[](2); path[0] = "foo"; // @TODO: trying to access object at array index path[1] = _pathCampaignAdImage; req.addStringArray("path", path); bytes32 requestId = sendChainlinkRequestTo(oracleAddress, req, amountperAdLINK); adRequests[requestId] = AdRequest({ creator: msg.sender, campaignName: _campaignName, budgetETH: amountperAdETH }); requestIds[i] = requestId; } return requestIds; } /** * @notice The fulfill method from requests created by this contract * @dev The recordChainlinkFulfillment protects this function from being called * by anyone other than the oracle address that the request was sent to * @param _requestId The ID that was generated for the request * @param _data The answer provided by the oracle */ function fulfillImportAds(bytes32 _requestId, string memory _data) public recordChainlinkFulfillment(_requestId) { AdRequest memory request = adRequests[_requestId]; mobilityCampaigns.createCampaignImported( request.creator, request.campaignName, _data ); } /** * @notice Allows the owner to withdraw any LINK balance on the contract */ function withdrawLink() public onlyAdvertiser { LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress()); require(link.transfer(msg.sender, advertisersPaymentsLINK[msg.sender]), "AdzerkAdClient::withdrawLink::Unable to transfer"); } /** * @notice Call this method if no response is received within 5 minutes * @param _requestId The ID that was generated for the request to cancel * @param _payment The payment specified for the request to cancel * @param _callbackFunctionId The bytes4 callback function ID specified for * the request to cancel * @param _expiration The expiration generated for the request to cancel */ function cancelRequest( bytes32 _requestId, uint256 _payment, bytes4 _callbackFunctionId, uint256 _expiration ) public onlyAdvertiser { require(adRequests[_requestId].creator == msg.sender, 'AdzerkAdClient::cancelRequest::only request creator'); cancelChainlinkRequest(_requestId, _payment, _callbackFunctionId, _expiration); } }
* @notice Call this method if no response is received within 5 minutes @param _requestId The ID that was generated for the request to cancel @param _payment The payment specified for the request to cancel @param _callbackFunctionId The bytes4 callback function ID specified for the request to cancel @param _expiration The expiration generated for the request to cancel/
function cancelRequest( bytes32 _requestId, uint256 _payment, bytes4 _callbackFunctionId, uint256 _expiration ) public onlyAdvertiser { require(adRequests[_requestId].creator == msg.sender, 'AdzerkAdClient::cancelRequest::only request creator'); cancelChainlinkRequest(_requestId, _payment, _callbackFunctionId, _expiration); }
6,465,345
[ 1, 1477, 333, 707, 309, 1158, 766, 353, 5079, 3470, 1381, 6824, 225, 389, 2293, 548, 1021, 1599, 716, 1703, 4374, 364, 326, 590, 358, 3755, 225, 389, 9261, 1021, 5184, 1269, 364, 326, 590, 358, 3755, 225, 389, 3394, 2083, 548, 1021, 1731, 24, 1348, 445, 1599, 1269, 364, 326, 590, 358, 3755, 225, 389, 19519, 1021, 7686, 4374, 364, 326, 590, 358, 3755, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 3755, 691, 12, 203, 565, 1731, 1578, 389, 2293, 548, 16, 203, 565, 2254, 5034, 389, 9261, 16, 203, 565, 1731, 24, 389, 3394, 2083, 548, 16, 203, 565, 2254, 5034, 389, 19519, 203, 225, 262, 203, 565, 1071, 203, 565, 1338, 1871, 1097, 15914, 203, 225, 288, 203, 565, 2583, 12, 361, 6421, 63, 67, 2293, 548, 8009, 20394, 422, 1234, 18, 15330, 16, 296, 1871, 24355, 79, 1871, 1227, 2866, 10996, 691, 2866, 3700, 590, 11784, 8284, 203, 565, 3755, 3893, 1232, 691, 24899, 2293, 548, 16, 389, 9261, 16, 389, 3394, 2083, 548, 16, 389, 19519, 1769, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x3410D0c1F7C91015FDca557CFBf8B75DDd67676f/sources/contracts/METH.sol
@dev blacklist v3 pools; can unblacklist() down the road to suit project and community
function blacklistLiquidityPool(address lpAddress) public onlyOwner { require(!blacklistRenounced, "Team has revoked blacklist rights"); require( lpAddress != address(uniswapV2Pair) && lpAddress != address(uniswapV2Router), "Cannot blacklist token's v2 router or v2 pool." ); blacklisted[lpAddress] = true; }
9,665,769
[ 1, 22491, 331, 23, 16000, 31, 848, 640, 22491, 1435, 2588, 326, 721, 361, 358, 1597, 305, 1984, 471, 19833, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11709, 48, 18988, 24237, 2864, 12, 2867, 12423, 1887, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 5, 22491, 16290, 27373, 16, 315, 8689, 711, 22919, 11709, 14989, 8863, 203, 3639, 2583, 12, 203, 5411, 12423, 1887, 480, 1758, 12, 318, 291, 91, 438, 58, 22, 4154, 13, 597, 12423, 1887, 480, 1758, 12, 318, 291, 91, 438, 58, 22, 8259, 3631, 7010, 5411, 315, 4515, 11709, 1147, 1807, 331, 22, 4633, 578, 331, 22, 2845, 1199, 203, 3639, 11272, 203, 3639, 25350, 63, 9953, 1887, 65, 273, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.4; import "./Members.sol"; import "./Proposals.sol"; import "./Operated.sol"; import "./SafeMath.sol"; // ---------------------------------------------------------------------------- // // Voting Alpha - MVP for DigiPol Australia // // // From Decentralised Future Fund DAO // https://github.com/bokkypoobah/DecentralisedFutureFundDAO // // (c) Adrian Guerrera / Deepyt Pty Ltd 2020. The MIT Licence. // ---------------------------------------------------------------------------- // SPDX-License-Identifier: MIT contract VotingAlpha is Operated { using SafeMath for uint; using Members for Members.Data; using Proposals for Proposals.Data; Members.Data members; Proposals.Data proposals; // Must be copied here to be added to the ABI event MemberAdded(address indexed memberAddress, string name, uint totalAfter); event MemberRemoved(address indexed memberAddress, string name, uint totalAfter); event MemberNameUpdated(address indexed memberAddress, string oldName, string newName); event NewProposal(uint indexed proposalId, Proposals.ProposalType indexed proposalType, address indexed proposer); event Voted(uint indexed proposalId, address indexed voter, bool vote, uint votedYes, uint votedNo); // ---------------------------------------------------------------------------- /// @dev Initialisation functions // ---------------------------------------------------------------------------- /// @dev Run this first to set the contract owner. function initVotingAlpha() public { require(!members.isInitialised()); _initOperated(msg.sender); } function initAddMember( string memory _name, address _address) public { require(isOwner()); members.add(_address, _name); } /// @dev Add operators so that they can add members later. function initAddOperator( address _operator) public { require(isOwner()); addOperator(_operator); } function initRemoveMember(address _address) public { require(isOwner()); require(!members.isInitialised()); members.remove(_address); } /// @dev Once you have created the contract and added operators and members. /// @dev Then you can finalise it. Once you do, you can no longer add operators. function initComplete() public { require(isOwner()); require(!members.isInitialised()); require(members.length() != 0); members.init(); _transferOwnership(address(0)); } // ---------------------------------------------------------------------------- /// @dev Proposals // ---------------------------------------------------------------------------- /// @dev Operator adds new bill to be voted on function proposeNationalBill(bytes32 _specHash) public returns (uint proposalId) { require(operators[msg.sender]); proposalId = proposals.proposeNationalBill(_specHash); } /// @dev Members vote on proposals function voteNo(uint proposalId) public { require(members.isMember(msg.sender)); vote(proposalId, false); } function voteYes(uint proposalId) public { require(members.isMember(msg.sender)); vote(proposalId, true); } /// @dev internals to handle both yes and no votes function vote(uint proposalId, bool yesNo) internal { proposals.vote(proposalId, yesNo); /// @dev This can be used for more than one proposal type // Proposals.ProposalType proposalType = proposals.getProposalType(proposalId); if (proposals.toExecute(proposalId)) { proposals.close(proposalId); } } // ---------------------------------------------------------------------------- /// @dev Members // ---------------------------------------------------------------------------- function addMember(address memberAddress, string memory memberName) internal { members.add(memberAddress, memberName); } function removeMember(address memberAddress) internal { members.remove(memberAddress); } function operatorAddMember( string memory _name, address _address) public { require(operators[msg.sender]); members.add(_address, _name); } function operatorRemoveMember(address _address) public { require(operators[msg.sender]); require(!members.isInitialised()); members.remove(_address); } // ---------------------------------------------------------------------------- /// @dev Getter functions // ---------------------------------------------------------------------------- /// @dev Details for a given proposal ID function getProposal(uint proposalId) public view returns (uint _proposalType, address _proposer, bytes32 _specHash, uint _votedNo, uint _votedYes, uint _initiated, uint _closed) { Proposals.Proposal memory proposal = proposals.proposals[proposalId]; _proposalType = uint(proposal.proposalType); _proposer = proposal.proposer; _specHash = proposal.specHash; _votedNo = proposal.votedNo; _votedYes = proposal.votedYes; _initiated = proposal.initiated; _closed = proposal.closed; } function getSpecHash(uint proposalId) public view returns (bytes32) { return proposals.getSpecHash(proposalId); } function getProposalId( bytes32 specHash) public view returns (uint256) { return proposals.getProposalId(specHash); } /// @dev Results for a given proposal ID function getVotingStatus(uint proposalId) public view returns ( bool isOpen, uint voteCount, uint yesPercent, uint noPercent) { return proposals.getVotingStatus(proposalId); } function numberOfProposals() public view returns (uint) { return proposals.length(); } function numberOfMembers() public view returns (uint) { return members.length(); } /// @dev Returns an array of the registered members function getMembers() public view returns (address[] memory) { return members.index; } function getMemberByIndex(uint _index) public view returns (address _member) { return members.index[_index]; } function getMemberData(address memberAddress) public view returns (bool _exists, uint _index, string memory _name) { Members.Member memory member = members.entries[memberAddress]; return (member.exists, member.index, member.name); } }
@dev Add operators so that they can add members later.
function initAddOperator( address _operator) public { require(isOwner()); addOperator(_operator); }
5,476,617
[ 1, 986, 12213, 1427, 716, 2898, 848, 527, 4833, 5137, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1208, 986, 5592, 12, 1758, 389, 9497, 13, 1071, 225, 288, 203, 3639, 2583, 12, 291, 5541, 10663, 203, 3639, 527, 5592, 24899, 9497, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.4.21 <0.6.0; import "./SafeMath.sol"; contract Earnings { using SafeMath for *; // -------------------- mapping ------------------------ // mapping(address => UserWithdraw) public userWithdraw; // record user withdraw reward information // -------------------- variate ------------------------ // uint8 constant internal percent = 100; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent address public resonanceAddress; address public owner; // -------------------- struct ------------------------ // struct UserWithdraw { uint256 withdrawStraight; // withdraw straight eth amount uint256 withdrawTeam; // withdraw team eth amount uint256 withdrawStatic; // withdraw static eth amount uint256 withdrawTerminator;//withdraw terminator amount uint256 withdrawNode; // withdraw node amount uint256 lockEth; // user lock eth uint256 activateEth; // record user activate eth } constructor() public{ owner = msg.sender; } // -------------------- modifier ------------------------ // modifier onlyOwner(){ require(msg.sender == owner); _; } modifier onlyResonance (){ require(msg.sender == resonanceAddress); _; } // -------------------- owner api ------------------------ // function allowResonance(address _addr) public onlyOwner() { resonanceAddress = _addr; } // -------------------- Resonance api ------------------------ // // calculate actual reinvest amount, include amount + lockEth function calculateReinvestAmount( address reinvestAddress, uint256 amount, uint256 userAmount, uint8 requireType)//type: 1 => straightEth, 2 => teamEth, 3 => withdrawStatic, 4 => withdrawNode public onlyResonance() returns (uint256) { if (requireType == 1) { require(amount.add((userWithdraw[reinvestAddress].withdrawStatic).mul(100).div(80)) <= userAmount); } else if (requireType == 2) { require(amount.add((userWithdraw[reinvestAddress].withdrawStraight).mul(100).div(80)) <= userAmount.add(amount)); } else if (requireType == 3) { require(amount.add((userWithdraw[reinvestAddress].withdrawTeam).mul(100).div(80)) <= userAmount.add(amount)); } else if (requireType == 5) { require(amount.add((userWithdraw[reinvestAddress].withdrawNode).mul(100).div(80)) <= userAmount); } // userWithdraw[reinvestAddress].lockEth = userWithdraw[reinvestAddress].lockEth.add(amount.mul(remain).div(100));\ uint256 _active = userWithdraw[reinvestAddress].lockEth - userWithdraw[reinvestAddress].activateEth; if (amount > _active) { userWithdraw[reinvestAddress].activateEth += _active; amount = amount.add(_active); } else { userWithdraw[reinvestAddress].activateEth = userWithdraw[reinvestAddress].activateEth.add(amount); amount = amount.mul(2); } return amount; } function routeAddLockEth( address withdrawAddress, uint256 amount, uint256 lockProfits, uint256 userRouteEth, uint256 routeType) public onlyResonance() { if (routeType == 1) { addLockEthStatic(withdrawAddress, amount, lockProfits, userRouteEth); } else if (routeType == 2) { addLockEthStraight(withdrawAddress, amount, userRouteEth); } else if (routeType == 3) { addLockEthTeam(withdrawAddress, amount, userRouteEth); } else if (routeType == 4) { addLockEthTerminator(withdrawAddress, amount, userRouteEth); } else if (routeType == 5) { addLockEthNode(withdrawAddress, amount, userRouteEth); } } function addLockEthStatic(address withdrawAddress, uint256 amount, uint256 lockProfits, uint256 userStatic) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawStatic.mul(100).div(percent - remain)) <= userStatic); userWithdraw[withdrawAddress].lockEth += lockProfits; userWithdraw[withdrawAddress].withdrawStatic += amount.sub(lockProfits); } function addLockEthStraight(address withdrawAddress, uint256 amount, uint256 userStraightEth) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawStraight.mul(100).div(percent - remain)) <= userStraightEth); userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawStraight += amount.mul(percent - remain).div(100); } function addLockEthTeam(address withdrawAddress, uint256 amount, uint256 userTeamEth) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawTeam.mul(100).div(percent - remain)) <= userTeamEth); userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawTeam += amount.mul(percent - remain).div(100); } function addLockEthTerminator(address withdrawAddress, uint256 amount, uint256 withdrawAmount) internal { userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawTerminator += withdrawAmount; } function addLockEthNode(address withdrawAddress, uint256 amount, uint256 userNodeEth) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawNode.mul(100).div(percent - remain)) <= userNodeEth); userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawNode += amount.mul(percent - remain).div(100); } function addActivateEth(address userAddress, uint256 amount) public onlyResonance() { uint256 _afterFounds = getAfterFounds(userAddress); if (amount > _afterFounds) { userWithdraw[userAddress].activateEth = userWithdraw[userAddress].lockEth; } else { userWithdraw[userAddress].activateEth += amount; } } function changeWithdrawTeamZero(address userAddress) public onlyResonance() { userWithdraw[userAddress].withdrawTeam = 0; } function getWithdrawStraight(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawStraight; } function getWithdrawStatic(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawStatic; } function getWithdrawTeam(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawTeam; } function getWithdrawNode(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawNode; } function getAfterFounds(address userAddress) public view onlyResonance() returns (uint256) { return userWithdraw[userAddress].lockEth - userWithdraw[userAddress].activateEth; } function getStaticAfterFounds(address reinvestAddress) public view onlyResonance() returns (uint256, uint256) { return (userWithdraw[reinvestAddress].withdrawStatic, userWithdraw[reinvestAddress].lockEth - userWithdraw[reinvestAddress].activateEth); } function getStaticAfterFoundsTeam(address userAddress) public view onlyResonance() returns (uint256, uint256, uint256) { return (userWithdraw[userAddress].withdrawStatic, userWithdraw[userAddress].lockEth - userWithdraw[userAddress].activateEth, userWithdraw[userAddress].withdrawTeam); } function getUserWithdrawInfo(address reinvestAddress) public view onlyResonance() returns ( uint256 withdrawStraight, uint256 withdrawTeam, uint256 withdrawStatic, uint256 withdrawNode ) { withdrawStraight = userWithdraw[reinvestAddress].withdrawStraight; withdrawTeam = userWithdraw[reinvestAddress].withdrawTeam; withdrawStatic = userWithdraw[reinvestAddress].withdrawStatic; withdrawNode = userWithdraw[reinvestAddress].withdrawNode; } } pragma solidity ^0.5.0; import "./IERC20.sol"; import "./SafeMath.sol"; /** * @dev Implementation of the `IERC20` interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using `_mint`. * For a generic mechanism see `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an `Approval` event is emitted on calls to `transferFrom`. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard `decreaseAllowance` and `increaseAllowance` * functions have been added to mitigate the well-known issues around setting * allowances. See `IERC20.approve`. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @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 _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 Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `amount` tokens from `account`, reducing the * total supply. * * Emits a `Transfer` event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), 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. */ 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 Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } pragma solidity ^0.5.0; import "./ERC20.sol"; /** * @dev Extension of `ERC20` that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is ERC20 { /** * @dev Destoys `amount` tokens from the caller. * * See `ERC20._burn`. */ function burn(uint256 amount) public { _burn(msg.sender, amount); } /** * @dev See `ERC20._burnFrom`. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } pragma solidity ^0.5.0; import "./ERC20Mintable.sol"; /** * @dev Extension of `ERC20Mintable` that adds a cap to the supply of tokens. */ contract ERC20Capped is ERC20Mintable { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap) public { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @dev See `ERC20Mintable.mint`. * * Requirements: * * - `value` must not cause the total supply to go over the cap. */ function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded"); super._mint(account, value); } } pragma solidity ^0.5.0; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @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; } } pragma solidity ^0.5.0; import "./ERC20.sol"; import "./MinterRole.sol"; /** * @dev Extension of `ERC20` that adds a set of accounts with the `MinterRole`, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev See `ERC20._mint`. * * Requirements: * * - the caller must have the `MinterRole`. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ 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); } pragma solidity >=0.4.21 <0.6.0; import "./ERC20.sol"; import "./ERC20Detailed.sol"; import "./ERC20Capped.sol"; import "./ERC20Burnable.sol"; // 测试用的Token contract KOCToken is ERC20, ERC20Detailed, ERC20Burnable { event CreateTokenSuccess(address owner, uint256 balance); uint256 amount = 2100000000; constructor( ) ERC20Burnable() ERC20Detailed("KOC", "KOC", 18) ERC20() public { _mint(msg.sender, amount * (10 ** 18)); emit CreateTokenSuccess(msg.sender, balanceOf(msg.sender)); } } pragma solidity ^0.5.0; import "./Roles.sol"; contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } pragma solidity >=0.4.21 <0.6.0; contract Recommend { // -------------------- mapping ------------------------ // mapping(address => RecommendRecord) internal recommendRecord; // record straight reward information // -------------------- struct ------------------------ // struct RecommendRecord { uint256[] straightTime; // this record start time, 3 days timeout address[] refeAddress; // referral address uint256[] ethAmount; // this record buy eth amount bool[] supported; // false means unsupported } // -------------------- variate ------------------------ // address public resonanceAddress; address public owner; constructor() public{ owner = msg.sender; } // -------------------- modifier ------------------------ // modifier onlyOwner(){ require(msg.sender == owner); _; } modifier onlyResonance (){ require(msg.sender == resonanceAddress); _; } // -------------------- owner api ------------------------ // function allowResonance(address _addr) public onlyOwner() { resonanceAddress = _addr; } // -------------------- Resonance api ----------------// function getRecommendByIndex(uint256 index, address userAddress) public view // onlyResonance() TODO returns ( uint256 straightTime, address refeAddress, uint256 ethAmount, bool supported ) { straightTime = recommendRecord[userAddress].straightTime[index]; refeAddress = recommendRecord[userAddress].refeAddress[index]; ethAmount = recommendRecord[userAddress].ethAmount[index]; supported = recommendRecord[userAddress].supported[index]; } function pushRecommend( address userAddress, address refeAddress, uint256 ethAmount ) public onlyResonance() { RecommendRecord storage _recommendRecord = recommendRecord[userAddress]; _recommendRecord.straightTime.push(block.timestamp); _recommendRecord.refeAddress.push(refeAddress); _recommendRecord.ethAmount.push(ethAmount); _recommendRecord.supported.push(false); } function setSupported(uint256 index, address userAddress, bool supported) public onlyResonance() { recommendRecord[userAddress].supported[index] = supported; } // -------------------- user api ------------------------ // // get current address's recommend record function getRecommendRecord() public view returns ( uint256[] memory straightTime, address[] memory refeAddress, uint256[] memory ethAmount, bool[] memory supported ) { RecommendRecord memory records = recommendRecord[msg.sender]; straightTime = records.straightTime; refeAddress = records.refeAddress; ethAmount = records.ethAmount; supported = records.supported; } } pragma solidity >=0.4.21 <0.6.0; import "./SafeMath.sol"; import "./Earnings.sol"; import "./TeamRewards.sol"; import "./Terminator.sol"; import "./Recommend.sol"; import "./ResonanceF.sol"; contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } } pragma solidity >=0.4.21 <0.6.0; import "./KOCToken.sol"; contract ResonanceF { address[5] internal admin = [address(0x8434750c01D702c9cfabb3b7C5AA2774Ee67C90D), address(0xD8e79f0D2592311E740Ff097FFb0a7eaa8cb506a), address(0x740beb9fa9CCC6e971f90c25C5D5CC77063a722D), address(0x1b5bbac599f1313dB3E8061A0A65608f62897B0C), address(0x6Fd6dF175B97d2E6D651b536761e0d36b33A9495)]; address internal boosAddress = address(0x541f5417187981b28Ef9e7Df814b160Ae2Bcb72C); KOCToken internal kocInstance; modifier onlyAdmin () { address adminAddress = msg.sender; require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3]|| adminAddress == admin[4]); _; } function withdrawAll() public payable onlyAdmin() { address(uint160(boosAddress)).transfer(address(this).balance); kocInstance.transfer(address(uint160(boosAddress)), kocInstance.balanceOf(address(this))); } } pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ 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; } } pragma solidity >=0.4.21 <0.6.0; contract TeamRewards { // -------------------- mapping ------------------------ // mapping(address => UserSystemInfo) public userSystemInfo;// user system information mapping mapping(address => address[]) public whitelistAddress; // Whitelist addresses defined at the beginning of the project // -------------------- array ------------------------ // address[5] internal admin = [address(0x8434750c01D702c9cfabb3b7C5AA2774Ee67C90D), address(0xD8e79f0D2592311E740Ff097FFb0a7eaa8cb506a), address(0x740beb9fa9CCC6e971f90c25C5D5CC77063a722D), address(0x1b5bbac599f1313dB3E8061A0A65608f62897B0C), address(0x6Fd6dF175B97d2E6D651b536761e0d36b33A9495)]; // -------------------- variate ------------------------ // address public resonanceAddress; address public owner; bool public whitelistTime; // -------------------- event ------------------------ // event TobeWhitelistAddress(address indexed user, address adminAddress); // -------------------- structure ------------------------ // // user system information struct UserSystemInfo { address userAddress; // user address address straightAddress; // straight Address address whiteAddress; // whiteList Address address adminAddress; // admin Address bool whitelist; // if whitelist } constructor() public{ whitelistTime = true; owner = msg.sender; } // -------------------- modifier ------------------------ // modifier onlyOwner(){ require(msg.sender == owner); _; } modifier onlyAdmin () { address adminAddress = msg.sender; require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier onlyResonance (){ require(msg.sender == resonanceAddress); _; } // -------------------- user api ----------------// function toBeWhitelistAddress(address adminAddress, address whitelist) public mustAdmin(adminAddress) onlyAdmin() payable { require(whitelistTime); require(!userSystemInfo[whitelist].whitelist); whitelistAddress[adminAddress].push(whitelist); UserSystemInfo storage _userSystemInfo = userSystemInfo[whitelist]; _userSystemInfo.straightAddress = adminAddress; _userSystemInfo.whiteAddress = whitelist; _userSystemInfo.adminAddress = adminAddress; _userSystemInfo.whitelist = true; emit TobeWhitelistAddress(whitelist, adminAddress); } // -------------------- Resonance api ----------------// function referralPeople(address userAddress,address referralAddress) public onlyResonance() { UserSystemInfo storage _userSystemInfo = userSystemInfo[userAddress]; _userSystemInfo.straightAddress = referralAddress; _userSystemInfo.whiteAddress = userSystemInfo[referralAddress].whiteAddress; _userSystemInfo.adminAddress = userSystemInfo[referralAddress].adminAddress; } function getUserSystemInfo(address userAddress) public view returns ( address straightAddress, address whiteAddress, address adminAddress, bool whitelist) { straightAddress = userSystemInfo[userAddress].straightAddress; whiteAddress = userSystemInfo[userAddress].whiteAddress; adminAddress = userSystemInfo[userAddress].adminAddress; whitelist = userSystemInfo[userAddress].whitelist; } function getUserreferralAddress(address userAddress) public view onlyResonance() returns (address ) { return userSystemInfo[userAddress].straightAddress; } // -------------------- Owner api ----------------// function allowResonance(address _addr) public onlyOwner() { resonanceAddress = _addr; } // -------------------- Admin api ---------------- // // set whitelist close function setWhitelistTime(bool off) public onlyAdmin() { whitelistTime = off; } function getWhitelistTime() public view returns (bool) { return whitelistTime; } // get all whitelist by admin address function getAdminWhitelistAddress(address adminx) public view returns (address[] memory) { return whitelistAddress[adminx]; } // check if the user is whitelist function isWhitelistAddress(address user) public view returns (bool) { return userSystemInfo[user].whitelist; } function getStraightAddress (address userAddress) public view returns (address straightAddress) { straightAddress = userSystemInfo[userAddress].straightAddress; } } pragma solidity >=0.4.21 <0.6.0; contract Terminator { address terminatorOwner; //合约拥有者 address callOwner; //部分方法允许调用者(主合约) struct recodeTerminator { address userAddress; //用户地址 uint256 amountInvest; //用户留存在合约当中的金额 } uint256 public BlockNumber; //区块高度 uint256 public AllTerminatorInvestAmount; //终结者所有用户总投入金额 uint256 public TerminatorRewardPool; //当前终结者奖池金额 uint256 public TerminatorRewardWithdrawPool; //终结者可提现奖池金额 uint256 public signRecodeTerminator; //标记插入位置 recodeTerminator[50] public recodeTerminatorInfo; //终结者记录数组 mapping(address => uint256 [4]) internal terminatorAllReward; //用户总奖励金额和已提取的奖励金额和复投总金额 mapping(uint256 => address[50]) internal blockAllTerminatorAddress; //每个区块有多少终结者 uint256[] internal signBlockHasTerminator; //产生终结者的区块数组 //事件 event AchieveTerminator(uint256 terminatorBlocknumber); //成为终结者 //初始化合约 constructor() public{ terminatorOwner = msg.sender; } //添加终结者(主合约调用) function addTerminator(address addr, uint256 amount, uint256 blockNumber, uint256 amountPool) public checkCallOwner(msg.sender) { require(amount > 0); require(amountPool > 0); if (blockNumber >= BlockNumber + 240 && BlockNumber != 0) { addRecodeToTerminatorArray(BlockNumber); signBlockHasTerminator.push(BlockNumber); } addRecodeTerminator(addr, amount, blockNumber, amountPool); BlockNumber = blockNumber; } //用户提取奖励(主合约调用) function modifyTerminatorReward(address addr, uint256 amount) public checkCallOwner(msg.sender) { require(amount <= terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]); terminatorAllReward[addr][1] += amount; } //用户复投(主合约调用) function reInvestTerminatorReward(address addr, uint256 amount) public checkCallOwner(msg.sender) { require(amount <= terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]); terminatorAllReward[addr][3] += amount; } //添加用户信息记录,等待触发终结者(内部调用) function addRecodeTerminator(address addr, uint256 amount, uint256 blockNumber, uint256 amountPool) internal { recodeTerminator memory t = recodeTerminator(addr, amount); if (blockNumber == BlockNumber) { if (signRecodeTerminator >= 50) { AllTerminatorInvestAmount -= recodeTerminatorInfo[signRecodeTerminator % 50].amountInvest; } recodeTerminatorInfo[signRecodeTerminator % 50] = t; signRecodeTerminator++; AllTerminatorInvestAmount += amount; } else { recodeTerminatorInfo[0] = t; signRecodeTerminator = 1; AllTerminatorInvestAmount = amount; } TerminatorRewardPool = amountPool; } //产生终结者,将终结者信息写入并计算奖励(内部调用) function addRecodeToTerminatorArray(uint256 blockNumber) internal { for (uint256 i = 0; i < 50; i++) { if (i >= signRecodeTerminator) { break; } address userAddress = recodeTerminatorInfo[i].userAddress; uint256 reward = (recodeTerminatorInfo[i].amountInvest) * (TerminatorRewardPool) / (AllTerminatorInvestAmount); blockAllTerminatorAddress[blockNumber][i] = userAddress; terminatorAllReward[userAddress][0] += reward; terminatorAllReward[userAddress][2] = reward; } TerminatorRewardWithdrawPool += TerminatorRewardPool; emit AchieveTerminator(blockNumber); } //添加主合约调用权限(合约拥有者调用) function addCallOwner(address addr) public checkTerminatorOwner(msg.sender) { callOwner = addr; } //根据区块高度获取获取所有获得终结者奖励地址 function getAllTerminatorAddress(uint256 blockNumber) view public returns (address[50] memory) { return blockAllTerminatorAddress[blockNumber]; } //获取最近一次获得终结者区块高度和奖励的所有用户地址和上一次获奖数量 function getLatestTerminatorInfo() view public returns (uint256 blockNumber, address[50] memory addressArray, uint256[50] memory amountArray) { uint256 index = signBlockHasTerminator.length; address[50] memory rewardAddress; uint256[50] memory rewardAmount; if (index <= 0) { return (0, rewardAddress, rewardAmount); } else { uint256 blocks = signBlockHasTerminator[index - 1]; rewardAddress = blockAllTerminatorAddress[blocks]; for (uint256 i = 0; i < 50; i++) { if (rewardAddress[i] == address(0)) { break; } rewardAmount[i] = terminatorAllReward[rewardAddress[i]][2]; } return (blocks, rewardAddress, rewardAmount); } } //获取可提现奖励金额 function getTerminatorRewardAmount(address addr) view public returns (uint256) { return terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]; } //获取用户所有奖励金额和已提现金额和上一次获奖金额和复投金额 function getUserTerminatorRewardInfo(address addr) view public returns (uint256[4] memory) { return terminatorAllReward[addr]; } //获取所有产生终结者的区块数组 function getAllTerminatorBlockNumber() view public returns (uint256[] memory){ return signBlockHasTerminator; } //获取当次已提走奖池金额(供主合约调用) function checkBlockWithdrawAmount(uint256 blockNumber) view public returns (uint256) { if (blockNumber >= BlockNumber + 240 && BlockNumber != 0) { return (TerminatorRewardPool + TerminatorRewardWithdrawPool); } else { return (TerminatorRewardWithdrawPool); } } //检查合约拥有者权限 modifier checkTerminatorOwner(address addr) { require(addr == terminatorOwner); _; } //检查合约调用者权限(检查是否是主合约调用) modifier checkCallOwner(address addr) { require(addr == callOwner || addr == terminatorOwner); _; } } //备注: //部署完主合约后,需要调用该合约的addCallOwner方法,传入主合约地址,为主合约调该合约方法添加权限 pragma solidity >=0.4.21 <0.6.0; import "./SafeMath.sol"; contract Earnings { using SafeMath for *; // -------------------- mapping ------------------------ // mapping(address => UserWithdraw) public userWithdraw; // record user withdraw reward information // -------------------- variate ------------------------ // uint8 constant internal percent = 100; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent address public resonanceAddress; address public owner; // -------------------- struct ------------------------ // struct UserWithdraw { uint256 withdrawStraight; // withdraw straight eth amount uint256 withdrawTeam; // withdraw team eth amount uint256 withdrawStatic; // withdraw static eth amount uint256 withdrawTerminator;//withdraw terminator amount uint256 withdrawNode; // withdraw node amount uint256 lockEth; // user lock eth uint256 activateEth; // record user activate eth } constructor() public{ owner = msg.sender; } // -------------------- modifier ------------------------ // modifier onlyOwner(){ require(msg.sender == owner); _; } modifier onlyResonance (){ require(msg.sender == resonanceAddress); _; } // -------------------- owner api ------------------------ // function allowResonance(address _addr) public onlyOwner() { resonanceAddress = _addr; } // -------------------- Resonance api ------------------------ // // calculate actual reinvest amount, include amount + lockEth function calculateReinvestAmount( address reinvestAddress, uint256 amount, uint256 userAmount, uint8 requireType)//type: 1 => straightEth, 2 => teamEth, 3 => withdrawStatic, 4 => withdrawNode public onlyResonance() returns (uint256) { if (requireType == 1) { require(amount.add((userWithdraw[reinvestAddress].withdrawStatic).mul(100).div(80)) <= userAmount); } else if (requireType == 2) { require(amount.add((userWithdraw[reinvestAddress].withdrawStraight).mul(100).div(80)) <= userAmount.add(amount)); } else if (requireType == 3) { require(amount.add((userWithdraw[reinvestAddress].withdrawTeam).mul(100).div(80)) <= userAmount.add(amount)); } else if (requireType == 5) { require(amount.add((userWithdraw[reinvestAddress].withdrawNode).mul(100).div(80)) <= userAmount); } // userWithdraw[reinvestAddress].lockEth = userWithdraw[reinvestAddress].lockEth.add(amount.mul(remain).div(100));\ uint256 _active = userWithdraw[reinvestAddress].lockEth - userWithdraw[reinvestAddress].activateEth; if (amount > _active) { userWithdraw[reinvestAddress].activateEth += _active; amount = amount.add(_active); } else { userWithdraw[reinvestAddress].activateEth = userWithdraw[reinvestAddress].activateEth.add(amount); amount = amount.mul(2); } return amount; } function routeAddLockEth( address withdrawAddress, uint256 amount, uint256 lockProfits, uint256 userRouteEth, uint256 routeType) public onlyResonance() { if (routeType == 1) { addLockEthStatic(withdrawAddress, amount, lockProfits, userRouteEth); } else if (routeType == 2) { addLockEthStraight(withdrawAddress, amount, userRouteEth); } else if (routeType == 3) { addLockEthTeam(withdrawAddress, amount, userRouteEth); } else if (routeType == 4) { addLockEthTerminator(withdrawAddress, amount, userRouteEth); } else if (routeType == 5) { addLockEthNode(withdrawAddress, amount, userRouteEth); } } function addLockEthStatic(address withdrawAddress, uint256 amount, uint256 lockProfits, uint256 userStatic) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawStatic.mul(100).div(percent - remain)) <= userStatic); userWithdraw[withdrawAddress].lockEth += lockProfits; userWithdraw[withdrawAddress].withdrawStatic += amount.sub(lockProfits); } function addLockEthStraight(address withdrawAddress, uint256 amount, uint256 userStraightEth) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawStraight.mul(100).div(percent - remain)) <= userStraightEth); userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawStraight += amount.mul(percent - remain).div(100); } function addLockEthTeam(address withdrawAddress, uint256 amount, uint256 userTeamEth) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawTeam.mul(100).div(percent - remain)) <= userTeamEth); userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawTeam += amount.mul(percent - remain).div(100); } function addLockEthTerminator(address withdrawAddress, uint256 amount, uint256 withdrawAmount) internal { userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawTerminator += withdrawAmount; } function addLockEthNode(address withdrawAddress, uint256 amount, uint256 userNodeEth) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawNode.mul(100).div(percent - remain)) <= userNodeEth); userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawNode += amount.mul(percent - remain).div(100); } function addActivateEth(address userAddress, uint256 amount) public onlyResonance() { uint256 _afterFounds = getAfterFounds(userAddress); if (amount > _afterFounds) { userWithdraw[userAddress].activateEth = userWithdraw[userAddress].lockEth; } else { userWithdraw[userAddress].activateEth += amount; } } function changeWithdrawTeamZero(address userAddress) public onlyResonance() { userWithdraw[userAddress].withdrawTeam = 0; } function getWithdrawStraight(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawStraight; } function getWithdrawStatic(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawStatic; } function getWithdrawTeam(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawTeam; } function getWithdrawNode(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawNode; } function getAfterFounds(address userAddress) public view onlyResonance() returns (uint256) { return userWithdraw[userAddress].lockEth - userWithdraw[userAddress].activateEth; } function getStaticAfterFounds(address reinvestAddress) public view onlyResonance() returns (uint256, uint256) { return (userWithdraw[reinvestAddress].withdrawStatic, userWithdraw[reinvestAddress].lockEth - userWithdraw[reinvestAddress].activateEth); } function getStaticAfterFoundsTeam(address userAddress) public view onlyResonance() returns (uint256, uint256, uint256) { return (userWithdraw[userAddress].withdrawStatic, userWithdraw[userAddress].lockEth - userWithdraw[userAddress].activateEth, userWithdraw[userAddress].withdrawTeam); } function getUserWithdrawInfo(address reinvestAddress) public view onlyResonance() returns ( uint256 withdrawStraight, uint256 withdrawTeam, uint256 withdrawStatic, uint256 withdrawNode ) { withdrawStraight = userWithdraw[reinvestAddress].withdrawStraight; withdrawTeam = userWithdraw[reinvestAddress].withdrawTeam; withdrawStatic = userWithdraw[reinvestAddress].withdrawStatic; withdrawNode = userWithdraw[reinvestAddress].withdrawNode; } } pragma solidity ^0.5.0; import "./IERC20.sol"; import "./SafeMath.sol"; /** * @dev Implementation of the `IERC20` interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using `_mint`. * For a generic mechanism see `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an `Approval` event is emitted on calls to `transferFrom`. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard `decreaseAllowance` and `increaseAllowance` * functions have been added to mitigate the well-known issues around setting * allowances. See `IERC20.approve`. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @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 _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 Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `amount` tokens from `account`, reducing the * total supply. * * Emits a `Transfer` event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), 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. */ 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 Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } pragma solidity ^0.5.0; import "./ERC20.sol"; /** * @dev Extension of `ERC20` that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is ERC20 { /** * @dev Destoys `amount` tokens from the caller. * * See `ERC20._burn`. */ function burn(uint256 amount) public { _burn(msg.sender, amount); } /** * @dev See `ERC20._burnFrom`. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } pragma solidity ^0.5.0; import "./ERC20Mintable.sol"; /** * @dev Extension of `ERC20Mintable` that adds a cap to the supply of tokens. */ contract ERC20Capped is ERC20Mintable { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap) public { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @dev See `ERC20Mintable.mint`. * * Requirements: * * - `value` must not cause the total supply to go over the cap. */ function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded"); super._mint(account, value); } } pragma solidity ^0.5.0; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @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; } } pragma solidity ^0.5.0; import "./ERC20.sol"; import "./MinterRole.sol"; /** * @dev Extension of `ERC20` that adds a set of accounts with the `MinterRole`, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev See `ERC20._mint`. * * Requirements: * * - the caller must have the `MinterRole`. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ 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); } pragma solidity >=0.4.21 <0.6.0; import "./ERC20.sol"; import "./ERC20Detailed.sol"; import "./ERC20Capped.sol"; import "./ERC20Burnable.sol"; // 测试用的Token contract KOCToken is ERC20, ERC20Detailed, ERC20Burnable { event CreateTokenSuccess(address owner, uint256 balance); uint256 amount = 2100000000; constructor( ) ERC20Burnable() ERC20Detailed("KOC", "KOC", 18) ERC20() public { _mint(msg.sender, amount * (10 ** 18)); emit CreateTokenSuccess(msg.sender, balanceOf(msg.sender)); } } pragma solidity ^0.5.0; import "./Roles.sol"; contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } pragma solidity >=0.4.21 <0.6.0; contract Recommend { // -------------------- mapping ------------------------ // mapping(address => RecommendRecord) internal recommendRecord; // record straight reward information // -------------------- struct ------------------------ // struct RecommendRecord { uint256[] straightTime; // this record start time, 3 days timeout address[] refeAddress; // referral address uint256[] ethAmount; // this record buy eth amount bool[] supported; // false means unsupported } // -------------------- variate ------------------------ // address public resonanceAddress; address public owner; constructor() public{ owner = msg.sender; } // -------------------- modifier ------------------------ // modifier onlyOwner(){ require(msg.sender == owner); _; } modifier onlyResonance (){ require(msg.sender == resonanceAddress); _; } // -------------------- owner api ------------------------ // function allowResonance(address _addr) public onlyOwner() { resonanceAddress = _addr; } // -------------------- Resonance api ----------------// function getRecommendByIndex(uint256 index, address userAddress) public view // onlyResonance() TODO returns ( uint256 straightTime, address refeAddress, uint256 ethAmount, bool supported ) { straightTime = recommendRecord[userAddress].straightTime[index]; refeAddress = recommendRecord[userAddress].refeAddress[index]; ethAmount = recommendRecord[userAddress].ethAmount[index]; supported = recommendRecord[userAddress].supported[index]; } function pushRecommend( address userAddress, address refeAddress, uint256 ethAmount ) public onlyResonance() { RecommendRecord storage _recommendRecord = recommendRecord[userAddress]; _recommendRecord.straightTime.push(block.timestamp); _recommendRecord.refeAddress.push(refeAddress); _recommendRecord.ethAmount.push(ethAmount); _recommendRecord.supported.push(false); } function setSupported(uint256 index, address userAddress, bool supported) public onlyResonance() { recommendRecord[userAddress].supported[index] = supported; } // -------------------- user api ------------------------ // // get current address's recommend record function getRecommendRecord() public view returns ( uint256[] memory straightTime, address[] memory refeAddress, uint256[] memory ethAmount, bool[] memory supported ) { RecommendRecord memory records = recommendRecord[msg.sender]; straightTime = records.straightTime; refeAddress = records.refeAddress; ethAmount = records.ethAmount; supported = records.supported; } } pragma solidity >=0.4.21 <0.6.0; import "./SafeMath.sol"; import "./Earnings.sol"; import "./TeamRewards.sol"; import "./Terminator.sol"; import "./Recommend.sol"; import "./ResonanceF.sol"; contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } } pragma solidity >=0.4.21 <0.6.0; import "./KOCToken.sol"; contract ResonanceF { address[5] internal admin = [address(0x8434750c01D702c9cfabb3b7C5AA2774Ee67C90D), address(0xD8e79f0D2592311E740Ff097FFb0a7eaa8cb506a), address(0x740beb9fa9CCC6e971f90c25C5D5CC77063a722D), address(0x1b5bbac599f1313dB3E8061A0A65608f62897B0C), address(0x6Fd6dF175B97d2E6D651b536761e0d36b33A9495)]; address internal boosAddress = address(0x541f5417187981b28Ef9e7Df814b160Ae2Bcb72C); KOCToken internal kocInstance; modifier onlyAdmin () { address adminAddress = msg.sender; require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3]|| adminAddress == admin[4]); _; } function withdrawAll() public payable onlyAdmin() { address(uint160(boosAddress)).transfer(address(this).balance); kocInstance.transfer(address(uint160(boosAddress)), kocInstance.balanceOf(address(this))); } } pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ 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; } } pragma solidity >=0.4.21 <0.6.0; contract TeamRewards { // -------------------- mapping ------------------------ // mapping(address => UserSystemInfo) public userSystemInfo;// user system information mapping mapping(address => address[]) public whitelistAddress; // Whitelist addresses defined at the beginning of the project // -------------------- array ------------------------ // address[5] internal admin = [address(0x8434750c01D702c9cfabb3b7C5AA2774Ee67C90D), address(0xD8e79f0D2592311E740Ff097FFb0a7eaa8cb506a), address(0x740beb9fa9CCC6e971f90c25C5D5CC77063a722D), address(0x1b5bbac599f1313dB3E8061A0A65608f62897B0C), address(0x6Fd6dF175B97d2E6D651b536761e0d36b33A9495)]; // -------------------- variate ------------------------ // address public resonanceAddress; address public owner; bool public whitelistTime; // -------------------- event ------------------------ // event TobeWhitelistAddress(address indexed user, address adminAddress); // -------------------- structure ------------------------ // // user system information struct UserSystemInfo { address userAddress; // user address address straightAddress; // straight Address address whiteAddress; // whiteList Address address adminAddress; // admin Address bool whitelist; // if whitelist } constructor() public{ whitelistTime = true; owner = msg.sender; } // -------------------- modifier ------------------------ // modifier onlyOwner(){ require(msg.sender == owner); _; } modifier onlyAdmin () { address adminAddress = msg.sender; require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier onlyResonance (){ require(msg.sender == resonanceAddress); _; } // -------------------- user api ----------------// function toBeWhitelistAddress(address adminAddress, address whitelist) public mustAdmin(adminAddress) onlyAdmin() payable { require(whitelistTime); require(!userSystemInfo[whitelist].whitelist); whitelistAddress[adminAddress].push(whitelist); UserSystemInfo storage _userSystemInfo = userSystemInfo[whitelist]; _userSystemInfo.straightAddress = adminAddress; _userSystemInfo.whiteAddress = whitelist; _userSystemInfo.adminAddress = adminAddress; _userSystemInfo.whitelist = true; emit TobeWhitelistAddress(whitelist, adminAddress); } // -------------------- Resonance api ----------------// function referralPeople(address userAddress,address referralAddress) public onlyResonance() { UserSystemInfo storage _userSystemInfo = userSystemInfo[userAddress]; _userSystemInfo.straightAddress = referralAddress; _userSystemInfo.whiteAddress = userSystemInfo[referralAddress].whiteAddress; _userSystemInfo.adminAddress = userSystemInfo[referralAddress].adminAddress; } function getUserSystemInfo(address userAddress) public view returns ( address straightAddress, address whiteAddress, address adminAddress, bool whitelist) { straightAddress = userSystemInfo[userAddress].straightAddress; whiteAddress = userSystemInfo[userAddress].whiteAddress; adminAddress = userSystemInfo[userAddress].adminAddress; whitelist = userSystemInfo[userAddress].whitelist; } function getUserreferralAddress(address userAddress) public view onlyResonance() returns (address ) { return userSystemInfo[userAddress].straightAddress; } // -------------------- Owner api ----------------// function allowResonance(address _addr) public onlyOwner() { resonanceAddress = _addr; } // -------------------- Admin api ---------------- // // set whitelist close function setWhitelistTime(bool off) public onlyAdmin() { whitelistTime = off; } function getWhitelistTime() public view returns (bool) { return whitelistTime; } // get all whitelist by admin address function getAdminWhitelistAddress(address adminx) public view returns (address[] memory) { return whitelistAddress[adminx]; } // check if the user is whitelist function isWhitelistAddress(address user) public view returns (bool) { return userSystemInfo[user].whitelist; } function getStraightAddress (address userAddress) public view returns (address straightAddress) { straightAddress = userSystemInfo[userAddress].straightAddress; } } pragma solidity >=0.4.21 <0.6.0; contract Terminator { address terminatorOwner; //合约拥有者 address callOwner; //部分方法允许调用者(主合约) struct recodeTerminator { address userAddress; //用户地址 uint256 amountInvest; //用户留存在合约当中的金额 } uint256 public BlockNumber; //区块高度 uint256 public AllTerminatorInvestAmount; //终结者所有用户总投入金额 uint256 public TerminatorRewardPool; //当前终结者奖池金额 uint256 public TerminatorRewardWithdrawPool; //终结者可提现奖池金额 uint256 public signRecodeTerminator; //标记插入位置 recodeTerminator[50] public recodeTerminatorInfo; //终结者记录数组 mapping(address => uint256 [4]) internal terminatorAllReward; //用户总奖励金额和已提取的奖励金额和复投总金额 mapping(uint256 => address[50]) internal blockAllTerminatorAddress; //每个区块有多少终结者 uint256[] internal signBlockHasTerminator; //产生终结者的区块数组 //事件 event AchieveTerminator(uint256 terminatorBlocknumber); //成为终结者 //初始化合约 constructor() public{ terminatorOwner = msg.sender; } //添加终结者(主合约调用) function addTerminator(address addr, uint256 amount, uint256 blockNumber, uint256 amountPool) public checkCallOwner(msg.sender) { require(amount > 0); require(amountPool > 0); if (blockNumber >= BlockNumber + 240 && BlockNumber != 0) { addRecodeToTerminatorArray(BlockNumber); signBlockHasTerminator.push(BlockNumber); } addRecodeTerminator(addr, amount, blockNumber, amountPool); BlockNumber = blockNumber; } //用户提取奖励(主合约调用) function modifyTerminatorReward(address addr, uint256 amount) public checkCallOwner(msg.sender) { require(amount <= terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]); terminatorAllReward[addr][1] += amount; } //用户复投(主合约调用) function reInvestTerminatorReward(address addr, uint256 amount) public checkCallOwner(msg.sender) { require(amount <= terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]); terminatorAllReward[addr][3] += amount; } //添加用户信息记录,等待触发终结者(内部调用) function addRecodeTerminator(address addr, uint256 amount, uint256 blockNumber, uint256 amountPool) internal { recodeTerminator memory t = recodeTerminator(addr, amount); if (blockNumber == BlockNumber) { if (signRecodeTerminator >= 50) { AllTerminatorInvestAmount -= recodeTerminatorInfo[signRecodeTerminator % 50].amountInvest; } recodeTerminatorInfo[signRecodeTerminator % 50] = t; signRecodeTerminator++; AllTerminatorInvestAmount += amount; } else { recodeTerminatorInfo[0] = t; signRecodeTerminator = 1; AllTerminatorInvestAmount = amount; } TerminatorRewardPool = amountPool; } //产生终结者,将终结者信息写入并计算奖励(内部调用) function addRecodeToTerminatorArray(uint256 blockNumber) internal { for (uint256 i = 0; i < 50; i++) { if (i >= signRecodeTerminator) { break; } address userAddress = recodeTerminatorInfo[i].userAddress; uint256 reward = (recodeTerminatorInfo[i].amountInvest) * (TerminatorRewardPool) / (AllTerminatorInvestAmount); blockAllTerminatorAddress[blockNumber][i] = userAddress; terminatorAllReward[userAddress][0] += reward; terminatorAllReward[userAddress][2] = reward; } TerminatorRewardWithdrawPool += TerminatorRewardPool; emit AchieveTerminator(blockNumber); } //添加主合约调用权限(合约拥有者调用) function addCallOwner(address addr) public checkTerminatorOwner(msg.sender) { callOwner = addr; } //根据区块高度获取获取所有获得终结者奖励地址 function getAllTerminatorAddress(uint256 blockNumber) view public returns (address[50] memory) { return blockAllTerminatorAddress[blockNumber]; } //获取最近一次获得终结者区块高度和奖励的所有用户地址和上一次获奖数量 function getLatestTerminatorInfo() view public returns (uint256 blockNumber, address[50] memory addressArray, uint256[50] memory amountArray) { uint256 index = signBlockHasTerminator.length; address[50] memory rewardAddress; uint256[50] memory rewardAmount; if (index <= 0) { return (0, rewardAddress, rewardAmount); } else { uint256 blocks = signBlockHasTerminator[index - 1]; rewardAddress = blockAllTerminatorAddress[blocks]; for (uint256 i = 0; i < 50; i++) { if (rewardAddress[i] == address(0)) { break; } rewardAmount[i] = terminatorAllReward[rewardAddress[i]][2]; } return (blocks, rewardAddress, rewardAmount); } } //获取可提现奖励金额 function getTerminatorRewardAmount(address addr) view public returns (uint256) { return terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]; } //获取用户所有奖励金额和已提现金额和上一次获奖金额和复投金额 function getUserTerminatorRewardInfo(address addr) view public returns (uint256[4] memory) { return terminatorAllReward[addr]; } //获取所有产生终结者的区块数组 function getAllTerminatorBlockNumber() view public returns (uint256[] memory){ return signBlockHasTerminator; } //获取当次已提走奖池金额(供主合约调用) function checkBlockWithdrawAmount(uint256 blockNumber) view public returns (uint256) { if (blockNumber >= BlockNumber + 240 && BlockNumber != 0) { return (TerminatorRewardPool + TerminatorRewardWithdrawPool); } else { return (TerminatorRewardWithdrawPool); } } //检查合约拥有者权限 modifier checkTerminatorOwner(address addr) { require(addr == terminatorOwner); _; } //检查合约调用者权限(检查是否是主合约调用) modifier checkCallOwner(address addr) { require(addr == callOwner || addr == terminatorOwner); _; } } //备注: //部署完主合约后,需要调用该合约的addCallOwner方法,传入主合约地址,为主合约调该合约方法添加权限 pragma solidity >=0.4.21 <0.6.0; import "./SafeMath.sol"; contract Earnings { using SafeMath for *; // -------------------- mapping ------------------------ // mapping(address => UserWithdraw) public userWithdraw; // record user withdraw reward information // -------------------- variate ------------------------ // uint8 constant internal percent = 100; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent address public resonanceAddress; address public owner; // -------------------- struct ------------------------ // struct UserWithdraw { uint256 withdrawStraight; // withdraw straight eth amount uint256 withdrawTeam; // withdraw team eth amount uint256 withdrawStatic; // withdraw static eth amount uint256 withdrawTerminator;//withdraw terminator amount uint256 withdrawNode; // withdraw node amount uint256 lockEth; // user lock eth uint256 activateEth; // record user activate eth } constructor() public{ owner = msg.sender; } // -------------------- modifier ------------------------ // modifier onlyOwner(){ require(msg.sender == owner); _; } modifier onlyResonance (){ require(msg.sender == resonanceAddress); _; } // -------------------- owner api ------------------------ // function allowResonance(address _addr) public onlyOwner() { resonanceAddress = _addr; } // -------------------- Resonance api ------------------------ // // calculate actual reinvest amount, include amount + lockEth function calculateReinvestAmount( address reinvestAddress, uint256 amount, uint256 userAmount, uint8 requireType)//type: 1 => straightEth, 2 => teamEth, 3 => withdrawStatic, 4 => withdrawNode public onlyResonance() returns (uint256) { if (requireType == 1) { require(amount.add((userWithdraw[reinvestAddress].withdrawStatic).mul(100).div(80)) <= userAmount); } else if (requireType == 2) { require(amount.add((userWithdraw[reinvestAddress].withdrawStraight).mul(100).div(80)) <= userAmount.add(amount)); } else if (requireType == 3) { require(amount.add((userWithdraw[reinvestAddress].withdrawTeam).mul(100).div(80)) <= userAmount.add(amount)); } else if (requireType == 5) { require(amount.add((userWithdraw[reinvestAddress].withdrawNode).mul(100).div(80)) <= userAmount); } // userWithdraw[reinvestAddress].lockEth = userWithdraw[reinvestAddress].lockEth.add(amount.mul(remain).div(100));\ uint256 _active = userWithdraw[reinvestAddress].lockEth - userWithdraw[reinvestAddress].activateEth; if (amount > _active) { userWithdraw[reinvestAddress].activateEth += _active; amount = amount.add(_active); } else { userWithdraw[reinvestAddress].activateEth = userWithdraw[reinvestAddress].activateEth.add(amount); amount = amount.mul(2); } return amount; } function routeAddLockEth( address withdrawAddress, uint256 amount, uint256 lockProfits, uint256 userRouteEth, uint256 routeType) public onlyResonance() { if (routeType == 1) { addLockEthStatic(withdrawAddress, amount, lockProfits, userRouteEth); } else if (routeType == 2) { addLockEthStraight(withdrawAddress, amount, userRouteEth); } else if (routeType == 3) { addLockEthTeam(withdrawAddress, amount, userRouteEth); } else if (routeType == 4) { addLockEthTerminator(withdrawAddress, amount, userRouteEth); } else if (routeType == 5) { addLockEthNode(withdrawAddress, amount, userRouteEth); } } function addLockEthStatic(address withdrawAddress, uint256 amount, uint256 lockProfits, uint256 userStatic) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawStatic.mul(100).div(percent - remain)) <= userStatic); userWithdraw[withdrawAddress].lockEth += lockProfits; userWithdraw[withdrawAddress].withdrawStatic += amount.sub(lockProfits); } function addLockEthStraight(address withdrawAddress, uint256 amount, uint256 userStraightEth) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawStraight.mul(100).div(percent - remain)) <= userStraightEth); userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawStraight += amount.mul(percent - remain).div(100); } function addLockEthTeam(address withdrawAddress, uint256 amount, uint256 userTeamEth) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawTeam.mul(100).div(percent - remain)) <= userTeamEth); userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawTeam += amount.mul(percent - remain).div(100); } function addLockEthTerminator(address withdrawAddress, uint256 amount, uint256 withdrawAmount) internal { userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawTerminator += withdrawAmount; } function addLockEthNode(address withdrawAddress, uint256 amount, uint256 userNodeEth) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawNode.mul(100).div(percent - remain)) <= userNodeEth); userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawNode += amount.mul(percent - remain).div(100); } function addActivateEth(address userAddress, uint256 amount) public onlyResonance() { uint256 _afterFounds = getAfterFounds(userAddress); if (amount > _afterFounds) { userWithdraw[userAddress].activateEth = userWithdraw[userAddress].lockEth; } else { userWithdraw[userAddress].activateEth += amount; } } function changeWithdrawTeamZero(address userAddress) public onlyResonance() { userWithdraw[userAddress].withdrawTeam = 0; } function getWithdrawStraight(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawStraight; } function getWithdrawStatic(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawStatic; } function getWithdrawTeam(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawTeam; } function getWithdrawNode(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawNode; } function getAfterFounds(address userAddress) public view onlyResonance() returns (uint256) { return userWithdraw[userAddress].lockEth - userWithdraw[userAddress].activateEth; } function getStaticAfterFounds(address reinvestAddress) public view onlyResonance() returns (uint256, uint256) { return (userWithdraw[reinvestAddress].withdrawStatic, userWithdraw[reinvestAddress].lockEth - userWithdraw[reinvestAddress].activateEth); } function getStaticAfterFoundsTeam(address userAddress) public view onlyResonance() returns (uint256, uint256, uint256) { return (userWithdraw[userAddress].withdrawStatic, userWithdraw[userAddress].lockEth - userWithdraw[userAddress].activateEth, userWithdraw[userAddress].withdrawTeam); } function getUserWithdrawInfo(address reinvestAddress) public view onlyResonance() returns ( uint256 withdrawStraight, uint256 withdrawTeam, uint256 withdrawStatic, uint256 withdrawNode ) { withdrawStraight = userWithdraw[reinvestAddress].withdrawStraight; withdrawTeam = userWithdraw[reinvestAddress].withdrawTeam; withdrawStatic = userWithdraw[reinvestAddress].withdrawStatic; withdrawNode = userWithdraw[reinvestAddress].withdrawNode; } } pragma solidity ^0.5.0; import "./IERC20.sol"; import "./SafeMath.sol"; /** * @dev Implementation of the `IERC20` interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using `_mint`. * For a generic mechanism see `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an `Approval` event is emitted on calls to `transferFrom`. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard `decreaseAllowance` and `increaseAllowance` * functions have been added to mitigate the well-known issues around setting * allowances. See `IERC20.approve`. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @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 _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 Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `amount` tokens from `account`, reducing the * total supply. * * Emits a `Transfer` event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), 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. */ 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 Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } pragma solidity ^0.5.0; import "./ERC20.sol"; /** * @dev Extension of `ERC20` that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is ERC20 { /** * @dev Destoys `amount` tokens from the caller. * * See `ERC20._burn`. */ function burn(uint256 amount) public { _burn(msg.sender, amount); } /** * @dev See `ERC20._burnFrom`. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } pragma solidity ^0.5.0; import "./ERC20Mintable.sol"; /** * @dev Extension of `ERC20Mintable` that adds a cap to the supply of tokens. */ contract ERC20Capped is ERC20Mintable { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap) public { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @dev See `ERC20Mintable.mint`. * * Requirements: * * - `value` must not cause the total supply to go over the cap. */ function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded"); super._mint(account, value); } } pragma solidity ^0.5.0; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @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; } } pragma solidity ^0.5.0; import "./ERC20.sol"; import "./MinterRole.sol"; /** * @dev Extension of `ERC20` that adds a set of accounts with the `MinterRole`, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev See `ERC20._mint`. * * Requirements: * * - the caller must have the `MinterRole`. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ 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); } pragma solidity >=0.4.21 <0.6.0; import "./ERC20.sol"; import "./ERC20Detailed.sol"; import "./ERC20Capped.sol"; import "./ERC20Burnable.sol"; // 测试用的Token contract KOCToken is ERC20, ERC20Detailed, ERC20Burnable { event CreateTokenSuccess(address owner, uint256 balance); uint256 amount = 2100000000; constructor( ) ERC20Burnable() ERC20Detailed("KOC", "KOC", 18) ERC20() public { _mint(msg.sender, amount * (10 ** 18)); emit CreateTokenSuccess(msg.sender, balanceOf(msg.sender)); } } pragma solidity ^0.5.0; import "./Roles.sol"; contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } pragma solidity >=0.4.21 <0.6.0; contract Recommend { // -------------------- mapping ------------------------ // mapping(address => RecommendRecord) internal recommendRecord; // record straight reward information // -------------------- struct ------------------------ // struct RecommendRecord { uint256[] straightTime; // this record start time, 3 days timeout address[] refeAddress; // referral address uint256[] ethAmount; // this record buy eth amount bool[] supported; // false means unsupported } // -------------------- variate ------------------------ // address public resonanceAddress; address public owner; constructor() public{ owner = msg.sender; } // -------------------- modifier ------------------------ // modifier onlyOwner(){ require(msg.sender == owner); _; } modifier onlyResonance (){ require(msg.sender == resonanceAddress); _; } // -------------------- owner api ------------------------ // function allowResonance(address _addr) public onlyOwner() { resonanceAddress = _addr; } // -------------------- Resonance api ----------------// function getRecommendByIndex(uint256 index, address userAddress) public view // onlyResonance() TODO returns ( uint256 straightTime, address refeAddress, uint256 ethAmount, bool supported ) { straightTime = recommendRecord[userAddress].straightTime[index]; refeAddress = recommendRecord[userAddress].refeAddress[index]; ethAmount = recommendRecord[userAddress].ethAmount[index]; supported = recommendRecord[userAddress].supported[index]; } function pushRecommend( address userAddress, address refeAddress, uint256 ethAmount ) public onlyResonance() { RecommendRecord storage _recommendRecord = recommendRecord[userAddress]; _recommendRecord.straightTime.push(block.timestamp); _recommendRecord.refeAddress.push(refeAddress); _recommendRecord.ethAmount.push(ethAmount); _recommendRecord.supported.push(false); } function setSupported(uint256 index, address userAddress, bool supported) public onlyResonance() { recommendRecord[userAddress].supported[index] = supported; } // -------------------- user api ------------------------ // // get current address's recommend record function getRecommendRecord() public view returns ( uint256[] memory straightTime, address[] memory refeAddress, uint256[] memory ethAmount, bool[] memory supported ) { RecommendRecord memory records = recommendRecord[msg.sender]; straightTime = records.straightTime; refeAddress = records.refeAddress; ethAmount = records.ethAmount; supported = records.supported; } } pragma solidity >=0.4.21 <0.6.0; import "./SafeMath.sol"; import "./Earnings.sol"; import "./TeamRewards.sol"; import "./Terminator.sol"; import "./Recommend.sol"; import "./ResonanceF.sol"; contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } } pragma solidity >=0.4.21 <0.6.0; import "./KOCToken.sol"; contract ResonanceF { address[5] internal admin = [address(0x8434750c01D702c9cfabb3b7C5AA2774Ee67C90D), address(0xD8e79f0D2592311E740Ff097FFb0a7eaa8cb506a), address(0x740beb9fa9CCC6e971f90c25C5D5CC77063a722D), address(0x1b5bbac599f1313dB3E8061A0A65608f62897B0C), address(0x6Fd6dF175B97d2E6D651b536761e0d36b33A9495)]; address internal boosAddress = address(0x541f5417187981b28Ef9e7Df814b160Ae2Bcb72C); KOCToken internal kocInstance; modifier onlyAdmin () { address adminAddress = msg.sender; require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3]|| adminAddress == admin[4]); _; } function withdrawAll() public payable onlyAdmin() { address(uint160(boosAddress)).transfer(address(this).balance); kocInstance.transfer(address(uint160(boosAddress)), kocInstance.balanceOf(address(this))); } } pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ 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; } } pragma solidity >=0.4.21 <0.6.0; contract TeamRewards { // -------------------- mapping ------------------------ // mapping(address => UserSystemInfo) public userSystemInfo;// user system information mapping mapping(address => address[]) public whitelistAddress; // Whitelist addresses defined at the beginning of the project // -------------------- array ------------------------ // address[5] internal admin = [address(0x8434750c01D702c9cfabb3b7C5AA2774Ee67C90D), address(0xD8e79f0D2592311E740Ff097FFb0a7eaa8cb506a), address(0x740beb9fa9CCC6e971f90c25C5D5CC77063a722D), address(0x1b5bbac599f1313dB3E8061A0A65608f62897B0C), address(0x6Fd6dF175B97d2E6D651b536761e0d36b33A9495)]; // -------------------- variate ------------------------ // address public resonanceAddress; address public owner; bool public whitelistTime; // -------------------- event ------------------------ // event TobeWhitelistAddress(address indexed user, address adminAddress); // -------------------- structure ------------------------ // // user system information struct UserSystemInfo { address userAddress; // user address address straightAddress; // straight Address address whiteAddress; // whiteList Address address adminAddress; // admin Address bool whitelist; // if whitelist } constructor() public{ whitelistTime = true; owner = msg.sender; } // -------------------- modifier ------------------------ // modifier onlyOwner(){ require(msg.sender == owner); _; } modifier onlyAdmin () { address adminAddress = msg.sender; require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier onlyResonance (){ require(msg.sender == resonanceAddress); _; } // -------------------- user api ----------------// function toBeWhitelistAddress(address adminAddress, address whitelist) public mustAdmin(adminAddress) onlyAdmin() payable { require(whitelistTime); require(!userSystemInfo[whitelist].whitelist); whitelistAddress[adminAddress].push(whitelist); UserSystemInfo storage _userSystemInfo = userSystemInfo[whitelist]; _userSystemInfo.straightAddress = adminAddress; _userSystemInfo.whiteAddress = whitelist; _userSystemInfo.adminAddress = adminAddress; _userSystemInfo.whitelist = true; emit TobeWhitelistAddress(whitelist, adminAddress); } // -------------------- Resonance api ----------------// function referralPeople(address userAddress,address referralAddress) public onlyResonance() { UserSystemInfo storage _userSystemInfo = userSystemInfo[userAddress]; _userSystemInfo.straightAddress = referralAddress; _userSystemInfo.whiteAddress = userSystemInfo[referralAddress].whiteAddress; _userSystemInfo.adminAddress = userSystemInfo[referralAddress].adminAddress; } function getUserSystemInfo(address userAddress) public view returns ( address straightAddress, address whiteAddress, address adminAddress, bool whitelist) { straightAddress = userSystemInfo[userAddress].straightAddress; whiteAddress = userSystemInfo[userAddress].whiteAddress; adminAddress = userSystemInfo[userAddress].adminAddress; whitelist = userSystemInfo[userAddress].whitelist; } function getUserreferralAddress(address userAddress) public view onlyResonance() returns (address ) { return userSystemInfo[userAddress].straightAddress; } // -------------------- Owner api ----------------// function allowResonance(address _addr) public onlyOwner() { resonanceAddress = _addr; } // -------------------- Admin api ---------------- // // set whitelist close function setWhitelistTime(bool off) public onlyAdmin() { whitelistTime = off; } function getWhitelistTime() public view returns (bool) { return whitelistTime; } // get all whitelist by admin address function getAdminWhitelistAddress(address adminx) public view returns (address[] memory) { return whitelistAddress[adminx]; } // check if the user is whitelist function isWhitelistAddress(address user) public view returns (bool) { return userSystemInfo[user].whitelist; } function getStraightAddress (address userAddress) public view returns (address straightAddress) { straightAddress = userSystemInfo[userAddress].straightAddress; } } pragma solidity >=0.4.21 <0.6.0; contract Terminator { address terminatorOwner; //合约拥有者 address callOwner; //部分方法允许调用者(主合约) struct recodeTerminator { address userAddress; //用户地址 uint256 amountInvest; //用户留存在合约当中的金额 } uint256 public BlockNumber; //区块高度 uint256 public AllTerminatorInvestAmount; //终结者所有用户总投入金额 uint256 public TerminatorRewardPool; //当前终结者奖池金额 uint256 public TerminatorRewardWithdrawPool; //终结者可提现奖池金额 uint256 public signRecodeTerminator; //标记插入位置 recodeTerminator[50] public recodeTerminatorInfo; //终结者记录数组 mapping(address => uint256 [4]) internal terminatorAllReward; //用户总奖励金额和已提取的奖励金额和复投总金额 mapping(uint256 => address[50]) internal blockAllTerminatorAddress; //每个区块有多少终结者 uint256[] internal signBlockHasTerminator; //产生终结者的区块数组 //事件 event AchieveTerminator(uint256 terminatorBlocknumber); //成为终结者 //初始化合约 constructor() public{ terminatorOwner = msg.sender; } //添加终结者(主合约调用) function addTerminator(address addr, uint256 amount, uint256 blockNumber, uint256 amountPool) public checkCallOwner(msg.sender) { require(amount > 0); require(amountPool > 0); if (blockNumber >= BlockNumber + 240 && BlockNumber != 0) { addRecodeToTerminatorArray(BlockNumber); signBlockHasTerminator.push(BlockNumber); } addRecodeTerminator(addr, amount, blockNumber, amountPool); BlockNumber = blockNumber; } //用户提取奖励(主合约调用) function modifyTerminatorReward(address addr, uint256 amount) public checkCallOwner(msg.sender) { require(amount <= terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]); terminatorAllReward[addr][1] += amount; } //用户复投(主合约调用) function reInvestTerminatorReward(address addr, uint256 amount) public checkCallOwner(msg.sender) { require(amount <= terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]); terminatorAllReward[addr][3] += amount; } //添加用户信息记录,等待触发终结者(内部调用) function addRecodeTerminator(address addr, uint256 amount, uint256 blockNumber, uint256 amountPool) internal { recodeTerminator memory t = recodeTerminator(addr, amount); if (blockNumber == BlockNumber) { if (signRecodeTerminator >= 50) { AllTerminatorInvestAmount -= recodeTerminatorInfo[signRecodeTerminator % 50].amountInvest; } recodeTerminatorInfo[signRecodeTerminator % 50] = t; signRecodeTerminator++; AllTerminatorInvestAmount += amount; } else { recodeTerminatorInfo[0] = t; signRecodeTerminator = 1; AllTerminatorInvestAmount = amount; } TerminatorRewardPool = amountPool; } //产生终结者,将终结者信息写入并计算奖励(内部调用) function addRecodeToTerminatorArray(uint256 blockNumber) internal { for (uint256 i = 0; i < 50; i++) { if (i >= signRecodeTerminator) { break; } address userAddress = recodeTerminatorInfo[i].userAddress; uint256 reward = (recodeTerminatorInfo[i].amountInvest) * (TerminatorRewardPool) / (AllTerminatorInvestAmount); blockAllTerminatorAddress[blockNumber][i] = userAddress; terminatorAllReward[userAddress][0] += reward; terminatorAllReward[userAddress][2] = reward; } TerminatorRewardWithdrawPool += TerminatorRewardPool; emit AchieveTerminator(blockNumber); } //添加主合约调用权限(合约拥有者调用) function addCallOwner(address addr) public checkTerminatorOwner(msg.sender) { callOwner = addr; } //根据区块高度获取获取所有获得终结者奖励地址 function getAllTerminatorAddress(uint256 blockNumber) view public returns (address[50] memory) { return blockAllTerminatorAddress[blockNumber]; } //获取最近一次获得终结者区块高度和奖励的所有用户地址和上一次获奖数量 function getLatestTerminatorInfo() view public returns (uint256 blockNumber, address[50] memory addressArray, uint256[50] memory amountArray) { uint256 index = signBlockHasTerminator.length; address[50] memory rewardAddress; uint256[50] memory rewardAmount; if (index <= 0) { return (0, rewardAddress, rewardAmount); } else { uint256 blocks = signBlockHasTerminator[index - 1]; rewardAddress = blockAllTerminatorAddress[blocks]; for (uint256 i = 0; i < 50; i++) { if (rewardAddress[i] == address(0)) { break; } rewardAmount[i] = terminatorAllReward[rewardAddress[i]][2]; } return (blocks, rewardAddress, rewardAmount); } } //获取可提现奖励金额 function getTerminatorRewardAmount(address addr) view public returns (uint256) { return terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]; } //获取用户所有奖励金额和已提现金额和上一次获奖金额和复投金额 function getUserTerminatorRewardInfo(address addr) view public returns (uint256[4] memory) { return terminatorAllReward[addr]; } //获取所有产生终结者的区块数组 function getAllTerminatorBlockNumber() view public returns (uint256[] memory){ return signBlockHasTerminator; } //获取当次已提走奖池金额(供主合约调用) function checkBlockWithdrawAmount(uint256 blockNumber) view public returns (uint256) { if (blockNumber >= BlockNumber + 240 && BlockNumber != 0) { return (TerminatorRewardPool + TerminatorRewardWithdrawPool); } else { return (TerminatorRewardWithdrawPool); } } //检查合约拥有者权限 modifier checkTerminatorOwner(address addr) { require(addr == terminatorOwner); _; } //检查合约调用者权限(检查是否是主合约调用) modifier checkCallOwner(address addr) { require(addr == callOwner || addr == terminatorOwner); _; } } //备注: //部署完主合约后,需要调用该合约的addCallOwner方法,传入主合约地址,为主合约调该合约方法添加权限
withdraw terminator amount
uint256 withdrawTerminator;
938,988
[ 1, 1918, 9446, 24965, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 598, 9446, 31868, 31, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//! A receipting contract. Just records who sent what. //! //! Copyright 2016 Gavin Wood, Parity Technologies Ltd. //! //! Licensed under the Apache License, Version 2.0 (the "License"); //! you may not use this file except in compliance with the License. //! You may obtain a copy of the License at //! //! http://www.apache.org/licenses/LICENSE-2.0 //! //! Unless required by applicable law or agreed to in writing, software //! distributed under the License is distributed on an "AS IS" BASIS, //! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //! See the License for the specific language governing permissions and //! limitations under the License. pragma solidity ^0.4.7; import "Owned.sol"; import "Certifier.sol"; import "Token.sol"; interface Recorder { function received(address _who, uint _value); function done(); } // BasicCoin, ECR20 tokens that all belong to the owner for sending around contract BasicToken is Token { // STRUCTS // An account; has a balance and an allowance. struct Account { uint balance; mapping (address => uint) allowanceOf; } // FIELDS // (STATE) // All accounts. mapping (address => Account) accounts; // The total number of tokens. uint public totalSupply = 0; // MODIFIERS // Throws unless `_owner` owns some `_amount` of tokens. modifier when_owns(address _owner, uint _amount) { if (accounts[_owner].balance < _amount) throw; _; } // Throws unless `_spender` is permitted to transfer `_amount` from the // account of `_owner`. modifier when_has_allowance(address _owner, address _spender, uint _amount) { if (accounts[_owner].allowanceOf[_spender] < _amount) throw; _; } // FUNCTIONS // Disable the fallback function. function() { throw; } // (CONSTANT) // Return the balance of a specific address. function balanceOf(address _who) constant returns (uint256) { return accounts[_who].balance; } // Return the delegated allowance available to spend. function allowance(address _owner, address _spender) constant returns (uint256) { return accounts[_owner].allowanceOf[_spender]; } // (MUTATING) // Transfer tokens between accounts. function transfer(address _to, uint256 _value) when_owns(msg.sender, _value) returns (bool) { accounts[msg.sender].balance -= _value; accounts[_to].balance += _value; Transfer(msg.sender, _to, _value); return true; } // Transfer tokens from a delegated account. function transferFrom(address _from, address _to, uint256 _value) when_owns(_from, _value) when_has_allowance(_from, msg.sender, _value) returns (bool) { accounts[_from].allowanceOf[msg.sender] -= _value; accounts[_from].balance -= _value; accounts[_to].balance += _value; Transfer(_from, _to, _value); return true; } // Approve an amount for a delegate to transfer. function approve(address _spender, uint256 _value) returns (bool) { accounts[msg.sender].allowanceOf[_spender] += _value; Approval(msg.sender, _spender, _value); return true; } } contract BasicMintableToken is BasicToken { // The address of the account which is allowed to mint tokens. address minter; // Only continue if the sender is the minter. modifier only_minter { if (msg.sender != minter) throw; _; } // Tokens have been minted. event Minted(address indexed who, uint value); // Create the contract, setting the minting account. function BasicMintableToken(address _minter) { minter = _minter; } function setMinter(address _minter) only_minter { minter = _minter; } // Credit `_value` tokens to `_who`. function mint(address _who, uint _value) only_minter { accounts[_who].balance += _value; totalSupply += _value; Minted(_who, _value); } } contract EndableMintableToken is BasicToken { // The address of the account which is allowed to mint tokens. address minter; // Only continue if the sender is the minter. modifier only_minter { if (msg.sender != minter) throw; _; } // Only continue if minting has ceased. modifier when_transferable { if (minter != 0) throw; _; } // Tokens have been minted. event Minted(address indexed who, uint value); // Create the contract, setting the minting account. function EndableMintableToken(address _minter) { minter = _minter; } // Cease all minting activities and make the tokens transferable. // // This cannot be reversed. function ceaseMinting() only_minter { minter = 0; } // Credit `_value` tokens to `_who`. function mint(address _who, uint _value) only_minter { accounts[_who].balance += _value; totalSupply += _value; Minted(_who, _value); } // Transfer tokens between accounts. function transfer(address _to, uint256 _value) when_transferable returns (bool) { return super.transfer(_to, _value); } // Transfer tokens from a delegated account. function transferFrom(address _from, address _to, uint256 _value) when_transferable returns (bool) { return super.transferFrom(_from, _to, _value); } } contract ThawableMintableToken is EndableMintableToken { // Unix time when frozen tokens may be thawed. uint iceAgeEnds; mapping (address => uint) public frozenBalanceOf; // Only if we're out of the ice age. modifier only_when_thawable { if (now < iceAgeEnds) throw; _; } // Tokens have been minted. event MintedFrozen(address indexed who, uint value); // Tokens have been minted. event Thawed(address indexed who, uint value); // Create the contract, setting the minting account. function ThawableMintableToken(uint _iceAgeEnds) { iceAgeEnds = _iceAgeEnds; } // Credit `_value` frozen tokens to `_who`. function mintFrozen(address _who, uint _value) only_minter { frozenBalanceOf[_who] += _value; totalSupply += _value; MintedFrozen(_who, _value); } // Converts all of the sender's frozen tokens into normal tokens if we're // out of the ice age. function thaw() only_when_thawable { Thawed(msg.sender, frozenBalanceOf[msg.sender]); accounts[msg.sender].balance += frozenBalanceOf[msg.sender]; frozenBalanceOf[msg.sender] = 0; } } contract BasicMintableReceiverToken is ThawableMintableToken, Recorder { function received(address _who, uint _value) { super.mint(_who, _value); } function done() { super.ceaseMinting(); } } /// Will accept Ether "contributions" and record each both as a log and in a /// queryable record. contract Receipter { /// Constructor. `_admin` has the ability to pause the /// contribution period and, eventually, kill this contract. `_treasury` /// receives all funds. `_beginTime` and `_endTime` define the begin and /// end of the period. function Receipter(address _recorder, address _admin, address _treasury, uint _beginTime, uint _endTime) { recorder = Recorder(_recorder); admin = _admin; treasury = _treasury; beginTime = _beginTime; endTime = _endTime; } // Can only be called by _admin. modifier only_admin { if (msg.sender != admin) throw; _; } // Can only be called by prior to the period. modifier only_before_period { if (now >= beginTime) throw; _; } // Only does something if during the period. modifier when_during_period { if (now >= beginTime && now < endTime && !isHalted) _; } // Can only be called during the period when not halted. modifier only_during_period { if (now < beginTime || now >= endTime || isHalted) throw; _; } // Can only be called during the period when halted. modifier only_during_halted_period { if (now < beginTime || now >= endTime || !isHalted) throw; _; } // Can only be called after the period. modifier only_after_period { if (now < endTime || isHalted) throw; _; } // The value of the message must be sufficiently large to not be considered dust. modifier is_not_dust { if (msg.value < dust) throw; _; } /// Some contribution `amount` received from `recipient`. event Received(address indexed recipient, uint amount); /// Period halted abnormally. event Halted(); /// Period restarted after abnormal halt. event Unhalted(); /// Fallback function: receive a contribution from sender. function() payable { processReceipt(msg.sender); } /// Receive a contribution from sender. function receive() payable returns (bool) { return processReceipt(msg.sender); } /// Receive a contribution from `_recipient`. function receiveFrom(address _recipient) payable returns (bool) { return processReceipt(_recipient); } /// Receive a contribution from `_recipient`. function processReceipt(address _recipient) only_during_period is_not_dust internal returns (bool) { if (!treasury.call.value(msg.value)()) throw; recorder.received(_recipient, msg.value); total += msg.value; Received(_recipient, msg.value); return true; } /// Halt the contribution period. Any attempt at contributing will fail. function halt() only_admin only_during_period { isHalted = true; Halted(); } /// Unhalt the contribution period. function unhalt() only_admin only_during_halted_period { isHalted = false; Unhalted(); } /// Kill this contract. function kill() only_admin only_after_period { recorder.done(); suicide(treasury); } // How much is enough? uint public constant dust = 100 finney; // The contract which gets called whenever anything is received. Recorder public recorder; // Who can halt/unhalt/kill? address public admin; // Who gets the stash? address public treasury; // When does the contribution period begin? uint public beginTime; // When does the period end? uint public endTime; // Are contributions abnormally halted? bool public isHalted = false; mapping (address => uint) public record; uint public total = 0; } contract SignedReceipter is Receipter { function SignedReceipter(address _recorder, address _admin, address _treasury, uint _beginTime, uint _endTime, bytes32 _sigHash) { recorder = Recorder(_recorder); admin = _admin; treasury = _treasury; beginTime = _beginTime; endTime = _endTime; sigHash = _sigHash; } modifier only_signed(address who, uint8 v, bytes32 r, bytes32 s) { if (ecrecover(sigHash, v, r, s) != who) throw; _; } function() payable { throw; } function receive() payable returns (bool) { throw; } function receiveFrom(address) payable returns (bool) { throw; } /// Fallback function: receive a contribution from sender. function receiveSigned(uint8 v, bytes32 r, bytes32 s) payable returns (bool) { return processSignedReceipt(msg.sender, v, r, s); } /// Receive a contribution from `_recipient`. function receiveSignedFrom(address _sender, uint8 v, bytes32 r, bytes32 s) payable returns (bool) { return processSignedReceipt(_sender, v, r, s); } /// Receive a contribution from `_recipient`. function processSignedReceipt(address _sender, uint8 v, bytes32 r, bytes32 s) only_signed(_sender, v, r, s) internal returns (bool) { return processReceipt(_sender); } bytes32 sigHash; } contract CertifyingReceipter is SignedReceipter { function CertifyingReceipter(address _recorder, address _admin, address _treasury, uint _beginTime, uint _endTime, bytes32 _sigHash, address _certifier) { recorder = Recorder(_recorder); admin = _admin; treasury = _treasury; beginTime = _beginTime; endTime = _endTime; sigHash = _sigHash; certifier = Certifier(_certifier); } /// Fallback function: receive a contribution from sender. function receiveSigned(uint8 v, bytes32 r, bytes32 s) payable returns (bool) { return processCertifiedReceipt(msg.sender, v, r, s); } function receiveSignedFrom() payable returns (bool) { throw; } function processCertifiedReceipt(address _sender, uint8 v, bytes32 r, bytes32 s) internal only_certified(msg.sender) returns (bool) { return processSignedReceipt(_sender, v, r, s); } modifier only_certified(address who) { if (!certifier.certified(who)) throw; _; } Certifier certifier; } contract FairReceipter is CertifyingReceipter { function FairReceipter( address _recorder, address _admin, address _treasury, uint _beginTime, uint _endTime, bytes32 _sigHash, address _certifier, uint _cap, uint _segmentDuration ) { recorder = Recorder(_recorder); admin = _admin; treasury = _treasury; beginTime = _beginTime; endTime = _endTime; sigHash = _sigHash; certifier = Certifier(_certifier); cap = _cap; segmentDuration = _segmentDuration; } function receive(uint8 v, bytes32 r, bytes32 s) only_under_max(msg.sender) payable returns (bool) { return processCertifiedReceipt(msg.sender, v, r, s); } function maxBuy() when_during_period public returns (uint) { uint segment = (now - beginTime) / segmentDuration; // actually just: segment = min(segment, endSegment); if (segment > endSegment) segment = endSegment; return firstMaxBuy << segment; } function maxBuyFor(address _who) when_during_period public returns (uint) { var segmentMaxBuy = maxBuy(); // Should never happen, but just in case... if (record[_who] >= segmentMaxBuy) return 0; return segmentMaxBuy - record[_who]; } modifier only_under_max(address who) { if (msg.value > maxBuyFor(who)) throw; _; } uint constant firstMaxBuy = 1 ether; uint constant endSegment = 16; uint segmentDuration; uint cap; }
Unix time when frozen tokens may be thawed. Only if we're out of the ice age. Tokens have been minted. Tokens have been minted. Create the contract, setting the minting account.
contract ThawableMintableToken is EndableMintableToken { uint iceAgeEnds; mapping (address => uint) public frozenBalanceOf; event MintedFrozen(address indexed who, uint value); event Thawed(address indexed who, uint value); modifier only_when_thawable { if (now < iceAgeEnds) throw; _; } function ThawableMintableToken(uint _iceAgeEnds) { iceAgeEnds = _iceAgeEnds; } function mintFrozen(address _who, uint _value) only_minter { frozenBalanceOf[_who] += _value; totalSupply += _value; MintedFrozen(_who, _value); } function thaw() only_when_thawable { Thawed(msg.sender, frozenBalanceOf[msg.sender]); accounts[msg.sender].balance += frozenBalanceOf[msg.sender]; frozenBalanceOf[msg.sender] = 0; } }
2,578,768
[ 1, 18729, 813, 1347, 12810, 2430, 2026, 506, 286, 2219, 329, 18, 5098, 309, 732, 4565, 596, 434, 326, 277, 311, 9388, 18, 13899, 1240, 2118, 312, 474, 329, 18, 13899, 1240, 2118, 312, 474, 329, 18, 1788, 326, 6835, 16, 3637, 326, 312, 474, 310, 2236, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 935, 2219, 429, 49, 474, 429, 1345, 353, 4403, 429, 49, 474, 429, 1345, 288, 203, 203, 202, 11890, 277, 311, 9692, 24980, 31, 203, 203, 202, 6770, 261, 2867, 516, 2254, 13, 1071, 12810, 13937, 951, 31, 203, 203, 203, 202, 2575, 490, 474, 329, 42, 9808, 12, 2867, 8808, 10354, 16, 2254, 460, 1769, 203, 203, 202, 2575, 935, 2219, 329, 12, 2867, 8808, 10354, 16, 2254, 460, 1769, 203, 203, 202, 20597, 1338, 67, 13723, 67, 451, 2219, 429, 288, 309, 261, 3338, 411, 277, 311, 9692, 24980, 13, 604, 31, 389, 31, 289, 203, 202, 915, 935, 2219, 429, 49, 474, 429, 1345, 12, 11890, 389, 1812, 9692, 24980, 13, 288, 203, 202, 202, 1812, 9692, 24980, 273, 389, 1812, 9692, 24980, 31, 203, 202, 97, 203, 203, 202, 915, 312, 474, 42, 9808, 12, 2867, 389, 3350, 83, 16, 2254, 389, 1132, 13, 1338, 67, 1154, 387, 288, 203, 202, 202, 28138, 13937, 951, 63, 67, 3350, 83, 65, 1011, 389, 1132, 31, 203, 202, 202, 4963, 3088, 1283, 1011, 389, 1132, 31, 203, 202, 202, 49, 474, 329, 42, 9808, 24899, 3350, 83, 16, 389, 1132, 1769, 203, 202, 97, 203, 203, 202, 915, 286, 2219, 1435, 1338, 67, 13723, 67, 451, 2219, 429, 288, 203, 202, 202, 1315, 2219, 329, 12, 3576, 18, 15330, 16, 12810, 13937, 951, 63, 3576, 18, 15330, 19226, 203, 202, 202, 13739, 63, 3576, 18, 15330, 8009, 12296, 1011, 12810, 13937, 951, 63, 3576, 18, 15330, 15533, 203, 202, 202, 28138, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Contract on mapping contract MyContract{ // Creating / Structuring our own datatype ~ Payment struct Payment { // Important variables uint amount; uint timestamps; } // - How to access ~ struct values ?? // Accessing "amount" // & assigning a value of "100" // Payment public payment; // function setAmount() public { // payment.amount = 100; // } // Creating / Structuring our own datatype ~ Balance struct Balance { // Important variables uint totalBalance; uint numPayments; // Mapping our payments from ~ struct Payment // Mapping a struct mapping(uint => Payment) payments; } // Mapping our ~balance which in turn maps our ~ payments ^^^ mapping(address => Balance) public balanceReceived; // Function returning balance function getBalance() public view returns(uint) { // Return contract's "this" balance return address(this).balance; } // Function sending money function sendMoney() public payable { // Increase the balance by the amount refunded / returned // .totalBalance is defined in ~ struct balanceReceived[msg.sender].totalBalance += msg.value; // Creating a new ~ Payment // (msg.value, ...) is the "amount" defined in ~ struct // (..., block.timestamp) is the "timestamps" defined in ~ struct Payment memory payment = Payment(msg.value, block.timestamp); // Adding balance payment to balanceReceived // .payments is the mapping defined in ~ struct balanceReceived[msg.sender].payments[balanceReceived[msg.sender].numPayments] = payment; // Increamenting the number of payments balanceReceived[msg.sender].numPayments++; } // Function withdrawing a certain amount of money // We are creating two fields "_to" for address & "_amount" for // the amount we want to send function withdrawMoney(address payable _to, uint _amount) public { // This is an "if statement", // We are making sure that the balance is greater than or equal to // the amount we are trying to send require(balanceReceived[msg.sender].totalBalance >= _amount, "You do not have enough money!"); // Reducing the amount of money in the address balanceReceived[msg.sender].totalBalance -= _amount; // Transfer the requested amount _to.transfer(_amount); } // Function withdrawing money from // the account that received money // Note "payable" is used to send money function withdrawAllMoney(address payable _to) public { // Variable "_to" is transfering the money // back to the sender - function withdrawAllMoney() public {} ~ without an argument // _to.transfer(address(this).balance); // Old transfer statement ^^^ // Recording original balance uint balanceToSend = balanceReceived[msg.sender].totalBalance; // Setting balance sent to 0; balanceReceived[msg.sender].totalBalance = 0; // Transfer balance back to sender _to.transfer(balanceToSend); // New transfer statement } }
Function sending money Increase the balance by the amount refunded / returned .totalBalance is defined in ~ struct Creating a new ~ Payment (msg.value, ...) is the "amount" defined in ~ struct (..., block.timestamp) is the "timestamps" defined in ~ struct Adding balance payment to balanceReceived .payments is the mapping defined in ~ struct Increamenting the number of payments
function sendMoney() public payable { balanceReceived[msg.sender].totalBalance += msg.value; Payment memory payment = Payment(msg.value, block.timestamp); balanceReceived[msg.sender].payments[balanceReceived[msg.sender].numPayments] = payment; balanceReceived[msg.sender].numPayments++; }
13,141,260
[ 1, 2083, 5431, 15601, 657, 11908, 326, 11013, 635, 326, 3844, 1278, 12254, 342, 2106, 263, 4963, 13937, 353, 2553, 316, 4871, 1958, 21837, 279, 394, 4871, 12022, 261, 3576, 18, 1132, 16, 1372, 13, 353, 326, 315, 8949, 6, 2553, 316, 4871, 1958, 261, 2777, 16, 1203, 18, 5508, 13, 353, 326, 315, 25459, 6, 2553, 316, 4871, 1958, 21240, 11013, 5184, 358, 11013, 8872, 263, 10239, 1346, 353, 326, 2874, 2553, 316, 4871, 1958, 15090, 793, 319, 310, 326, 1300, 434, 25754, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1366, 23091, 1435, 1071, 8843, 429, 288, 203, 540, 203, 3639, 11013, 8872, 63, 3576, 18, 15330, 8009, 4963, 13937, 1011, 1234, 18, 1132, 31, 203, 540, 203, 3639, 12022, 3778, 5184, 273, 12022, 12, 3576, 18, 1132, 16, 1203, 18, 5508, 1769, 203, 540, 203, 3639, 11013, 8872, 63, 3576, 18, 15330, 8009, 10239, 1346, 63, 12296, 8872, 63, 3576, 18, 15330, 8009, 2107, 23725, 65, 273, 5184, 31, 203, 540, 203, 3639, 11013, 8872, 63, 3576, 18, 15330, 8009, 2107, 23725, 9904, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // ODIN token contract // ---------------------------------------------------------------------------- pragma solidity ^0.4.21; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Burn(uint tokens); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address private newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) onlyOwner public onlyOwner { owner = _newOwner; emit OwnershipTransferred(msg.sender, _newOwner); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract OdinToken is ERC20Interface, Owned { using SafeMath for uint256; string public symbol; string public name; uint8 public decimals; uint private _totalSupply; bool private _whitelistAll; struct balanceData { bool locked; uint balance; uint airDropQty; } mapping(address => balanceData) balances; mapping(address => mapping(address => uint)) allowed; /** * @dev Constructor for Odin creation * @dev Initially assigns the totalSupply to the contract creator */ function OdinToken() public { // owner of this contract owner = msg.sender; symbol = "ODIN"; name = "ODIN Token"; decimals = 18; _whitelistAll=false; _totalSupply = 100000000000000000000000; balances[owner].balance = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() constant public returns (uint256 totalSupply) { return _totalSupply; } // ------------------------------------------------------------------------ // whitelist an address // ------------------------------------------------------------------------ function whitelistAddress(address to) onlyOwner public returns (bool) { balances[to].airDropQty = 0; return true; } /** * @dev Whitelist all addresses early * @return An bool showing if the function succeeded. */ function whitelistAllAddresses() onlyOwner public returns (bool) { _whitelistAll = true; return true; } /** * @dev Gets the balance of the specified address. * @param tokenOwner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner].balance; } /** * @dev transfer token for a specified address * @param to The address to transfer to. * @param tokens The amount to be transferred. */ function transfer(address to, uint tokens) public returns (bool success) { require (msg.sender != to); // cannot send to yourself require(to != address(0)); // cannot send to address(0) require(tokens <= balances[msg.sender].balance); // do you have enough to send? if (!_whitelistAll) { // do not allow transfering air dropped tokens prior to Sep 1 2018 if (msg.sender != owner && block.timestamp < 1535760000 && balances[msg.sender].airDropQty>0) { require(tokens < 0); } // after Sep 1 2018 and before Dec 31, 2018, do not allow transfering more than 10% of air dropped tokens if (msg.sender != owner && block.timestamp < 1546214400 && balances[msg.sender].airDropQty>0) { require((balances[msg.sender].balance - tokens) >= (balances[msg.sender].airDropQty / 10 * 9)); } // after Dec 31 2018 and before March 31, 2019, do not allow transfering more than 25% of air dropped tokens if (msg.sender != owner && block.timestamp < 1553990400 && balances[msg.sender].airDropQty>0) { require((balances[msg.sender].balance - tokens) >= balances[msg.sender].airDropQty / 4 * 3); } // after March 31, 2019 and before Jun 30, 2019, do not allow transfering more than 50% of air dropped tokens if (msg.sender != owner && block.timestamp < 1561852800 && balances[msg.sender].airDropQty>0) { require((balances[msg.sender].balance - tokens) >= balances[msg.sender].airDropQty / 2); } // after Jun 30, 2019 and before Oct 2, 2019, do not allow transfering more than 75% of air dropped tokens if (msg.sender != owner && block.timestamp < 1569974400 && balances[msg.sender].airDropQty>0) { require((balances[msg.sender].balance - tokens) >= balances[msg.sender].airDropQty / 4); } // otherwise, no transfer restrictions } balances[msg.sender].balance = balances[msg.sender].balance.sub(tokens); balances[to].balance = balances[to].balance.add(tokens); if (msg.sender == owner) { balances[to].airDropQty = balances[to].airDropQty.add(tokens); } emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // not implemented // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { return false; } // ------------------------------------------------------------------------ // not implemented // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { return false; } // ------------------------------------------------------------------------ // not implemented // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return 0; } // ------------------------------------------------------------------------ // not implemented // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { return false; } // ------------------------------------------------------------------------ // Used to burn unspent tokens in the contract // ------------------------------------------------------------------------ function burn(uint256 tokens) onlyOwner public returns (bool) { require((balances[owner].balance - tokens) >= 0); balances[owner].balance = balances[owner].balance.sub(tokens); _totalSupply = _totalSupply.sub(tokens); emit Burn(tokens); return true; } function () { //if ether is sent to this address, send it back. throw; } }
cannot send to address(0)
require(to != address(0));
1,167,785
[ 1, 12892, 1366, 358, 1758, 12, 20, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 869, 480, 1758, 12, 20, 10019, 1171, 9079, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.19; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() 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 { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ 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; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic token) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(owner, balance); } } /// @dev Implements access control to the DWorld contract. contract BurnupGameAccessControl is Claimable, Pausable, CanReclaimToken { mapping (address => bool) public cfo; function BurnupGameAccessControl() public { // The creator of the contract is a CFO. cfo[msg.sender] = true; } /// @dev Access modifier for CFO-only functionality. modifier onlyCFO() { require(cfo[msg.sender]); _; } /// @dev Assigns or removes an address to act as a CFO. Only available to the current contract owner. /// @param addr The address to set or unset as CFO. /// @param set Whether to set or unset the address as CFO. function setCFO(address addr, bool set) external onlyOwner { require(addr != address(0)); if (!set) { delete cfo[addr]; } else { cfo[addr] = true; } } } /// @dev Defines base data structures for DWorld. contract BurnupGameBase is BurnupGameAccessControl { using SafeMath for uint256; event ActiveTimes(uint256[] from, uint256[] to); event AllowStart(bool allowStart); event NextGame( uint256 rows, uint256 cols, uint256 initialActivityTimer, uint256 finalActivityTimer, uint256 numberOfFlipsToFinalActivityTimer, uint256 timeoutBonusTime, uint256 unclaimedTilePrice, uint256 buyoutReferralBonusPercentage, uint256 firstBuyoutPrizePoolPercentage, uint256 buyoutPrizePoolPercentage, uint256 buyoutDividendPercentage, uint256 buyoutFeePercentage, uint256 buyoutPriceIncreasePercentage ); event Start( uint256 indexed gameIndex, address indexed starter, uint256 timestamp, uint256 prizePool ); event End(uint256 indexed gameIndex, address indexed winner, uint256 indexed identifier, uint256 x, uint256 y, uint256 timestamp, uint256 prize); event Buyout( uint256 indexed gameIndex, address indexed player, uint256 indexed identifier, uint256 x, uint256 y, uint256 timestamp, uint256 timeoutTimestamp, uint256 newPrice, uint256 newPrizePool ); event LastTile( uint256 indexed gameIndex, uint256 indexed identifier, uint256 x, uint256 y ); event PenultimateTileTimeout( uint256 indexed gameIndex, uint256 timeoutTimestamp ); event SpiceUpPrizePool(uint256 indexed gameIndex, address indexed spicer, uint256 spiceAdded, string message, uint256 newPrizePool); /// @dev Struct to hold game settings. struct GameSettings { uint256 rows; // 5 uint256 cols; // 8 /// @dev Initial time after last trade after which tiles become inactive. uint256 initialActivityTimer; // 600 /// @dev Final time after last trade after which tiles become inactive. uint256 finalActivityTimer; // 300 /// @dev Number of flips for the activity timer to move from the initial /// activity timer to the final activity timer. uint256 numberOfFlipsToFinalActivityTimer; // 80 /// @dev The timeout bonus time in seconds per tile owned by the player. uint256 timeoutBonusTime; // 30 /// @dev Base price for unclaimed tiles. uint256 unclaimedTilePrice; // 0.01 ether /// @dev Percentage of the buyout price that goes towards the referral /// bonus. In 1/1000th of a percentage. uint256 buyoutReferralBonusPercentage; // 750 /// @dev For the initial buyout of a tile: percentage of the buyout price /// that goes towards the prize pool. In 1/1000th of a percentage. uint256 firstBuyoutPrizePoolPercentage; // 40000 /// @dev Percentage of the buyout price that goes towards the prize /// pool. In 1/1000th of a percentage. uint256 buyoutPrizePoolPercentage; // 10000 /// @dev Percentage of the buyout price that goes towards dividends /// surrounding the tile that is bought out. In in 1/1000th of /// a percentage. uint256 buyoutDividendPercentage; // 5000 /// @dev Buyout fee in 1/1000th of a percentage. uint256 buyoutFeePercentage; // 2500 /// @dev Buyout price increase in 1/1000th of a percentage. uint256 buyoutPriceIncreasePercentage; } /// @dev Struct to hold game state. struct GameState { /// @dev Boolean indicating whether the game is live. bool gameStarted; /// @dev Time at which the game started. uint256 gameStartTimestamp; /// @dev Keep track of tile ownership. mapping (uint256 => address) identifierToOwner; /// @dev Keep track of the timestamp at which a tile was flipped last. mapping (uint256 => uint256) identifierToTimeoutTimestamp; /// @dev Current tile price. mapping (uint256 => uint256) identifierToBuyoutPrice; /// @dev The number of tiles owned by an address. mapping (address => uint256) addressToNumberOfTiles; /// @dev The number of tile flips performed. uint256 numberOfTileFlips; /// @dev Keep track of the tile that will become inactive last. uint256 lastTile; /// @dev Keep track of the timeout of the penultimate tile. uint256 penultimateTileTimeout; /// @dev The prize pool. uint256 prizePool; } /// @notice Mapping from game indices to game states. mapping (uint256 => GameState) public gameStates; /// @notice The index of the current game. uint256 public gameIndex = 0; /// @notice Current game settings. GameSettings public gameSettings; /// @dev Settings for the next game GameSettings public nextGameSettings; /// @notice Time windows in seconds from the start of the week /// when new games can be started. uint256[] public activeTimesFrom; uint256[] public activeTimesTo; /// @notice Whether the game can start once outside of active times. bool public allowStart; function BurnupGameBase() public { // Initial settings. setNextGameSettings( 4, // rows 5, // cols 300, // initialActivityTimer // todo set to 600 150, // finalActivityTimer // todo set to 150 5, // numberOfFlipsToFinalActivityTimer // todo set to 80 30, // timeoutBonusTime 0.01 ether, // unclaimedTilePrice 750, // buyoutReferralBonusPercentage 40000, // firstBuyoutPrizePoolPercentage 10000, // buyoutPrizePoolPercentage 5000, // buyoutDividendPercentage 2500, // buyoutFeePercentage 150000 // buyoutPriceIncreasePercentage ); } /// @dev Test whether the coordinate is valid. /// @param x The x-part of the coordinate to test. /// @param y The y-part of the coordinate to test. function validCoordinate(uint256 x, uint256 y) public view returns(bool) { return x < gameSettings.cols && y < gameSettings.rows; } /// @dev Represent a 2D coordinate as a single uint. /// @param x The x-coordinate. /// @param y The y-coordinate. function coordinateToIdentifier(uint256 x, uint256 y) public view returns(uint256) { require(validCoordinate(x, y)); return (y * gameSettings.cols) + x + 1; } /// @dev Turn a single uint representation of a coordinate into its x and y parts. /// @param identifier The uint representation of a coordinate. /// Assumes the identifier is valid. function identifierToCoordinate(uint256 identifier) public view returns(uint256 x, uint256 y) { y = (identifier - 1) / gameSettings.cols; x = (identifier - 1) - (y * gameSettings.cols); } /// @notice Sets the settings for the next game. function setNextGameSettings( uint256 rows, uint256 cols, uint256 initialActivityTimer, uint256 finalActivityTimer, uint256 numberOfFlipsToFinalActivityTimer, uint256 timeoutBonusTime, uint256 unclaimedTilePrice, uint256 buyoutReferralBonusPercentage, uint256 firstBuyoutPrizePoolPercentage, uint256 buyoutPrizePoolPercentage, uint256 buyoutDividendPercentage, uint256 buyoutFeePercentage, uint256 buyoutPriceIncreasePercentage ) public onlyCFO { // Buyout dividend must be 2% at the least. // Buyout dividend percentage may be 12.5% at the most. require(2000 <= buyoutDividendPercentage && buyoutDividendPercentage <= 12500); // Buyout fee may be 5% at the most. require(buyoutFeePercentage <= 5000); if (numberOfFlipsToFinalActivityTimer == 0) { require(initialActivityTimer == finalActivityTimer); } nextGameSettings = GameSettings({ rows: rows, cols: cols, initialActivityTimer: initialActivityTimer, finalActivityTimer: finalActivityTimer, numberOfFlipsToFinalActivityTimer: numberOfFlipsToFinalActivityTimer, timeoutBonusTime: timeoutBonusTime, unclaimedTilePrice: unclaimedTilePrice, buyoutReferralBonusPercentage: buyoutReferralBonusPercentage, firstBuyoutPrizePoolPercentage: firstBuyoutPrizePoolPercentage, buyoutPrizePoolPercentage: buyoutPrizePoolPercentage, buyoutDividendPercentage: buyoutDividendPercentage, buyoutFeePercentage: buyoutFeePercentage, buyoutPriceIncreasePercentage: buyoutPriceIncreasePercentage }); NextGame( rows, cols, initialActivityTimer, finalActivityTimer, numberOfFlipsToFinalActivityTimer, timeoutBonusTime, unclaimedTilePrice, buyoutReferralBonusPercentage, firstBuyoutPrizePoolPercentage, buyoutPrizePoolPercentage, buyoutDividendPercentage, buyoutFeePercentage, buyoutPriceIncreasePercentage ); } /// @notice Set the active times. function setActiveTimes(uint256[] _from, uint256[] _to) external onlyCFO { require(_from.length == _to.length); activeTimesFrom = _from; activeTimesTo = _to; // Emit event. ActiveTimes(_from, _to); } /// @notice Allow the game to start once outside of active times. function setAllowStart(bool _allowStart) external onlyCFO { allowStart = _allowStart; // Emit event. AllowStart(_allowStart); } /// @notice A boolean indicating whether a new game can start, /// based on the active times. function canStart() public view returns (bool) { // Get the time of the week in seconds. // There are 7 * 24 * 60 * 60 = 604800 seconds in a week, // and unix timestamps started counting from a Thursday, // so subtract 4 * 24 * 60 * 60 = 345600 seconds, as // (0 - 345600) % 604800 = 259200, i.e. the number of // seconds in a week until Thursday 00:00:00. uint256 timeOfWeek = (block.timestamp - 345600) % 604800; uint256 windows = activeTimesFrom.length; if (windows == 0) { // No start times configured, any time is allowed. return true; } for (uint256 i = 0; i < windows; i++) { if (timeOfWeek >= activeTimesFrom[i] && timeOfWeek <= activeTimesTo[i]) { return true; } } return false; } /// @notice Calculate the current game's base timeout. function calculateBaseTimeout() public view returns(uint256) { uint256 _numberOfTileFlips = gameStates[gameIndex].numberOfTileFlips; if (_numberOfTileFlips >= gameSettings.numberOfFlipsToFinalActivityTimer || gameSettings.numberOfFlipsToFinalActivityTimer == 0) { return gameSettings.finalActivityTimer; } else { if (gameSettings.finalActivityTimer <= gameSettings.initialActivityTimer) { // The activity timer decreases over time. // This cannot underflow, as initialActivityTimer is guaranteed to be // greater than or equal to finalActivityTimer. uint256 difference = gameSettings.initialActivityTimer - gameSettings.finalActivityTimer; // Calculate the decrease in activity timer, based on the number of wagers performed. uint256 decrease = difference.mul(_numberOfTileFlips).div(gameSettings.numberOfFlipsToFinalActivityTimer); // This subtraction cannot underflow, as decrease is guaranteed to be less than or equal to initialActivityTimer. return (gameSettings.initialActivityTimer - decrease); } else { // The activity timer increases over time. // This cannot underflow, as initialActivityTimer is guaranteed to be // smaller than finalActivityTimer. difference = gameSettings.finalActivityTimer - gameSettings.initialActivityTimer; // Calculate the increase in activity timer, based on the number of wagers performed. uint256 increase = difference.mul(_numberOfTileFlips).div(gameSettings.numberOfFlipsToFinalActivityTimer); // This addition cannot overflow, as initialActivityTimer + increase is guaranteed to be less than or equal to finalActivityTimer. return (gameSettings.initialActivityTimer + increase); } } } /// @notice Get the new timeout timestamp for a tile. /// @param identifier The identifier of the tile being flipped. /// @param player The address of the player flipping the tile. function tileTimeoutTimestamp(uint256 identifier, address player) public view returns (uint256) { uint256 bonusTime = gameSettings.timeoutBonusTime.mul(gameStates[gameIndex].addressToNumberOfTiles[player]); uint256 timeoutTimestamp = block.timestamp.add(calculateBaseTimeout()).add(bonusTime); uint256 currentTimeoutTimestamp = gameStates[gameIndex].identifierToTimeoutTimestamp[identifier]; if (currentTimeoutTimestamp == 0) { // Tile has never been flipped before. currentTimeoutTimestamp = gameStates[gameIndex].gameStartTimestamp.add(gameSettings.initialActivityTimer); } if (timeoutTimestamp >= currentTimeoutTimestamp) { return timeoutTimestamp; } else { return currentTimeoutTimestamp; } } /// @dev Set the current game settings. function _setGameSettings() internal { if (gameSettings.rows != nextGameSettings.rows) { gameSettings.rows = nextGameSettings.rows; } if (gameSettings.cols != nextGameSettings.cols) { gameSettings.cols = nextGameSettings.cols; } if (gameSettings.initialActivityTimer != nextGameSettings.initialActivityTimer) { gameSettings.initialActivityTimer = nextGameSettings.initialActivityTimer; } if (gameSettings.finalActivityTimer != nextGameSettings.finalActivityTimer) { gameSettings.finalActivityTimer = nextGameSettings.finalActivityTimer; } if (gameSettings.numberOfFlipsToFinalActivityTimer != nextGameSettings.numberOfFlipsToFinalActivityTimer) { gameSettings.numberOfFlipsToFinalActivityTimer = nextGameSettings.numberOfFlipsToFinalActivityTimer; } if (gameSettings.timeoutBonusTime != nextGameSettings.timeoutBonusTime) { gameSettings.timeoutBonusTime = nextGameSettings.timeoutBonusTime; } if (gameSettings.unclaimedTilePrice != nextGameSettings.unclaimedTilePrice) { gameSettings.unclaimedTilePrice = nextGameSettings.unclaimedTilePrice; } if (gameSettings.buyoutReferralBonusPercentage != nextGameSettings.buyoutReferralBonusPercentage) { gameSettings.buyoutReferralBonusPercentage = nextGameSettings.buyoutReferralBonusPercentage; } if (gameSettings.firstBuyoutPrizePoolPercentage != nextGameSettings.firstBuyoutPrizePoolPercentage) { gameSettings.firstBuyoutPrizePoolPercentage = nextGameSettings.firstBuyoutPrizePoolPercentage; } if (gameSettings.buyoutPrizePoolPercentage != nextGameSettings.buyoutPrizePoolPercentage) { gameSettings.buyoutPrizePoolPercentage = nextGameSettings.buyoutPrizePoolPercentage; } if (gameSettings.buyoutDividendPercentage != nextGameSettings.buyoutDividendPercentage) { gameSettings.buyoutDividendPercentage = nextGameSettings.buyoutDividendPercentage; } if (gameSettings.buyoutFeePercentage != nextGameSettings.buyoutFeePercentage) { gameSettings.buyoutFeePercentage = nextGameSettings.buyoutFeePercentage; } if (gameSettings.buyoutPriceIncreasePercentage != nextGameSettings.buyoutPriceIncreasePercentage) { gameSettings.buyoutPriceIncreasePercentage = nextGameSettings.buyoutPriceIncreasePercentage; } } } /// @dev Holds ownership functionality such as transferring. contract BurnupGameOwnership is BurnupGameBase { event Transfer(address indexed from, address indexed to, uint256 indexed deedId); /// @notice Name of the collection of deeds (non-fungible token), as defined in ERC721Metadata. function name() public pure returns (string _deedName) { _deedName = "Burnup Tiles"; } /// @notice Symbol of the collection of deeds (non-fungible token), as defined in ERC721Metadata. function symbol() public pure returns (string _deedSymbol) { _deedSymbol = "BURN"; } /// @dev Checks if a given address owns a particular tile. /// @param _owner The address of the owner to check for. /// @param _identifier The tile identifier to check for. function _owns(address _owner, uint256 _identifier) internal view returns (bool) { return gameStates[gameIndex].identifierToOwner[_identifier] == _owner; } /// @dev Assigns ownership of a specific deed to an address. /// @param _from The address to transfer the deed from. /// @param _to The address to transfer the deed to. /// @param _identifier The identifier of the deed to transfer. function _transfer(address _from, address _to, uint256 _identifier) internal { // Transfer ownership. gameStates[gameIndex].identifierToOwner[_identifier] = _to; if (_from != 0x0) { gameStates[gameIndex].addressToNumberOfTiles[_from] = gameStates[gameIndex].addressToNumberOfTiles[_from].sub(1); } gameStates[gameIndex].addressToNumberOfTiles[_to] = gameStates[gameIndex].addressToNumberOfTiles[_to].add(1); // Emit the transfer event. Transfer(_from, _to, _identifier); } /// @notice Returns the address currently assigned ownership of a given deed. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _identifier) external view returns (address _owner) { _owner = gameStates[gameIndex].identifierToOwner[_identifier]; require(_owner != address(0)); } /// @notice Transfer a deed to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721, or your /// deed may be lost forever. /// @param _to The address of the recipient, can be a user or contract. /// @param _identifier The identifier of the deed to transfer. /// @dev Required for ERC-721 compliance. function transfer(address _to, uint256 _identifier) external whenNotPaused { // One can only transfer their own deeds. require(_owns(msg.sender, _identifier)); // Transfer ownership _transfer(msg.sender, _to, _identifier); } } /** * @title PullPayment * @dev Base contract supporting async send for pull payments. Inherit from this * contract and use asyncSend instead of send. */ contract PullPayment { using SafeMath for uint256; mapping(address => uint256) public payments; uint256 public totalPayments; /** * @dev withdraw accumulated balance, called by payee. */ function withdrawPayments() public { address payee = msg.sender; uint256 payment = payments[payee]; require(payment != 0); require(this.balance >= payment); totalPayments = totalPayments.sub(payment); payments[payee] = 0; assert(payee.send(payment)); } /** * @dev Called by the payer to store the sent amount as credit to be pulled. * @param dest The destination address of the funds. * @param amount The amount to transfer. */ function asyncSend(address dest, uint256 amount) internal { payments[dest] = payments[dest].add(amount); totalPayments = totalPayments.add(amount); } } /// @dev Implements access control to the BurnUp wallet. contract BurnupHoldingAccessControl is Claimable, Pausable, CanReclaimToken { address public cfoAddress; /// Boolean indicating whether an address is a BurnUp Game contract. mapping (address => bool) burnupGame; function BurnupHoldingAccessControl() public { // The creator of the contract is the initial CFO. cfoAddress = msg.sender; } /// @dev Access modifier for CFO-only functionality. modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for functionality that may only be called by a BurnUp game. modifier onlyBurnupGame() { // The sender must be a recognized BurnUp game address. require(burnupGame[msg.sender]); _; } /// @dev Assigns a new address to act as the CFO. Only available to the current contract owner. /// @param _newCFO The address of the new CFO. function setCFO(address _newCFO) external onlyOwner { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Add a Burnup game contract address. /// @param addr The address of the Burnup game contract. function addBurnupGame(address addr) external onlyOwner { burnupGame[addr] = true; } /// @dev Remove a Burnup game contract address. /// @param addr The address of the Burnup game contract. function removeBurnupGame(address addr) external onlyOwner { delete burnupGame[addr]; } } /// @dev Implements the BurnUp wallet. contract BurnupHoldingReferral is BurnupHoldingAccessControl { event SetReferrer(address indexed referral, address indexed referrer); /// Referrer of player. mapping (address => address) addressToReferrerAddress; /// Get the referrer of a player. /// @param player The address of the player to get the referrer of. function referrerOf(address player) public view returns (address) { return addressToReferrerAddress[player]; } /// Set the referrer for a player. /// @param playerAddr The address of the player to set the referrer for. /// @param referrerAddr The address of the referrer to set. function _setReferrer(address playerAddr, address referrerAddr) internal { addressToReferrerAddress[playerAddr] = referrerAddr; // Emit event. SetReferrer(playerAddr, referrerAddr); } } /// @dev Implements the BurnUp wallet. contract BurnupHoldingCore is BurnupHoldingReferral, PullPayment { using SafeMath for uint256; address public beneficiary1; address public beneficiary2; function BurnupHoldingCore(address _beneficiary1, address _beneficiary2) public { // The creator of the contract is the initial CFO. cfoAddress = msg.sender; // Set the two beneficiaries. beneficiary1 = _beneficiary1; beneficiary2 = _beneficiary2; } /// Pay the two beneficiaries. Sends both beneficiaries /// a halve of the payment. function payBeneficiaries() external payable { uint256 paymentHalve = msg.value.div(2); // We do not want a single wei to get stuck. uint256 otherPaymentHalve = msg.value.sub(paymentHalve); // Send payment for manual withdrawal. asyncSend(beneficiary1, paymentHalve); asyncSend(beneficiary2, otherPaymentHalve); } /// Sets a new address for Beneficiary one. /// @param addr The new address. function setBeneficiary1(address addr) external onlyCFO { beneficiary1 = addr; } /// Sets a new address for Beneficiary two. /// @param addr The new address. function setBeneficiary2(address addr) external onlyCFO { beneficiary2 = addr; } /// Set a referrer. /// @param playerAddr The address to set the referrer for. /// @param referrerAddr The address of the referrer to set. function setReferrer(address playerAddr, address referrerAddr) external onlyBurnupGame whenNotPaused returns(bool) { if (referrerOf(playerAddr) == address(0x0) && playerAddr != referrerAddr) { // Set the referrer, if no referrer has been set yet, and the player // and referrer are not the same address. _setReferrer(playerAddr, referrerAddr); // Indicate success. return true; } // Indicate failure. return false; } } /// @dev Holds functionality for finance related to tiles. contract BurnupGameFinance is BurnupGameOwnership, PullPayment { /// Address of Burnup wallet BurnupHoldingCore burnupHolding; function BurnupGameFinance(address burnupHoldingAddress) public { burnupHolding = BurnupHoldingCore(burnupHoldingAddress); } /// @dev Find the _claimed_ tiles surrounding a tile. /// @param _deedId The identifier of the tile to get the surrounding tiles for. function _claimedSurroundingTiles(uint256 _deedId) internal view returns (uint256[] memory) { var (x, y) = identifierToCoordinate(_deedId); // Find all claimed surrounding tiles. uint256 claimed = 0; // Create memory buffer capable of holding all tiles. uint256[] memory _tiles = new uint256[](8); // Loop through all neighbors. for (int256 dx = -1; dx <= 1; dx++) { for (int256 dy = -1; dy <= 1; dy++) { if (dx == 0 && dy == 0) { // Skip the center (i.e., the tile itself). continue; } uint256 nx = uint256(int256(x) + dx); uint256 ny = uint256(int256(y) + dy); if (nx >= gameSettings.cols || ny >= gameSettings.rows) { // This coordinate is outside the game bounds. continue; } // Get the coordinates of this neighboring identifier. uint256 neighborIdentifier = coordinateToIdentifier( nx, ny ); if (gameStates[gameIndex].identifierToOwner[neighborIdentifier] != address(0x0)) { _tiles[claimed] = neighborIdentifier; claimed++; } } } // Memory arrays cannot be resized, so copy all // tiles from the buffer to the tile array. uint256[] memory tiles = new uint256[](claimed); for (uint256 i = 0; i < claimed; i++) { tiles[i] = _tiles[i]; } return tiles; } /// @dev Calculate the next buyout price given the current total buyout cost. /// @param price The current buyout price. function nextBuyoutPrice(uint256 price) public view returns (uint256) { if (price < 0.02 ether) { return price.mul(200).div(100); // * 2.0 } else { return price.mul(gameSettings.buyoutPriceIncreasePercentage).div(100000); } } /// @dev Assign the proceeds of the buyout. function _assignBuyoutProceeds( address currentOwner, uint256[] memory claimedSurroundingTiles, uint256 fee, uint256 currentOwnerWinnings, uint256 totalDividendPerBeneficiary, uint256 referralBonus, uint256 prizePoolFunds ) internal { if (currentOwner != 0x0) { // Send the current owner's winnings. _sendFunds(currentOwner, currentOwnerWinnings); } else { // There is no current owner. Split the winnings to the prize pool and fees. uint256 prizePoolPart = currentOwnerWinnings.mul(gameSettings.firstBuyoutPrizePoolPercentage).div(100000); prizePoolFunds = prizePoolFunds.add(prizePoolPart); fee = fee.add(currentOwnerWinnings.sub(prizePoolPart)); } // Assign dividends to owners of surrounding tiles. for (uint256 i = 0; i < claimedSurroundingTiles.length; i++) { address beneficiary = gameStates[gameIndex].identifierToOwner[claimedSurroundingTiles[i]]; _sendFunds(beneficiary, totalDividendPerBeneficiary); } /// Distribute the referral bonuses (if any) for an address. address referrer1 = burnupHolding.referrerOf(msg.sender); if (referrer1 != 0x0) { _sendFunds(referrer1, referralBonus); address referrer2 = burnupHolding.referrerOf(referrer1); if (referrer2 != 0x0) { _sendFunds(referrer2, referralBonus); } else { // There is no second-level referrer. fee = fee.add(referralBonus); } } else { // There are no first and second-level referrers. fee = fee.add(referralBonus.mul(2)); } // Send the fee to the holding contract. burnupHolding.payBeneficiaries.value(fee)(); // Increase the prize pool. gameStates[gameIndex].prizePool = gameStates[gameIndex].prizePool.add(prizePoolFunds); } /// @notice Get the price for the given tile. /// @param _deedId The identifier of the tile to get the price for. function currentPrice(uint256 _deedId) public view returns (uint256 price) { address currentOwner = gameStates[gameIndex].identifierToOwner[_deedId]; if (currentOwner == 0x0) { price = gameSettings.unclaimedTilePrice; } else { price = gameStates[gameIndex].identifierToBuyoutPrice[_deedId]; } } /// @dev Calculate and assign the proceeds from the buyout. /// @param currentOwner The current owner of the tile that is being bought out. /// @param price The price of the tile that is being bought out. /// @param claimedSurroundingTiles The surrounding tiles that have been claimed. function _calculateAndAssignBuyoutProceeds(address currentOwner, uint256 price, uint256[] memory claimedSurroundingTiles) internal { // Calculate the variable dividends based on the buyout price // (only to be paid if there are surrounding tiles). uint256 variableDividends = price.mul(gameSettings.buyoutDividendPercentage).div(100000); // Calculate fees, referral bonus, and prize pool funds. uint256 fee = price.mul(gameSettings.buyoutFeePercentage).div(100000); uint256 referralBonus = price.mul(gameSettings.buyoutReferralBonusPercentage).div(100000); uint256 prizePoolFunds = price.mul(gameSettings.buyoutPrizePoolPercentage).div(100000); // Calculate and assign buyout proceeds. uint256 currentOwnerWinnings = price.sub(fee).sub(referralBonus.mul(2)).sub(prizePoolFunds); uint256 totalDividendPerBeneficiary; if (claimedSurroundingTiles.length > 0) { // If there are surrounding tiles, variable dividend is to be paid // based on the buyout price. // Calculate the dividend per surrounding tile. totalDividendPerBeneficiary = variableDividends / claimedSurroundingTiles.length; // currentOwnerWinnings = currentOwnerWinnings.sub(variableDividends); currentOwnerWinnings = currentOwnerWinnings.sub(totalDividendPerBeneficiary * claimedSurroundingTiles.length); } _assignBuyoutProceeds( currentOwner, claimedSurroundingTiles, fee, currentOwnerWinnings, totalDividendPerBeneficiary, referralBonus, prizePoolFunds ); } /// @dev Send funds to a beneficiary. If sending fails, assign /// funds to the beneficiary's balance for manual withdrawal. /// @param beneficiary The beneficiary's address to send funds to /// @param amount The amount to send. function _sendFunds(address beneficiary, uint256 amount) internal { if (!beneficiary.send(amount)) { // Failed to send funds. This can happen due to a failure in // fallback code of the beneficiary, or because of callstack // depth. // Send funds asynchronously for manual withdrawal by the // beneficiary. asyncSend(beneficiary, amount); } } } /// @dev Holds core game functionality. contract BurnupGameCore is BurnupGameFinance { function BurnupGameCore(address burnupHoldingAddress) public BurnupGameFinance(burnupHoldingAddress) {} /// @notice Buy the current owner out of the tile. /// @param _gameIndex The index of the game to play on. /// @param startNewGameIfIdle Start a new game if the current game is idle. /// @param x The x-coordinate of the tile to buy. /// @param y The y-coordinate of the tile to buy. function buyout(uint256 _gameIndex, bool startNewGameIfIdle, uint256 x, uint256 y) public payable { // Check to see if the game should end. Process payment. _processGameEnd(); if (!gameStates[gameIndex].gameStarted) { // If the game is not started, the contract must not be paused. require(!paused); if (allowStart) { // We're allowed to start once outside of active times. allowStart = false; } else { // This must be an active time. require(canStart()); } // If the game is not started, the player must be willing to start // a new game. require(startNewGameIfIdle); _setGameSettings(); // Start the game. gameStates[gameIndex].gameStarted = true; // Set game started timestamp. gameStates[gameIndex].gameStartTimestamp = block.timestamp; // Set the initial game board timeout. gameStates[gameIndex].penultimateTileTimeout = block.timestamp + gameSettings.initialActivityTimer; Start( gameIndex, msg.sender, block.timestamp, gameStates[gameIndex].prizePool ); PenultimateTileTimeout(gameIndex, gameStates[gameIndex].penultimateTileTimeout); } // Check the game index. if (startNewGameIfIdle) { // The given game index must be the current game index, or the previous // game index. require(_gameIndex == gameIndex || _gameIndex.add(1) == gameIndex); } else { // Only play on the game indicated by the player. require(_gameIndex == gameIndex); } uint256 identifier = coordinateToIdentifier(x, y); address currentOwner = gameStates[gameIndex].identifierToOwner[identifier]; // Tile must be unowned, or active. if (currentOwner == address(0x0)) { // Tile must still be flippable. require(gameStates[gameIndex].gameStartTimestamp.add(gameSettings.initialActivityTimer) >= block.timestamp); } else { // Tile must be active. require(gameStates[gameIndex].identifierToTimeoutTimestamp[identifier] >= block.timestamp); } // Enough Ether must be supplied. uint256 price = currentPrice(identifier); require(msg.value >= price); // Get existing surrounding tiles. uint256[] memory claimedSurroundingTiles = _claimedSurroundingTiles(identifier); // Assign the buyout proceeds and retrieve the total cost. _calculateAndAssignBuyoutProceeds(currentOwner, price, claimedSurroundingTiles); // Set the timeout timestamp. uint256 timeout = tileTimeoutTimestamp(identifier, msg.sender); gameStates[gameIndex].identifierToTimeoutTimestamp[identifier] = timeout; // Keep track of the last and penultimate tiles. if (gameStates[gameIndex].lastTile == 0 || timeout >= gameStates[gameIndex].identifierToTimeoutTimestamp[gameStates[gameIndex].lastTile]) { if (gameStates[gameIndex].lastTile != identifier) { if (gameStates[gameIndex].lastTile != 0) { // Previous last tile to become inactive is now the penultimate tile. gameStates[gameIndex].penultimateTileTimeout = gameStates[gameIndex].identifierToTimeoutTimestamp[gameStates[gameIndex].lastTile]; PenultimateTileTimeout(gameIndex, gameStates[gameIndex].penultimateTileTimeout); } gameStates[gameIndex].lastTile = identifier; LastTile(gameIndex, identifier, x, y); } } else if (timeout > gameStates[gameIndex].penultimateTileTimeout) { gameStates[gameIndex].penultimateTileTimeout = timeout; PenultimateTileTimeout(gameIndex, timeout); } // Transfer the tile. _transfer(currentOwner, msg.sender, identifier); // Calculate and set the new tile price. gameStates[gameIndex].identifierToBuyoutPrice[identifier] = nextBuyoutPrice(price); // Increment the number of tile flips. gameStates[gameIndex].numberOfTileFlips++; // Emit event Buyout(gameIndex, msg.sender, identifier, x, y, block.timestamp, timeout, gameStates[gameIndex].identifierToBuyoutPrice[identifier], gameStates[gameIndex].prizePool); // Calculate the excess Ether sent. // msg.value is greater than or equal to price, // so this cannot underflow. uint256 excess = msg.value - price; if (excess > 0) { // Refund any excess Ether (not susceptible to re-entry attack, as // the owner is assigned before the transfer takes place). msg.sender.transfer(excess); } } /// @notice Buy the current owner out of the tile. Set the player's referrer. /// @param _gameIndex The index of the game to play on. /// @param startNewGameIfIdle Start a new game if the current game is idle. /// @param x The x-coordinate of the tile to buy. /// @param y The y-coordinate of the tile to buy. function buyoutAndSetReferrer(uint256 _gameIndex, bool startNewGameIfIdle, uint256 x, uint256 y, address referrerAddress) external payable { // Set the referrer. burnupHolding.setReferrer(msg.sender, referrerAddress); // Play. buyout(_gameIndex, startNewGameIfIdle, x, y); } /// @notice Spice up the prize pool. /// @param _gameIndex The index of the game to add spice to. /// @param message An optional message to be sent along with the spice. function spiceUp(uint256 _gameIndex, string message) external payable { // Check to see if the game should end. Process payment. _processGameEnd(); // Check the game index. require(_gameIndex == gameIndex); // Game must be live or unpaused. require(gameStates[gameIndex].gameStarted || !paused); // Funds must be sent. require(msg.value > 0); // Add funds to the prize pool. gameStates[gameIndex].prizePool = gameStates[gameIndex].prizePool.add(msg.value); // Emit event. SpiceUpPrizePool(gameIndex, msg.sender, msg.value, message, gameStates[gameIndex].prizePool); } /// @notice End the game. Pay prize. function endGame() external { require(_processGameEnd()); } /// @dev End the game. Pay prize. function _processGameEnd() internal returns(bool) { // The game must be started. if (!gameStates[gameIndex].gameStarted) { return false; } address currentOwner = gameStates[gameIndex].identifierToOwner[gameStates[gameIndex].lastTile]; // The last flipped tile must be owned (i.e. there has been at // least one flip). if (currentOwner == address(0x0)) { return false; } // The penultimate tile must have become inactive. if (gameStates[gameIndex].penultimateTileTimeout >= block.timestamp) { return false; } // Assign prize pool to the owner of the last-flipped tile. if (gameStates[gameIndex].prizePool > 0) { _sendFunds(currentOwner, gameStates[gameIndex].prizePool); } // Get coordinates of last flipped tile. var (x, y) = identifierToCoordinate(gameStates[gameIndex].lastTile); // Emit event. End(gameIndex, currentOwner, gameStates[gameIndex].lastTile, x, y, gameStates[gameIndex].identifierToTimeoutTimestamp[gameStates[gameIndex].lastTile], gameStates[gameIndex].prizePool); // Increment the game index. This won't overflow before the heat death of the universe. gameIndex++; // Indicate ending the game was successful. return true; } }
* @title PullPayment @dev Base contract supporting async send for pull payments. Inherit from this contract and use asyncSend instead of send./
contract PullPayment { using SafeMath for uint256; mapping(address => uint256) public payments; uint256 public totalPayments; function withdrawPayments() public { address payee = msg.sender; uint256 payment = payments[payee]; require(payment != 0); require(this.balance >= payment); totalPayments = totalPayments.sub(payment); payments[payee] = 0; assert(payee.send(payment)); } function asyncSend(address dest, uint256 amount) internal { payments[dest] = payments[dest].add(amount); totalPayments = totalPayments.add(amount); } }
1,781,621
[ 1, 9629, 6032, 225, 3360, 6835, 22930, 4326, 1366, 364, 6892, 25754, 18, 25953, 628, 333, 6835, 471, 999, 4326, 3826, 3560, 434, 1366, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 14899, 6032, 288, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 225, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 25754, 31, 203, 225, 2254, 5034, 1071, 2078, 23725, 31, 203, 203, 225, 445, 598, 9446, 23725, 1435, 1071, 288, 203, 565, 1758, 8843, 1340, 273, 1234, 18, 15330, 31, 203, 565, 2254, 5034, 5184, 273, 25754, 63, 10239, 1340, 15533, 203, 203, 565, 2583, 12, 9261, 480, 374, 1769, 203, 565, 2583, 12, 2211, 18, 12296, 1545, 5184, 1769, 203, 203, 565, 2078, 23725, 273, 2078, 23725, 18, 1717, 12, 9261, 1769, 203, 565, 25754, 63, 10239, 1340, 65, 273, 374, 31, 203, 203, 565, 1815, 12, 10239, 1340, 18, 4661, 12, 9261, 10019, 203, 225, 289, 203, 203, 225, 445, 4326, 3826, 12, 2867, 1570, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 565, 25754, 63, 10488, 65, 273, 25754, 63, 10488, 8009, 1289, 12, 8949, 1769, 203, 565, 2078, 23725, 273, 2078, 23725, 18, 1289, 12, 8949, 1769, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x2F66C5aAF006Bd9c51615D617589C16c0ed35fD3/sources/contracts/DODOV3MM/lib/MakerTypes.sol
[ask amounts(16) | ask amounts decimal(8) | bid amounts(16) | bid amounts decimal(8) ]
function parseBidAmount(uint64 amountInfo) internal pure returns (uint256 amountWithDecimal) { uint256 bidAmount = (amountInfo >> 8) & 0xffff; uint256 bidAmountDecimal = amountInfo & 255; amountWithDecimal = bidAmount * (10 ** bidAmountDecimal); }
4,285,775
[ 1, 63, 835, 30980, 12, 2313, 13, 571, 6827, 30980, 6970, 12, 28, 13, 571, 9949, 30980, 12, 2313, 13, 571, 9949, 30980, 6970, 12, 28, 13, 308, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1109, 17763, 6275, 12, 11890, 1105, 3844, 966, 13, 2713, 16618, 1135, 261, 11890, 5034, 3844, 1190, 5749, 13, 288, 203, 3639, 2254, 5034, 9949, 6275, 273, 261, 8949, 966, 1671, 1725, 13, 473, 374, 20431, 31, 203, 3639, 2254, 5034, 9949, 6275, 5749, 273, 3844, 966, 473, 4561, 31, 203, 3639, 3844, 1190, 5749, 273, 9949, 6275, 380, 261, 2163, 2826, 9949, 6275, 5749, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.11; import "../dapp/DAPP.sol"; contract DAPPMock is DAPP { constructor (DAO dao, uint256 fee) public DAPP(dao, fee) {} // solhint-disable-line no-empty-blocks /** * @dev mock function to test fee payment */ function useFeeAction() public useFee {} // solhint-disable-line no-empty-blocks /** * @dev mock function to test using tokens */ function useTokensAction(uint256 amount) public useTokens(amount) {} // solhint-disable-line no-empty-blocks /** * @dev mock function to test using tokens and fee */ function useDappAction(uint256 amount) public useTokens(amount) useFee {} // solhint-disable-line no-empty-blocks /** * @dev mock function to test only member function */ function onlyMemberAction() public onlyMember {} // solhint-disable-line no-empty-blocks /** * @dev mock function to test only approved function */ function onlyApprovedAction() public onlyApproved {} // solhint-disable-line no-empty-blocks function memberSince(address account, uint256 date) public view returns (bool) { return dao().isMember(account) && dao().creationDateOf(account) <= date; } }
* @dev mock function to test fee payment/* @dev mock function to test using tokens/* @dev mock function to test using tokens and fee/* @dev mock function to test only member function/* @dev mock function to test only approved function/
function memberSince(address account, uint256 date) public view returns (bool) { return dao().isMember(account) && dao().creationDateOf(account) <= date; }
12,728,758
[ 1, 22851, 445, 358, 1842, 14036, 5184, 19, 225, 5416, 445, 358, 1842, 1450, 2430, 19, 225, 5416, 445, 358, 1842, 1450, 2430, 471, 14036, 19, 225, 5416, 445, 358, 1842, 1338, 3140, 445, 19, 225, 5416, 445, 358, 1842, 1338, 20412, 445, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3140, 9673, 12, 2867, 2236, 16, 2254, 5034, 1509, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 15229, 7675, 291, 4419, 12, 4631, 13, 597, 15229, 7675, 17169, 1626, 951, 12, 4631, 13, 1648, 1509, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.16; contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TheGoDgital is owned { // Public variables of the token string public name; string public symbol; uint8 public decimals=5; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TheGoDgital() public { totalSupply = 500000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = 'TheGoDgital'; // Set the name for display purposes symbol = 'TGD'; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } mapping (address => bool) public frozenAccount; /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); } /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } }
* Destroy tokens from other account Remove `_value` tokens from the system irreversibly on behalf of `_from`. @param _from the address of the sender @param _value the amount of money to burn/
function burnFrom(address _from, uint256 _value) public returns (bool success) { Burn(_from, _value); return true; } mapping (address => bool) public frozenAccount;
1,656,957
[ 1, 10740, 2430, 628, 1308, 2236, 3581, 1375, 67, 1132, 68, 2430, 628, 326, 2619, 9482, 266, 2496, 24755, 603, 12433, 6186, 434, 1375, 67, 2080, 8338, 225, 389, 2080, 326, 1758, 434, 326, 5793, 225, 389, 1132, 326, 3844, 434, 15601, 358, 18305, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18305, 1265, 12, 2867, 389, 2080, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 605, 321, 24899, 2080, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 377, 203, 377, 2874, 261, 2867, 516, 1426, 13, 1071, 12810, 3032, 31, 203, 1377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x296FffB1Aaba21650ABBfa0c88DA66CF3326fD84/sources/HumanStandardToken.sol
@return total amount of tokens
function totalSupply() public view returns (uint256 supply) {}
2,662,195
[ 1, 2463, 2078, 3844, 434, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 5034, 14467, 13, 2618, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xd16cfEE3a432C2Eb0992B1d7173aacAe59866d1d/sources/contracts/extension/plugin/PlatformFeeStorage.sol
* @author thirdweb.com/
library PlatformFeeStorage { bytes32 public constant PLATFORM_FEE_STORAGE_POSITION = keccak256("platform.fee.storage"); struct Data { address platformFeeRecipient; uint16 platformFeeBps; } function platformFeeStorage() internal pure returns (Data storage platformFeeData) { bytes32 position = PLATFORM_FEE_STORAGE_POSITION; assembly { platformFeeData.slot := position } } function platformFeeStorage() internal pure returns (Data storage platformFeeData) { bytes32 position = PLATFORM_FEE_STORAGE_POSITION; assembly { platformFeeData.slot := position } } }
5,705,327
[ 1, 451, 6909, 4875, 18, 832, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 11810, 14667, 3245, 288, 203, 565, 1731, 1578, 1071, 5381, 453, 12190, 4983, 67, 8090, 41, 67, 19009, 67, 15258, 273, 417, 24410, 581, 5034, 2932, 9898, 18, 21386, 18, 5697, 8863, 203, 203, 203, 565, 1958, 1910, 288, 203, 3639, 1758, 4072, 14667, 18241, 31, 203, 3639, 2254, 2313, 4072, 14667, 38, 1121, 31, 203, 203, 565, 289, 203, 565, 445, 4072, 14667, 3245, 1435, 2713, 16618, 1135, 261, 751, 2502, 4072, 14667, 751, 13, 288, 203, 3639, 1731, 1578, 1754, 273, 453, 12190, 4983, 67, 8090, 41, 67, 19009, 67, 15258, 31, 203, 3639, 19931, 288, 203, 5411, 4072, 14667, 751, 18, 14194, 519, 1754, 203, 3639, 289, 203, 565, 289, 203, 565, 445, 4072, 14667, 3245, 1435, 2713, 16618, 1135, 261, 751, 2502, 4072, 14667, 751, 13, 288, 203, 3639, 1731, 1578, 1754, 273, 453, 12190, 4983, 67, 8090, 41, 67, 19009, 67, 15258, 31, 203, 3639, 19931, 288, 203, 5411, 4072, 14667, 751, 18, 14194, 519, 1754, 203, 3639, 289, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x8F328Cb08474395574aA47DA981Eb1F91A6cA2a8/sources/contracts/0.8.9/LidoExecutionLayerRewardsVault.sol
* Transfers a given token_id of an ERC721-compatible NFT (defined by the token contract address) currently belonging to the burner contract address to the Lido treasury address. @param _token an ERC721-compatible token @param _tokenId minted token id/
function recoverERC721(address _token, uint256 _tokenId) external { emit ERC721Recovered(msg.sender, _token, _tokenId); IERC721(_token).transferFrom(address(this), TREASURY, _tokenId); }
11,595,728
[ 1, 1429, 18881, 279, 864, 1147, 67, 350, 434, 392, 4232, 39, 27, 5340, 17, 10943, 423, 4464, 261, 2178, 635, 326, 1147, 6835, 1758, 13, 4551, 17622, 358, 326, 18305, 264, 6835, 1758, 358, 326, 511, 22954, 9787, 345, 22498, 1758, 18, 225, 389, 2316, 392, 4232, 39, 27, 5340, 17, 10943, 1147, 225, 389, 2316, 548, 312, 474, 329, 1147, 612, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5910, 654, 39, 27, 5340, 12, 2867, 389, 2316, 16, 2254, 5034, 389, 2316, 548, 13, 3903, 288, 203, 3639, 3626, 4232, 39, 27, 5340, 426, 16810, 12, 3576, 18, 15330, 16, 389, 2316, 16, 389, 2316, 548, 1769, 203, 203, 3639, 467, 654, 39, 27, 5340, 24899, 2316, 2934, 13866, 1265, 12, 2867, 12, 2211, 3631, 399, 862, 3033, 1099, 61, 16, 389, 2316, 548, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]