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/1/0x5E684FDa40cb5e89ca616eC50C7EFF7D54792A7D/sources/contracts/SudoWassie.sol
Individual NFT Sale Price in ETH
contract SudoWassie is ERC721i, ReentrancyGuard { using Address for address payable; using Counters for Counters.Counter; event Purchase( address indexed newOwner, uint256 amount, uint256 lastTokenId ); event Withdraw(address indexed receiver, uint256 amount); event PriceUpdate(uint256 newPrice); Counters.Counter internal _lastPurchasedTokenId; string internal _baseTokenURI; uint256 public _pricePer; constructor( string memory name, string memory symbol, string memory baseUri, uint256 maxSupply ) ERC721i(name, symbol, _msgSender(), maxSupply) { _baseTokenURI = baseUri; _setApprovalForAll(_msgSender(), address(this), true); } function preMint() external onlyOwner { _preMint(); } function purchase(uint256 amount) external payable virtual nonReentrant returns (uint256 amountTransferred) { uint256 index = _lastPurchasedTokenId.current(); if (index + amount > _maxSupply) { amount = _maxSupply - index; } uint256 cost; if (_pricePer > 0) { cost = _pricePer * amount; require(msg.value >= cost, "Insufficient payment"); } uint256[] memory tokenIds = new uint256[](amount); for (uint256 i = 0; i < amount; i++) { _lastPurchasedTokenId.increment(); tokenIds[i] = _lastPurchasedTokenId.current(); } amountTransferred = _batchTransfer(owner(), _msgSender(), tokenIds); emit Purchase(_msgSender(), amount, _lastPurchasedTokenId.current()); if (msg.value > cost) { payable(_msgSender()).sendValue(msg.value - cost); } } function purchase(uint256 amount) external payable virtual nonReentrant returns (uint256 amountTransferred) { uint256 index = _lastPurchasedTokenId.current(); if (index + amount > _maxSupply) { amount = _maxSupply - index; } uint256 cost; if (_pricePer > 0) { cost = _pricePer * amount; require(msg.value >= cost, "Insufficient payment"); } uint256[] memory tokenIds = new uint256[](amount); for (uint256 i = 0; i < amount; i++) { _lastPurchasedTokenId.increment(); tokenIds[i] = _lastPurchasedTokenId.current(); } amountTransferred = _batchTransfer(owner(), _msgSender(), tokenIds); emit Purchase(_msgSender(), amount, _lastPurchasedTokenId.current()); if (msg.value > cost) { payable(_msgSender()).sendValue(msg.value - cost); } } function purchase(uint256 amount) external payable virtual nonReentrant returns (uint256 amountTransferred) { uint256 index = _lastPurchasedTokenId.current(); if (index + amount > _maxSupply) { amount = _maxSupply - index; } uint256 cost; if (_pricePer > 0) { cost = _pricePer * amount; require(msg.value >= cost, "Insufficient payment"); } uint256[] memory tokenIds = new uint256[](amount); for (uint256 i = 0; i < amount; i++) { _lastPurchasedTokenId.increment(); tokenIds[i] = _lastPurchasedTokenId.current(); } amountTransferred = _batchTransfer(owner(), _msgSender(), tokenIds); emit Purchase(_msgSender(), amount, _lastPurchasedTokenId.current()); if (msg.value > cost) { payable(_msgSender()).sendValue(msg.value - cost); } } function purchase(uint256 amount) external payable virtual nonReentrant returns (uint256 amountTransferred) { uint256 index = _lastPurchasedTokenId.current(); if (index + amount > _maxSupply) { amount = _maxSupply - index; } uint256 cost; if (_pricePer > 0) { cost = _pricePer * amount; require(msg.value >= cost, "Insufficient payment"); } uint256[] memory tokenIds = new uint256[](amount); for (uint256 i = 0; i < amount; i++) { _lastPurchasedTokenId.increment(); tokenIds[i] = _lastPurchasedTokenId.current(); } amountTransferred = _batchTransfer(owner(), _msgSender(), tokenIds); emit Purchase(_msgSender(), amount, _lastPurchasedTokenId.current()); if (msg.value > cost) { payable(_msgSender()).sendValue(msg.value - cost); } } function purchase(uint256 amount) external payable virtual nonReentrant returns (uint256 amountTransferred) { uint256 index = _lastPurchasedTokenId.current(); if (index + amount > _maxSupply) { amount = _maxSupply - index; } uint256 cost; if (_pricePer > 0) { cost = _pricePer * amount; require(msg.value >= cost, "Insufficient payment"); } uint256[] memory tokenIds = new uint256[](amount); for (uint256 i = 0; i < amount; i++) { _lastPurchasedTokenId.increment(); tokenIds[i] = _lastPurchasedTokenId.current(); } amountTransferred = _batchTransfer(owner(), _msgSender(), tokenIds); emit Purchase(_msgSender(), amount, _lastPurchasedTokenId.current()); if (msg.value > cost) { payable(_msgSender()).sendValue(msg.value - cost); } } function setPrice(uint256 newPrice) external onlyOwner { _pricePer = newPrice; emit PriceUpdate(newPrice); } function withdraw() external onlyOwner { uint256 amount = address(this).balance; address payable receiver = payable(owner()); receiver.sendValue(amount); emit Withdraw(receiver, amount); } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function batchTransfer(address to, uint256[] memory tokenIds) external virtual returns (uint256 amountTransferred) { amountTransferred = _batchTransfer(_msgSender(), to, tokenIds); } function batchTransferFrom( address from, address to, uint256[] memory tokenIds ) external virtual returns (uint256 amountTransferred) { amountTransferred = _batchTransfer(from, to, tokenIds); } function _batchTransfer( address from, address to, uint256[] memory tokenIds ) internal virtual returns (uint256 amountTransferred) { uint256 count = tokenIds.length; for (uint256 i = 0; i < count; i++) { uint256 tokenId = tokenIds[i]; if ( (ownerOf(tokenId) != from) || (!_isApprovedOrOwner(from, tokenId)) || (to == address(0)) ) { continue; } _beforeTokenTransfer(from, to, tokenId); amountTransferred += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } _balances[to] += amountTransferred; } function _batchTransfer( address from, address to, uint256[] memory tokenIds ) internal virtual returns (uint256 amountTransferred) { uint256 count = tokenIds.length; for (uint256 i = 0; i < count; i++) { uint256 tokenId = tokenIds[i]; if ( (ownerOf(tokenId) != from) || (!_isApprovedOrOwner(from, tokenId)) || (to == address(0)) ) { continue; } _beforeTokenTransfer(from, to, tokenId); amountTransferred += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } _balances[to] += amountTransferred; } function _batchTransfer( address from, address to, uint256[] memory tokenIds ) internal virtual returns (uint256 amountTransferred) { uint256 count = tokenIds.length; for (uint256 i = 0; i < count; i++) { uint256 tokenId = tokenIds[i]; if ( (ownerOf(tokenId) != from) || (!_isApprovedOrOwner(from, tokenId)) || (to == address(0)) ) { continue; } _beforeTokenTransfer(from, to, tokenId); amountTransferred += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } _balances[to] += amountTransferred; } _approve(address(0), tokenId); _balances[from] -= amountTransferred; }
16,474,068
[ 1, 29834, 423, 4464, 348, 5349, 20137, 316, 512, 2455, 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, 16351, 348, 6506, 59, 428, 1385, 353, 4232, 39, 27, 5340, 77, 16, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 5267, 364, 1758, 8843, 429, 31, 203, 565, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 203, 565, 871, 26552, 12, 203, 3639, 1758, 8808, 394, 5541, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 2254, 5034, 27231, 548, 203, 565, 11272, 203, 565, 871, 3423, 9446, 12, 2867, 8808, 5971, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 20137, 1891, 12, 11890, 5034, 394, 5147, 1769, 203, 203, 565, 9354, 87, 18, 4789, 2713, 389, 2722, 10262, 343, 8905, 1345, 548, 31, 203, 203, 565, 533, 2713, 389, 1969, 1345, 3098, 31, 203, 203, 565, 2254, 5034, 1071, 389, 8694, 2173, 31, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 508, 16, 203, 3639, 533, 3778, 3273, 16, 203, 3639, 533, 3778, 23418, 16, 203, 3639, 2254, 5034, 943, 3088, 1283, 203, 203, 565, 262, 4232, 39, 27, 5340, 77, 12, 529, 16, 3273, 16, 389, 3576, 12021, 9334, 943, 3088, 1283, 13, 288, 203, 3639, 389, 1969, 1345, 3098, 273, 23418, 31, 203, 203, 3639, 389, 542, 23461, 1290, 1595, 24899, 3576, 12021, 9334, 1758, 12, 2211, 3631, 638, 1769, 203, 565, 289, 203, 203, 565, 445, 675, 49, 474, 1435, 3903, 1338, 5541, 288, 203, 3639, 389, 1484, 49, 474, 5621, 203, 565, 289, 203, 203, 565, 445, 23701, 12, 11890, 5034, 3844, 13, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 5024, 203, 3639, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/ClonesUpgradeable.sol"; import "contracts/IAuthToken.sol"; import "contracts/ERC721Preset.sol"; /** * @title NFT contract for licenses * @notice The contract provides the issuer and the artists with the required functions to comply and evolve with the regulation */ contract LicensedNFT is ERC721Preset { using SafeMathUpgradeable for uint256; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using CountersUpgradeable for CountersUpgradeable.Counter; /* Access Control*/ bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); bytes32 public constant ISSUER_ROLE = keccak256("ISSUER_ROLE"); /* Public addresses */ address public issuer; address public artist; /* Implementation addresses */ address public authTokenImplementation; /* States */ mapping(uint256 => bool) internal frozenToken; mapping(uint256 => string) internal stateDescription; mapping(uint256 => string) internal tokenLegalURI; mapping(uint256 => address) internal authToken; mapping(uint256 => uint256) internal parentLicense; mapping(uint256 => EnumerableSetUpgradeable.UintSet) internal childLicenses; bool public subLicensesDeployementPaused; bool public authTokenDeployementPaused; /* Events */ event AuthTokensImplementationSet(address _tokenImplementation); event AuthTokenDeploymentPaused(); event AuthTokenDeploymentResumed(); event AuthTokenDeployed(uint256 _tokenId, address _authAddress); event SubLicensesDeploymentPaused(); event SubLicensesDeploymentResumed(); event SubLicenseDeployed( uint256 _parentLicense, uint256 _childLicense, address _recipient ); event SubLicenseRevoked(uint256 _tokenId); event TokenFrozen(uint256 _tokenId); event TokenUnfrozen(uint256 _tokenId); event TokenColored(uint256 _tokenId, string _stateDescription); event FreezeRequestPrinted(uint256 _tokenId); event BaseURIUpdated(string _URI); event LegalURIUpdate(uint256 _tokenId, string _newLegalURI); function initialize( string memory _name, string memory _symbol, string memory _baseTokenURI, address _admin, address _issuer, address _artist ) public initializer { super.initialize(_name, _symbol, _baseTokenURI); _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(ADMIN_ROLE, _admin); _setupRole(ISSUER_ROLE, _admin); _setupRole(ISSUER_ROLE, _issuer); subLicensesDeployementPaused = true; authTokenDeployementPaused = true; issuer = _issuer; artist = _artist; } /** * @notice Setter for the base URI of the NFTs * @param _baseURI the base URI of the NFTs */ function setBaseURI(string memory _baseURI) public { require(hasRole(ADMIN_ROLE, msg.sender), "ERR_CALLER"); _baseTokenURI = _baseURI; emit BaseURIUpdated(_baseURI); } /* Tokens control functions */ /** * @notice Freeze a particular token * @param _tokenId the id of the token */ function freezeToken(uint256 _tokenId) public { require(hasRole(ISSUER_ROLE, msg.sender), "ERR_CALLER"); frozenToken[_tokenId] = true; emit TokenFrozen(_tokenId); } /** * @notice Unfreeze a particular token * @param _tokenId the id of the token */ function unfreezeToken(uint256 _tokenId) public { require(hasRole(ISSUER_ROLE, msg.sender), "ERR_CALLER"); frozenToken[_tokenId] = false; emit TokenUnfrozen(_tokenId); } /** * @notice Color a particular token with a described state * @param _tokenId the id of the token * @param _stateDescription the description of its state */ function colorToken(uint256 _tokenId, string memory _stateDescription) public { require(hasRole(ISSUER_ROLE, msg.sender), "ERR_CALLER"); stateDescription[_tokenId] = _stateDescription; emit TokenColored(_tokenId, _stateDescription); } /** * @notice Empty tx to record a freeze request by the artist * @param _tokenId the id of the token */ function printFreezeRequest(uint256 _tokenId) public { require(msg.sender == artist, "ERR_CALLER"); emit FreezeRequestPrinted(_tokenId); } /** * @notice Issuer function to burn a token * @param _tokenId the id of the token */ function cancelToken(uint256 _tokenId) public { require(hasRole(ISSUER_ROLE, msg.sender), "ERR_CALLER"); _burn(_tokenId); } /** * @notice Update the URI for the legal contract associated with a token * @param _tokenId the id of the token * @param _legalURI the new URI of the legal contract */ function updateTokenLegalURI(uint256 _tokenId, string memory _legalURI) public { require(hasRole(ISSUER_ROLE, msg.sender), "ERR_CALLER"); tokenLegalURI[_tokenId] = _legalURI; emit LegalURIUpdate(_tokenId, _legalURI); } /* Sub Licenses */ /** * @notice Deploy a sub license of a specific token * @param _tokenId the id of the token * @param _recipient the address of the recipient of the sublicense * @param _name the name of the sublicense * @param _symbol the symbol of the sublicense * @param _legalURI the URI of the legal contract associated with the sublicense */ function deploySubLicense( uint256 _tokenId, address _recipient, string memory _name, string memory _symbol, string memory _legalURI ) public { require(hasRole(ISSUER_ROLE, msg.sender), "ERR_CALLER"); mint(_recipient, _name, _symbol, _legalURI); uint256 sublicenseID = _tokenIdTracker.current(); parentLicense[sublicenseID] = _tokenId; childLicenses[_tokenId].add(sublicenseID); emit SubLicenseDeployed(_tokenId, sublicenseID, _recipient); } /** * @notice Revoke a sublicense token * @param _subLicenseId the id of the sublicence token */ function revokeSubLicense(uint256 _subLicenseId) public { uint256 parentId = parentLicense[_subLicenseId]; require(hasRole(ISSUER_ROLE, msg.sender), "ERR_CALLER"); _burn(_subLicenseId); delete parentLicense[_subLicenseId]; childLicenses[parentId].remove(_subLicenseId); emit SubLicenseRevoked(_subLicenseId); } /** * @notice Pause the deployement of sublicenses */ function pauseSubLicenseDeployement() public { require(hasRole(ADMIN_ROLE, msg.sender), "ERR_CALLER"); subLicensesDeployementPaused = true; emit SubLicensesDeploymentPaused(); } /** * @notice Resume the deployement of sublicenses */ function resumeSubLicenseDeployement() public { require(hasRole(ADMIN_ROLE, msg.sender), "ERR_CALLER"); subLicensesDeployementPaused = false; emit SubLicensesDeploymentResumed(); } /* Auth */ function _deployAuthToken( uint256 _tokendId, string memory _name, string memory _symbol ) internal returns (address) { require( authTokenImplementation != address(0x0), "ERR_TOKEN_IMPLEMENTATION" ); address newAuth = ClonesUpgradeable.clone(authTokenImplementation); IAuthToken(newAuth).initialize(_name, _symbol, _tokendId); authToken[_tokendId] = newAuth; emit AuthTokenDeployed(_tokendId, newAuth); return newAuth; } /** * @notice Pause the deployement of auth tokens */ function pauseAuthTokenDeployement() public { require(hasRole(ADMIN_ROLE, msg.sender), "ERR_CALLER"); authTokenDeployementPaused = true; emit AuthTokenDeploymentPaused(); } /** * @notice Resume the deployement of auth tokens */ function resumeAuthTokenDeployement() public { require(hasRole(ADMIN_ROLE, msg.sender), "ERR_CALLER"); authTokenDeployementPaused = false; emit AuthTokenDeploymentResumed(); } /** * @notice Setter for the auth token implementation * @param _tokenImplementation the implementation of the auth token */ function setTokenImplementation(address _tokenImplementation) public { require(hasRole(ADMIN_ROLE, msg.sender), "ERR_CALLER"); authTokenImplementation = _tokenImplementation; emit AuthTokensImplementationSet(_tokenImplementation); } /* Getters */ /** * @notice Getter for the parent license of a token * @param _tokenId the token id * @return the token id of the parent license */ function getParentLicense(uint256 _tokenId) public view returns (uint256) { require(_exists(_tokenId), "ERR_TOKEN_ID"); return parentLicense[_tokenId]; } /** * @notice Getter for the child licenses of a token * @param _tokenId the token id * @return the token ids of the parent license */ function getChildLicenses(uint256 _tokenId) public view returns (uint256[] memory) { require(_exists(_tokenId), "ERR_TOKEN_ID"); uint256[] memory childLicensesList = new uint256[](childLicenses[_tokenId].length()); for (uint256 i = 0; i < childLicenses[_tokenId].length(); i++) { childLicensesList[i] = childLicenses[_tokenId].at(i); } return childLicensesList; } /** * @notice Getter for auth token address of a token * @param _tokenId the token id * @return the address of the auth token */ function getAuthTokenAddress(uint256 _tokenId) public view returns (address) { require(_exists(_tokenId), "ERR_TOKEN_ID"); return authToken[_tokenId]; } /** * @notice Getter for the frozen state of a token * @param _tokenId the token id * @return true if frozen, false otherwise */ function isTokenFrozen(uint256 _tokenId) public view returns (bool) { require(_exists(_tokenId), "ERR_TOKEN_ID"); return frozenToken[_tokenId]; } /** * @notice Getter decription of the state of a token * @param _tokenId the token id * @return the state of the token */ function getTokenStateDescriptionRef(uint256 _tokenId) public view returns (string memory) { require(_exists(_tokenId), "ERR_TOKEN_ID"); return stateDescription[_tokenId]; } /* Overrides */ function mint( address _to, string memory _name, string memory _symbol, string memory _legalURI ) public { require(hasRole(MINTER_ROLE, msg.sender), "ERR_CALLER"); uint256 tokenId = _tokenIdTracker.current(); _mint(_to, tokenId); _deployAuthToken(tokenId, _name, _symbol); _tokenIdTracker.increment(); tokenLegalURI[tokenId] = _legalURI; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { require(!frozenToken[tokenId], "ERR_TOKEN_FROZEN"); super._beforeTokenTransfer(from, to, tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // 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 no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMathUpgradeable { /** * @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. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * 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; } } } // SPDX-License-Identifier: MIT pragma solidity ^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 EnumerableSetUpgradeable { // 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] = valueIndex; // Replace lastvalue's index to valueIndex // 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.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library ClonesUpgradeable { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt, address deployer) internal pure returns (address predicted) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IAuthToken { function initialize( string memory _name, string memory _symbol, uint256 _tokenId ) external; function transferOwnership(address _from, address _to) external; function hasRole(bytes32 role, address account) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; /** * @dev {ERC721} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * - token ID and URI autogeneration * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ERC721Preset is Initializable, ContextUpgradeable, AccessControlEnumerableUpgradeable, ERC721EnumerableUpgradeable, ERC721BurnableUpgradeable, ERC721PausableUpgradeable { function initialize( string memory name, string memory symbol, string memory baseTokenURI ) public virtual initializer { __ERC721PresetMinterPauserAutoId_init(name, symbol, baseTokenURI); } using CountersUpgradeable for CountersUpgradeable.Counter; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); CountersUpgradeable.Counter internal _tokenIdTracker; string internal _baseTokenURI; /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * Token URIs will be autogenerated based on `baseURI` and their token IDs. * See {ERC721-tokenURI}. */ function __ERC721PresetMinterPauserAutoId_init( string memory name, string memory symbol, string memory baseTokenURI ) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); __ERC721_init_unchained(name, symbol); __ERC721Enumerable_init_unchained(); __ERC721Burnable_init_unchained(); __Pausable_init_unchained(); __ERC721Pausable_init_unchained(); __ERC721PresetMinterPauserAutoId_init_unchained(baseTokenURI); } function __ERC721PresetMinterPauserAutoId_init_unchained(string memory baseTokenURI) internal initializer { _baseTokenURI = baseTokenURI; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /** * @dev Pauses all token transfers. * * See {ERC721Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC721Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable, ERC721PausableUpgradeable) { super._beforeTokenTransfer(from, to, tokenId); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerableUpgradeable, ERC721Upgradeable, ERC721EnumerableUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } uint256[48] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // 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; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @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 _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @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 baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || 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 _owners[tokenId] != address(0); } /** * @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 = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `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); _balances[to] += 1; _owners[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 = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[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(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @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()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Enumerable_init_unchained(); } function __ERC721Enumerable_init_unchained() internal initializer { } // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @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 override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721Upgradeable.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } uint256[46] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable { function __ERC721Burnable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Burnable_init_unchained(); } function __ERC721Burnable_init_unchained() internal initializer { } /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../security/PausableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721PausableUpgradeable is Initializable, ERC721Upgradeable, PausableUpgradeable { function __ERC721Pausable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __Pausable_init_unchained(); __ERC721Pausable_init_unchained(); } function __ERC721Pausable_init_unchained() internal initializer { } /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable { function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleMemberCount(bytes32 role) external view returns (uint256); } /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); } function __AccessControlEnumerable_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping (bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @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 override returns (address) { return _roleMembers[role].at(index); } /** * @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 override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/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 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) { 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; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. 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 CountersUpgradeable { 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; } } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @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 {ERC1967Proxy-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 || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @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.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @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.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @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.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.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant alphabet = "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] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^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 IERC165Upgradeable { /** * @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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @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.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * 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, msg.sender)); * ... * } * ``` * * 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}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @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 Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if(!hasRole(role, account)) { revert(string(abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ))); } } /** * @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 override 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 override onlyRole(getRoleAdmin(role)) { _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 override onlyRole(getRoleAdmin(role)) { _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 override { 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. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; }
* @notice Revoke a sublicense token @param _subLicenseId the id of the sublicence token/
function revokeSubLicense(uint256 _subLicenseId) public { uint256 parentId = parentLicense[_subLicenseId]; require(hasRole(ISSUER_ROLE, msg.sender), "ERR_CALLER"); _burn(_subLicenseId); delete parentLicense[_subLicenseId]; childLicenses[parentId].remove(_subLicenseId); emit SubLicenseRevoked(_subLicenseId); }
5,972,382
[ 1, 29196, 279, 272, 447, 3558, 1147, 225, 389, 1717, 13211, 548, 326, 612, 434, 326, 272, 447, 802, 1147, 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 ]
[ 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, 225, 445, 18007, 1676, 13211, 12, 11890, 5034, 389, 1717, 13211, 548, 13, 1071, 288, 203, 565, 2254, 5034, 11582, 273, 982, 13211, 63, 67, 1717, 13211, 548, 15533, 203, 565, 2583, 12, 5332, 2996, 12, 25689, 57, 654, 67, 16256, 16, 1234, 18, 15330, 3631, 315, 9712, 67, 13730, 654, 8863, 203, 565, 389, 70, 321, 24899, 1717, 13211, 548, 1769, 203, 565, 1430, 982, 13211, 63, 67, 1717, 13211, 548, 15533, 203, 565, 1151, 48, 16548, 63, 2938, 548, 8009, 4479, 24899, 1717, 13211, 548, 1769, 203, 565, 3626, 2592, 13211, 10070, 14276, 24899, 1717, 13211, 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 ]
./full_match/10/0x000000000AF0BB14e1BcfaA67D76cc436dF54A47/sources/contracts/FixedWager.sol
@notice Fills a wager and starts the wager countdown @param _wagerId id of the wager p2p UserA fees have not been paid yet ETH p2m
function fillWager(uint256 _wagerId) external payable nonReentrant { Wager memory wager = wagers[_wagerId]; if (wager.isFilled) revert WagerAlreadyFilled(); if (wager.isClosed) revert WagerAlreadyClosed(); if ( refundableTimestamp[wager.wagerToken].nonrefundable < refundableTimestamp[wager.wagerToken].refundable ) { revert TokenNotApproved(); } if (msg.sender == wager.userA) revert SelfWager(); uint256 feeUserB = _calculateFee(wager.amountUserB, wager.paymentToken); if (wager.userB != address(0)) { if (msg.sender != wager.userB) revert RestrictedP2P(); uint256 feeUserA = _calculateFee( wager.amountUserA, wager.paymentToken ); if ( wager.paymentToken == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) ) { if (msg.value != wager.amountUserB) revert InvalidValue(); wager.amountUserA -= feeUserA; wager.amountUserB -= feeUserB; _transfer(payable(feeAddress), feeUserA + feeUserB); uint256 balanceBefore = IERC20(wager.paymentToken).balanceOf( address(this) ); IERC20(wager.paymentToken).safeTransferFrom( msg.sender, address(this), wager.amountUserB ); uint256 balanceAfter = IERC20(wager.paymentToken).balanceOf( address(this) ); wager.amountUserB = balanceAfter - balanceBefore; wager.amountUserA -= feeUserA; wager.amountUserB -= feeUserB; IERC20(wager.paymentToken).safeTransfer( feeAddress, feeUserA + feeUserB ); } if (createdTimes[_wagerId] + 30 days <= block.timestamp) { revert WagerExpired(); } wager.userB = msg.sender; if ( wager.paymentToken == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) ) { if (msg.value != wager.amountUserB) revert InvalidValue(); wager.amountUserB -= feeUserB; _transfer(payable(feeAddress), feeUserB); uint256 balanceBefore = IERC20(wager.paymentToken).balanceOf( address(this) ); IERC20(wager.paymentToken).safeTransferFrom( msg.sender, address(this), wager.amountUserB ); IERC20(wager.paymentToken).safeTransfer(feeAddress, feeUserB); uint256 balanceAfter = IERC20(wager.paymentToken).balanceOf( address(this) ); wager.amountUserB = balanceAfter - balanceBefore; } } endTimes[_wagerId] = wager.duration + block.timestamp; wager.isFilled = true; emit WagerFilled( _wagerId, wager.userA, wager.userB, wager.wagerToken, wager.wagerPrice ); }
3,782,618
[ 1, 28688, 279, 341, 6817, 471, 2542, 326, 341, 6817, 1056, 2378, 225, 389, 91, 6817, 548, 612, 434, 326, 341, 6817, 293, 22, 84, 2177, 37, 1656, 281, 1240, 486, 2118, 30591, 4671, 512, 2455, 293, 22, 81, 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, 565, 445, 3636, 59, 6817, 12, 11890, 5034, 389, 91, 6817, 548, 13, 3903, 8843, 429, 1661, 426, 8230, 970, 288, 203, 3639, 678, 6817, 3778, 341, 6817, 273, 341, 346, 414, 63, 67, 91, 6817, 548, 15533, 203, 203, 3639, 309, 261, 91, 6817, 18, 291, 29754, 13, 15226, 678, 6817, 9430, 29754, 5621, 203, 3639, 309, 261, 91, 6817, 18, 291, 7395, 13, 15226, 678, 6817, 9430, 7395, 5621, 203, 3639, 309, 261, 203, 5411, 16255, 429, 4921, 63, 91, 6817, 18, 91, 6817, 1345, 8009, 5836, 1734, 1074, 429, 411, 203, 5411, 16255, 429, 4921, 63, 91, 6817, 18, 91, 6817, 1345, 8009, 1734, 1074, 429, 203, 3639, 262, 288, 203, 5411, 15226, 3155, 1248, 31639, 5621, 203, 3639, 289, 203, 3639, 309, 261, 3576, 18, 15330, 422, 341, 6817, 18, 1355, 37, 13, 15226, 18954, 59, 6817, 5621, 203, 203, 3639, 2254, 5034, 14036, 1299, 38, 273, 389, 11162, 14667, 12, 91, 6817, 18, 8949, 1299, 38, 16, 341, 6817, 18, 9261, 1345, 1769, 203, 203, 3639, 309, 261, 91, 6817, 18, 1355, 38, 480, 1758, 12, 20, 3719, 288, 203, 5411, 309, 261, 3576, 18, 15330, 480, 341, 6817, 18, 1355, 38, 13, 15226, 29814, 52, 22, 52, 5621, 203, 203, 5411, 2254, 5034, 14036, 1299, 37, 273, 389, 11162, 14667, 12, 203, 7734, 341, 6817, 18, 8949, 1299, 37, 16, 203, 7734, 341, 6817, 18, 9261, 1345, 203, 5411, 11272, 203, 203, 5411, 309, 261, 203, 7734, 341, 6817, 18, 9261, 1345, 422, 203, 7734, 1758, 12, 20, 2 ]
./full_match/1/0x5D8217F64fA8620F6EE4270De2e773C4795f4cea/sources/contracts/StackedMonkeys.sol
100 tokens (dont remove the word ether bro!)
uint256 public dropPerBanana = 250 ether;
16,556,028
[ 1, 6625, 2430, 261, 72, 1580, 1206, 326, 2076, 225, 2437, 23670, 24949, 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, 5034, 1071, 3640, 2173, 38, 304, 13848, 273, 16927, 225, 2437, 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 ]
pragma solidity ^0.5.0; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { 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); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } 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; } } /** * @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 IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @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 Transfer token to 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) { _transfer(msg.sender, 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) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][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 * Emits an Approval event. * @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) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][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 * Emits an Approval event. * @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) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses. * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ 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); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ 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); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ 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); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, 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 private _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 () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @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. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _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; } } /** * @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(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); 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)); return role.bearer[account]; } } contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } contract BurnRole{ using Roles for Roles.Role; event BurnerAdded(address indexed account); event BurnerRemoved(address indexed account); Roles.Role private _burners; constructor () internal { _addBurner(msg.sender); } modifier onlyBurner() { require(isBurner(msg.sender)); _; } function isBurner(address account) public view returns (bool) { return _burners.has(account); } function addBurner(address account) public onlyBurner { _addBurner(account); } function renounceBurner() public { _removeBurner(msg.sender); } function _addBurner(address account) internal { _burners.add(account); emit BurnerAdded(account); } function _removeBurner(address account) internal { _burners.remove(account); emit BurnerRemoved(account); } } 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)); _; } 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); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return True if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @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 a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } /** * @title Pausable token * @dev ERC20 modified with pausable transfers. */ contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } contract ERC20Mintable is ERC20, MinterRole, Pausable { /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 value) public onlyMinter whenNotPaused returns (bool) { _mint(to, value); return true; } } contract ERC20Capped is ERC20Mintable { uint256 private _cap; constructor (uint256 cap) public { require(cap > 0); _cap = cap; } /** * @return the cap for the token minting. */ function cap() public view returns (uint256) { return _cap; } function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap); super._mint(account, value); } } contract ERC20Burnable is ERC20, BurnRole, Pausable { /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public onlyBurner whenNotPaused returns (bool){ _burn(msg.sender, value); return true; } } /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } 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 { // 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)); 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); 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. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. require(address(token).isContract()); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool))); } } } /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { // The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is // therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore, // it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a // cliff period of a year and a duration of four years, are safe to use. // solhint-disable not-rely-on-time using SafeMath for uint256; using SafeERC20 for IERC20; event TokensReleased(address token, uint256 amount); event TokenVestingRevoked(address token); // beneficiary of tokens after they are released address private _beneficiary; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint256 private _phase; uint256 private _start; uint256 private _duration; bool private _revocable; mapping (address => uint256) private _released; mapping (address => bool) private _revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary, gradually in a linear fashion until start + duration. By then all * of the balance will have vested. * @param beneficiary address of the beneficiary to whom vested tokens are transferred * @param phase duration in seconds of the cliff in which tokens will begin to vest * @param start the time (as Unix time) at which point vesting starts * @param duration duration in seconds of the period in which the tokens will vest * @param revocable whether the vesting is revocable or not */ constructor (address beneficiary, uint256 start, uint256 phase, uint256 duration, bool revocable) public { require(beneficiary != address(0)); require(phase >= 1); require(duration > 0); require(start.add(duration) > block.timestamp); _beneficiary = beneficiary; _revocable = revocable; _duration = duration; _phase = phase; _start = start; } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return the cliff time of the token vesting. */ function phase() public view returns (uint256) { return _phase; } /** * @return the start time of the token vesting. */ function start() public view returns (uint256) { return _start; } /** * @return the duration of the token vesting. */ function duration() public view returns (uint256) { return _duration; } /** * @return true if the vesting is revocable. */ function revocable() public view returns (bool) { return _revocable; } /** * @return the amount of the token released. */ function released(address token) public view returns (uint256) { return _released[token]; } /** * @return true if the token is revoked. */ function revoked(address token) public view returns (bool) { return _revoked[token]; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(IERC20 token) public { uint256 unreleased = _releasableAmount(token); require(unreleased > 0); _released[address(token)] = _released[address(token)].add(unreleased); token.safeTransfer(_beneficiary, unreleased); emit TokensReleased(address(token), unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(IERC20 token) public onlyOwner { require(_revocable); require(!_revoked[address(token)]); uint256 balance = token.balanceOf(address(this)); uint256 unreleased = _releasableAmount(token); uint256 refund = balance.sub(unreleased); _revoked[address(token)] = true; token.safeTransfer(owner(), refund); emit TokenVestingRevoked(address(token)); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function _releasableAmount(IERC20 token) private view returns (uint256) { return _vestedAmount(token).sub(_released[address(token)]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function _vestedAmount(IERC20 token) private view returns (uint256) { uint256 currentBalance = token.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(_released[address(token)]); if (block.timestamp < _start) { return 0; } else if (block.timestamp >= _start.add(_duration) || _revoked[address(token)]) { return totalBalance; } else { uint256 everyPhaseDuration = _duration.div(_phase); uint256 currentPhase = (block.timestamp - _start).div(everyPhaseDuration); return totalBalance.div(_phase).mul(currentPhase); } } } contract MToken is ERC20, ERC20Detailed, ERC20Pausable, ERC20Capped, ERC20Burnable { using Address for address; event TransferExtend(address indexed from, address indexed to, uint256 value, string name); constructor(string memory name, string memory symbol, uint8 decimals, uint256 cap) ERC20Pausable() ERC20Burnable() ERC20Capped(cap) ERC20Detailed(name, symbol, decimals) ERC20() public {} function mintVesting(address _to, uint256 _amount, uint256 start, uint256 phase, uint256 duration, bool revocable) public onlyMinter whenNotPaused returns (TokenVesting) { TokenVesting vesting = new TokenVesting(_to, start, phase, duration, revocable); mint(address(vesting), _amount); return vesting; } function revokeVesting(TokenVesting vesting) public onlyMinter whenNotPaused returns(bool) { require(address(vesting).isContract()); vesting.revoke(this); return true; } /** * @dev Transfer token to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @param name Custom string */ function transfer(address to, uint256 value, string memory name) public whenNotPaused returns (bool) { _transfer(msg.sender, to, value); emit TransferExtend(msg.sender, to, value, name); return true; } /** * @dev Batch transfer token. * @param tos The address list to transfer to. * @param value The amount to be transferred. */ function transfer(address[] memory tos, uint256 value) public whenNotPaused returns (bool) { require(tos.length > 0); require(tos.length <= 50); for(uint i = 0; i < tos.length; i ++){ _transfer(msg.sender, tos[i], value); } return true; } /** * @dev Batch transfer token. * @param tos The address list to transfer to. * @param values The amount list to be transferred. */ function transfer(address[] memory tos, uint256[] memory values) public whenNotPaused returns (bool) { require(tos.length > 0); require(tos.length <= 50); require(values.length == tos.length); for(uint i = 0; i < tos.length; i ++){ _transfer(msg.sender, tos[i], values[i]); } return true; } }
* @return the cliff time of the token vesting./
function phase() public view returns (uint256) { return _phase; }
2,557,720
[ 1, 2463, 326, 927, 3048, 813, 434, 326, 1147, 331, 10100, 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 ]
[ 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, 6855, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 13961, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 // Copyright 2017 Loopring Technology Limited. pragma solidity ^0.7.0; /// @title Ownable /// @author Brecht Devos - <[email protected]> /// @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. constructor() { owner = msg.sender; } /// @dev Throws if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner, "UNAUTHORIZED"); _; } /// @dev Allows the current owner to transfer control of the contract to a /// new owner. /// @param newOwner The address to transfer ownership to. function transferOwnership( address newOwner ) public virtual onlyOwner { require(newOwner != address(0), "ZERO_ADDRESS"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } } /// @title Claimable /// @author Brecht Devos - <[email protected]> /// @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, "UNAUTHORIZED"); _; } /// @dev Allows the current owner to set the pendingOwner address. /// @param newOwner The address to transfer ownership to. function transferOwnership( address newOwner ) public override onlyOwner { require(newOwner != address(0) && newOwner != owner, "INVALID_ADDRESS"); pendingOwner = newOwner; } /// @dev Allows the pendingOwner address to finalize the transfer. function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // Copyright 2017 Loopring Technology Limited. pragma experimental ABIEncoderV2; // Copyright 2017 Loopring Technology Limited. interface IAgent{} interface IAgentRegistry { /// @dev Returns whether an agent address is an agent of an account owner /// @param owner The account owner. /// @param agent The agent address /// @return True if the agent address is an agent for the account owner, else false function isAgent( address owner, address agent ) external view returns (bool); /// @dev Returns whether an agent address is an agent of all account owners /// @param owners The account owners. /// @param agent The agent address /// @return True if the agent address is an agent for the account owner, else false function isAgent( address[] calldata owners, address agent ) external view returns (bool); } // Copyright 2017 Loopring Technology Limited. /// @title IBlockVerifier /// @author Brecht Devos - <[email protected]> abstract contract IBlockVerifier is Claimable { // -- Events -- event CircuitRegistered( uint8 indexed blockType, uint16 blockSize, uint8 blockVersion ); event CircuitDisabled( uint8 indexed blockType, uint16 blockSize, uint8 blockVersion ); // -- Public functions -- /// @dev Sets the verifying key for the specified circuit. /// Every block permutation needs its own circuit and thus its own set of /// verification keys. Only a limited number of block sizes per block /// type are supported. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @param vk The verification key function registerCircuit( uint8 blockType, uint16 blockSize, uint8 blockVersion, uint[18] calldata vk ) external virtual; /// @dev Disables the use of the specified circuit. /// This will stop NEW blocks from using the given circuit, blocks that were already committed /// can still be verified. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) function disableCircuit( uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual; /// @dev Verifies blocks with the given public data and proofs. /// Verifying a block makes sure all requests handled in the block /// are correctly handled by the operator. /// @param blockType The type of block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @param publicInputs The hash of all the public data of the blocks /// @param proofs The ZK proofs proving that the blocks are correct /// @return True if the block is valid, false otherwise function verifyProofs( uint8 blockType, uint16 blockSize, uint8 blockVersion, uint[] calldata publicInputs, uint[] calldata proofs ) external virtual view returns (bool); /// @dev Checks if a circuit with the specified parameters is registered. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @return True if the circuit is registered, false otherwise function isCircuitRegistered( uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual view returns (bool); /// @dev Checks if a circuit can still be used to commit new blocks. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @return True if the circuit is enabled, false otherwise function isCircuitEnabled( uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual view returns (bool); } // Copyright 2017 Loopring Technology Limited. /// @title IDepositContract. /// @dev Contract storing and transferring funds for an exchange. /// /// ERC1155 tokens can be supported by registering pseudo token addresses calculated /// as `address(keccak256(real_token_address, token_params))`. Then the custom /// deposit contract can look up the real token address and paramsters with the /// pseudo token address before doing the transfers. /// @author Brecht Devos - <[email protected]> interface IDepositContract { /// @dev Returns if a token is suppoprted by this contract. function isTokenSupported(address token) external view returns (bool); /// @dev Transfers tokens from a user to the exchange. This function will /// be called when a user deposits funds to the exchange. /// In a simple implementation the funds are simply stored inside the /// deposit contract directly. More advanced implementations may store the funds /// in some DeFi application to earn interest, so this function could directly /// call the necessary functions to store the funds there. /// /// This function needs to throw when an error occurred! /// /// This function can only be called by the exchange. /// /// @param from The address of the account that sends the tokens. /// @param token The address of the token to transfer (`0x0` for ETH). /// @param amount The amount of tokens to transfer. /// @param extraData Opaque data that can be used by the contract to handle the deposit /// @return amountReceived The amount to deposit to the user's account in the Merkle tree function deposit( address from, address token, uint96 amount, bytes calldata extraData ) external payable returns (uint96 amountReceived); /// @dev Transfers tokens from the exchange to a user. This function will /// be called when a withdrawal is done for a user on the exchange. /// In the simplest implementation the funds are simply stored inside the /// deposit contract directly so this simply transfers the requested tokens back /// to the user. More advanced implementations may store the funds /// in some DeFi application to earn interest so the function would /// need to get those tokens back from the DeFi application first before they /// can be transferred to the user. /// /// This function needs to throw when an error occurred! /// /// This function can only be called by the exchange. /// /// @param from The address from which 'amount' tokens are transferred. /// @param to The address to which 'amount' tokens are transferred. /// @param token The address of the token to transfer (`0x0` for ETH). /// @param amount The amount of tokens transferred. /// @param extraData Opaque data that can be used by the contract to handle the withdrawal function withdraw( address from, address to, address token, uint amount, bytes calldata extraData ) external payable; /// @dev Transfers tokens (ETH not supported) for a user using the allowance set /// for the exchange. This way the approval can be used for all functionality (and /// extended functionality) of the exchange. /// Should NOT be used to deposit/withdraw user funds, `deposit`/`withdraw` /// should be used for that as they will contain specialised logic for those operations. /// This function can be called by the exchange to transfer onchain funds of users /// necessary for Agent functionality. /// /// This function needs to throw when an error occurred! /// /// This function can only be called by the exchange. /// /// @param from The address of the account that sends the tokens. /// @param to The address to which 'amount' tokens are transferred. /// @param token The address of the token to transfer (ETH is and cannot be suppported). /// @param amount The amount of tokens transferred. function transfer( address from, address to, address token, uint amount ) external payable; /// @dev Checks if the given address is used for depositing ETH or not. /// Is used while depositing to send the correct ETH amount to the deposit contract. /// /// Note that 0x0 is always registered for deposting ETH when the exchange is created! /// This function allows additional addresses to be used for depositing ETH, the deposit /// contract can implement different behaviour based on the address value. /// /// @param addr The address to check /// @return True if the address is used for depositing ETH, else false. function isETH(address addr) external view returns (bool); } // Copyright 2017 Loopring Technology Limited. /// @title ILoopringV3 /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> abstract contract ILoopringV3 is Claimable { // == Events == event ExchangeStakeDeposited(address exchangeAddr, uint amount); event ExchangeStakeWithdrawn(address exchangeAddr, uint amount); event ExchangeStakeBurned(address exchangeAddr, uint amount); event SettingsUpdated(uint time); // == Public Variables == mapping (address => uint) internal exchangeStake; address public lrcAddress; uint public totalStake; address public blockVerifierAddress; uint public forcedWithdrawalFee; uint public tokenRegistrationFeeLRCBase; uint public tokenRegistrationFeeLRCDelta; uint8 public protocolTakerFeeBips; uint8 public protocolMakerFeeBips; address payable public protocolFeeVault; // == Public Functions == /// @dev Updates the global exchange settings. /// This function can only be called by the owner of this contract. /// /// Warning: these new values will be used by existing and /// new Loopring exchanges. function updateSettings( address payable _protocolFeeVault, // address(0) not allowed address _blockVerifierAddress, // address(0) not allowed uint _forcedWithdrawalFee ) external virtual; /// @dev Updates the global protocol fee settings. /// This function can only be called by the owner of this contract. /// /// Warning: these new values will be used by existing and /// new Loopring exchanges. function updateProtocolFeeSettings( uint8 _protocolTakerFeeBips, uint8 _protocolMakerFeeBips ) external virtual; /// @dev Gets the amount of staked LRC for an exchange. /// @param exchangeAddr The address of the exchange /// @return stakedLRC The amount of LRC function getExchangeStake( address exchangeAddr ) public virtual view returns (uint stakedLRC); /// @dev Burns a certain amount of staked LRC for a specific exchange. /// This function is meant to be called only from exchange contracts. /// @return burnedLRC The amount of LRC burned. If the amount is greater than /// the staked amount, all staked LRC will be burned. function burnExchangeStake( uint amount ) external virtual returns (uint burnedLRC); /// @dev Stakes more LRC for an exchange. /// @param exchangeAddr The address of the exchange /// @param amountLRC The amount of LRC to stake /// @return stakedLRC The total amount of LRC staked for the exchange function depositExchangeStake( address exchangeAddr, uint amountLRC ) external virtual returns (uint stakedLRC); /// @dev Withdraws a certain amount of staked LRC for an exchange to the given address. /// This function is meant to be called only from within exchange contracts. /// @param recipient The address to receive LRC /// @param requestedAmount The amount of LRC to withdraw /// @return amountLRC The amount of LRC withdrawn function withdrawExchangeStake( address recipient, uint requestedAmount ) external virtual returns (uint amountLRC); /// @dev Gets the protocol fee values for an exchange. /// @return takerFeeBips The protocol taker fee /// @return makerFeeBips The protocol maker fee function getProtocolFeeValues( ) public virtual view returns ( uint8 takerFeeBips, uint8 makerFeeBips ); } /// @title ExchangeData /// @dev All methods in this lib are internal, therefore, there is no need /// to deploy this library independently. /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library ExchangeData { // -- Enums -- enum TransactionType { NOOP, DEPOSIT, WITHDRAWAL, TRANSFER, SPOT_TRADE, ACCOUNT_UPDATE, AMM_UPDATE } // -- Structs -- struct Token { address token; } struct ProtocolFeeData { uint32 syncedAt; // only valid before 2105 (85 years to go) uint8 takerFeeBips; uint8 makerFeeBips; uint8 previousTakerFeeBips; uint8 previousMakerFeeBips; } // General auxiliary data for each conditional transaction struct AuxiliaryData { uint txIndex; bytes data; } // This is the (virtual) block the owner needs to submit onchain to maintain the // per-exchange (virtual) blockchain. struct Block { uint8 blockType; uint16 blockSize; uint8 blockVersion; bytes data; uint256[8] proof; // Whether we should store the @BlockInfo for this block on-chain. bool storeBlockInfoOnchain; // Block specific data that is only used to help process the block on-chain. // It is not used as input for the circuits and it is not necessary for data-availability. AuxiliaryData[] auxiliaryData; // Arbitrary data, mainly for off-chain data-availability, i.e., // the multihash of the IPFS file that contains the block data. bytes offchainData; } struct BlockInfo { // The time the block was submitted on-chain. uint32 timestamp; // The public data hash of the block (the 28 most significant bytes). bytes28 blockDataHash; } // Represents an onchain deposit request. struct Deposit { uint96 amount; uint64 timestamp; } // A forced withdrawal request. // If the actual owner of the account initiated the request (we don't know who the owner is // at the time the request is being made) the full balance will be withdrawn. struct ForcedWithdrawal { address owner; uint64 timestamp; } struct Constants { uint SNARK_SCALAR_FIELD; uint MAX_OPEN_FORCED_REQUESTS; uint MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE; uint TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS; uint MAX_NUM_ACCOUNTS; uint MAX_NUM_TOKENS; uint MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED; uint MIN_TIME_IN_SHUTDOWN; uint TX_DATA_AVAILABILITY_SIZE; uint MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND; } function SNARK_SCALAR_FIELD() internal pure returns (uint) { // This is the prime number that is used for the alt_bn128 elliptic curve, see EIP-196. return 21888242871839275222246405745257275088548364400416034343698204186575808495617; } function MAX_OPEN_FORCED_REQUESTS() internal pure returns (uint16) { return 4096; } function MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE() internal pure returns (uint32) { return 15 days; } function TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS() internal pure returns (uint32) { return 7 days; } function MAX_NUM_ACCOUNTS() internal pure returns (uint) { return 2 ** 32; } function MAX_NUM_TOKENS() internal pure returns (uint) { return 2 ** 16; } function MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED() internal pure returns (uint32) { return 7 days; } function MIN_TIME_IN_SHUTDOWN() internal pure returns (uint32) { return 30 days; } // The amount of bytes each rollup transaction uses in the block data for data-availability. // This is the maximum amount of bytes of all different transaction types. function TX_DATA_AVAILABILITY_SIZE() internal pure returns (uint32) { return 68; } function MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND() internal pure returns (uint32) { return 15 days; } function ACCOUNTID_PROTOCOLFEE() internal pure returns (uint32) { return 0; } function TX_DATA_AVAILABILITY_SIZE_PART_1() internal pure returns (uint32) { return 29; } function TX_DATA_AVAILABILITY_SIZE_PART_2() internal pure returns (uint32) { return 39; } struct AccountLeaf { uint32 accountID; address owner; uint pubKeyX; uint pubKeyY; uint32 nonce; uint feeBipsAMM; } struct BalanceLeaf { uint16 tokenID; uint96 balance; uint96 weightAMM; uint storageRoot; } struct MerkleProof { ExchangeData.AccountLeaf accountLeaf; ExchangeData.BalanceLeaf balanceLeaf; uint[48] accountMerkleProof; uint[24] balanceMerkleProof; } struct BlockContext { bytes32 DOMAIN_SEPARATOR; uint32 timestamp; } // Represents the entire exchange state except the owner of the exchange. struct State { uint32 maxAgeDepositUntilWithdrawable; bytes32 DOMAIN_SEPARATOR; ILoopringV3 loopring; IBlockVerifier blockVerifier; IAgentRegistry agentRegistry; IDepositContract depositContract; // The merkle root of the offchain data stored in a Merkle tree. The Merkle tree // stores balances for users using an account model. bytes32 merkleRoot; // List of all blocks mapping(uint => BlockInfo) blocks; uint numBlocks; // List of all tokens Token[] tokens; // A map from a token to its tokenID + 1 mapping (address => uint16) tokenToTokenId; // A map from an accountID to a tokenID to if the balance is withdrawn mapping (uint32 => mapping (uint16 => bool)) withdrawnInWithdrawMode; // A map from an account to a token to the amount withdrawable for that account. // This is only used when the automatic distribution of the withdrawal failed. mapping (address => mapping (uint16 => uint)) amountWithdrawable; // A map from an account to a token to the forced withdrawal (always full balance) mapping (uint32 => mapping (uint16 => ForcedWithdrawal)) pendingForcedWithdrawals; // A map from an address to a token to a deposit mapping (address => mapping (uint16 => Deposit)) pendingDeposits; // A map from an account owner to an approved transaction hash to if the transaction is approved or not mapping (address => mapping (bytes32 => bool)) approvedTx; // A map from an account owner to a destination address to a tokenID to an amount to a storageID to a new recipient address mapping (address => mapping (address => mapping (uint16 => mapping (uint => mapping (uint32 => address))))) withdrawalRecipient; // Counter to keep track of how many of forced requests are open so we can limit the work that needs to be done by the owner uint32 numPendingForcedTransactions; // Cached data for the protocol fee ProtocolFeeData protocolFeeData; // Time when the exchange was shutdown uint shutdownModeStartTime; // Time when the exchange has entered withdrawal mode uint withdrawalModeStartTime; // Last time the protocol fee was withdrawn for a specific token mapping (address => uint) protocolFeeLastWithdrawnTime; } } // Copyright 2017 Loopring Technology Limited. abstract contract ERC1271 { // bytes4(keccak256("isValidSignature(bytes32,bytes)") bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e; function isValidSignature( bytes32 _hash, bytes memory _signature) public view virtual returns (bytes4 magicValueB32); } // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for uint /// @author Daniel Wang - <[email protected]> library MathUint { using MathUint for uint; function mul( uint a, uint b ) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b, "MUL_OVERFLOW"); } function sub( uint a, uint b ) internal pure returns (uint) { require(b <= a, "SUB_UNDERFLOW"); return a - b; } function add( uint a, uint b ) internal pure returns (uint c) { c = a + b; require(c >= a, "ADD_OVERFLOW"); } function add64( uint64 a, uint64 b ) internal pure returns (uint64 c) { c = a + b; require(c >= a, "ADD_OVERFLOW"); } } // Copyright 2017 Loopring Technology Limited. interface IAmmSharedConfig { function maxForcedExitAge() external view returns (uint); function maxForcedExitCount() external view returns (uint); function forcedExitFee() external view returns (uint); } // Copyright 2017 Loopring Technology Limited. // Copyright 2017 Loopring Technology Limited. /// @title IExchangeV3 /// @dev Note that Claimable and RentrancyGuard are inherited here to /// ensure all data members are declared on IExchangeV3 to make it /// easy to support upgradability through proxies. /// /// Subclasses of this contract must NOT define constructor to /// initialize data. /// /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> abstract contract IExchangeV3 is Claimable { // -- Events -- event ExchangeCloned( address exchangeAddress, address owner, bytes32 genesisMerkleRoot ); event TokenRegistered( address token, uint16 tokenId ); event Shutdown( uint timestamp ); event WithdrawalModeActivated( uint timestamp ); event BlockSubmitted( uint indexed blockIdx, bytes32 merkleRoot, bytes32 publicDataHash ); event DepositRequested( address from, address to, address token, uint16 tokenId, uint96 amount ); event ForcedWithdrawalRequested( address owner, address token, uint32 accountID ); event WithdrawalCompleted( uint8 category, address from, address to, address token, uint amount ); event WithdrawalFailed( uint8 category, address from, address to, address token, uint amount ); event ProtocolFeesUpdated( uint8 takerFeeBips, uint8 makerFeeBips, uint8 previousTakerFeeBips, uint8 previousMakerFeeBips ); event TransactionApproved( address owner, bytes32 transactionHash ); // events from libraries /*event DepositProcessed( address to, uint32 toAccountId, uint16 token, uint amount );*/ /*event ForcedWithdrawalProcessed( uint32 fromAccountID, uint16 tokenID, uint amount );*/ /*event ConditionalTransferProcessed( address from, address to, uint16 token, uint amount );*/ /*event AccountUpdated( uint32 owner, uint publicKey );*/ // -- Initialization -- /// @dev Initializes this exchange. This method can only be called once. /// @param loopring The LoopringV3 contract address. /// @param owner The owner of this exchange. /// @param genesisMerkleRoot The initial Merkle tree state. function initialize( address loopring, address owner, bytes32 genesisMerkleRoot ) virtual external; /// @dev Initialized the agent registry contract used by the exchange. /// Can only be called by the exchange owner once. /// @param agentRegistry The agent registry contract to be used function setAgentRegistry(address agentRegistry) external virtual; /// @dev Gets the agent registry contract used by the exchange. /// @return the agent registry contract function getAgentRegistry() external virtual view returns (IAgentRegistry); /// Can only be called by the exchange owner once. /// @param depositContract The deposit contract to be used function setDepositContract(address depositContract) external virtual; /// @dev Gets the deposit contract used by the exchange. /// @return the deposit contract function getDepositContract() external virtual view returns (IDepositContract); // @dev Exchange owner withdraws fees from the exchange. // @param token Fee token address // @param feeRecipient Fee recipient address function withdrawExchangeFees( address token, address feeRecipient ) external virtual; // -- Constants -- /// @dev Returns a list of constants used by the exchange. /// @return constants The list of constants. function getConstants() external virtual pure returns(ExchangeData.Constants memory); // -- Mode -- /// @dev Returns hether the exchange is in withdrawal mode. /// @return Returns true if the exchange is in withdrawal mode, else false. function isInWithdrawalMode() external virtual view returns (bool); /// @dev Returns whether the exchange is shutdown. /// @return Returns true if the exchange is shutdown, else false. function isShutdown() external virtual view returns (bool); // -- Tokens -- /// @dev Registers an ERC20 token for a token id. Note that different exchanges may have /// different ids for the same ERC20 token. /// /// Please note that 1 is reserved for Ether (ETH), 2 is reserved for Wrapped Ether (ETH), /// and 3 is reserved for Loopring Token (LRC). /// /// This function is only callable by the exchange owner. /// /// @param tokenAddress The token's address /// @return tokenID The token's ID in this exchanges. function registerToken( address tokenAddress ) external virtual returns (uint16 tokenID); /// @dev Returns the id of a registered token. /// @param tokenAddress The token's address /// @return tokenID The token's ID in this exchanges. function getTokenID( address tokenAddress ) external virtual view returns (uint16 tokenID); /// @dev Returns the address of a registered token. /// @param tokenID The token's ID in this exchanges. /// @return tokenAddress The token's address function getTokenAddress( uint16 tokenID ) external virtual view returns (address tokenAddress); // -- Stakes -- /// @dev Gets the amount of LRC the owner has staked onchain for this exchange. /// The stake will be burned if the exchange does not fulfill its duty by /// processing user requests in time. Please note that order matching may potentially /// performed by another party and is not part of the exchange's duty. /// /// @return The amount of LRC staked function getExchangeStake() external virtual view returns (uint); /// @dev Withdraws the amount staked for this exchange. /// This can only be done if the exchange has been correctly shutdown: /// - The exchange owner has shutdown the exchange /// - All deposit requests are processed /// - All funds are returned to the users (merkle root is reset to initial state) /// /// Can only be called by the exchange owner. /// /// @return amountLRC The amount of LRC withdrawn function withdrawExchangeStake( address recipient ) external virtual returns (uint amountLRC); /// @dev Can by called by anyone to burn the stake of the exchange when certain /// conditions are fulfilled. /// /// Currently this will only burn the stake of the exchange if /// the exchange is in withdrawal mode. function burnExchangeStake() external virtual; // -- Blocks -- /// @dev Gets the current Merkle root of this exchange's virtual blockchain. /// @return The current Merkle root. function getMerkleRoot() external virtual view returns (bytes32); /// @dev Gets the height of this exchange's virtual blockchain. The block height for a /// new exchange is 1. /// @return The virtual blockchain height which is the index of the last block. function getBlockHeight() external virtual view returns (uint); /// @dev Gets some minimal info of a previously submitted block that's kept onchain. /// A DEX can use this function to implement a payment receipt verification /// contract with a challange-response scheme. /// @param blockIdx The block index. function getBlockInfo(uint blockIdx) external virtual view returns (ExchangeData.BlockInfo memory); /// @dev Sumbits new blocks to the rollup blockchain. /// /// This function can only be called by the exchange operator. /// /// @param blocks The blocks being submitted /// - blockType: The type of the new block /// - blockSize: The number of onchain or offchain requests/settlements /// that have been processed in this block /// - blockVersion: The circuit version to use for verifying the block /// - storeBlockInfoOnchain: If the block info for this block needs to be stored on-chain /// - data: The data for this block /// - offchainData: Arbitrary data, mainly for off-chain data-availability, i.e., /// the multihash of the IPFS file that contains the block data. function submitBlocks(ExchangeData.Block[] calldata blocks) external virtual; /// @dev Gets the number of available forced request slots. /// @return The number of available slots. function getNumAvailableForcedSlots() external virtual view returns (uint); // -- Deposits -- /// @dev Deposits Ether or ERC20 tokens to the specified account. /// /// This function is only callable by an agent of 'from'. /// /// A fee to the owner is paid in ETH to process the deposit. /// The operator is not forced to do the deposit and the user can send /// any fee amount. /// /// @param from The address that deposits the funds to the exchange /// @param to The account owner's address receiving the funds /// @param tokenAddress The address of the token, use `0x0` for Ether. /// @param amount The amount of tokens to deposit /// @param auxiliaryData Optional extra data used by the deposit contract function deposit( address from, address to, address tokenAddress, uint96 amount, bytes calldata auxiliaryData ) external virtual payable; /// @dev Gets the amount of tokens that may be added to the owner's account. /// @param owner The destination address for the amount deposited. /// @param tokenAddress The address of the token, use `0x0` for Ether. /// @return The amount of tokens pending. function getPendingDepositAmount( address owner, address tokenAddress ) external virtual view returns (uint96); // -- Withdrawals -- /// @dev Submits an onchain request to force withdraw Ether or ERC20 tokens. /// This request always withdraws the full balance. /// /// This function is only callable by an agent of the account. /// /// The total fee in ETH that the user needs to pay is 'withdrawalFee'. /// If the user sends too much ETH the surplus is sent back immediately. /// /// Note that after such an operation, it will take the owner some /// time (no more than MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE) to process the request /// and create the deposit to the offchain account. /// /// @param owner The expected owner of the account /// @param tokenAddress The address of the token, use `0x0` for Ether. /// @param accountID The address the account in the Merkle tree. function forceWithdraw( address owner, address tokenAddress, uint32 accountID ) external virtual payable; /// @dev Checks if a forced withdrawal is pending for an account balance. /// @param accountID The accountID of the account to check. /// @param token The token address /// @return True if a request is pending, false otherwise function isForcedWithdrawalPending( uint32 accountID, address token ) external virtual view returns (bool); /// @dev Submits an onchain request to withdraw Ether or ERC20 tokens from the /// protocol fees account. The complete balance is always withdrawn. /// /// Anyone can request a withdrawal of the protocol fees. /// /// Note that after such an operation, it will take the owner some /// time (no more than MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE) to process the request /// and create the deposit to the offchain account. /// /// @param tokenAddress The address of the token, use `0x0` for Ether. function withdrawProtocolFees( address tokenAddress ) external virtual payable; /// @dev Gets the time the protocol fee for a token was last withdrawn. /// @param tokenAddress The address of the token, use `0x0` for Ether. /// @return The time the protocol fee was last withdrawn. function getProtocolFeeLastWithdrawnTime( address tokenAddress ) external virtual view returns (uint); /// @dev Allows anyone to withdraw funds for a specified user using the balances stored /// in the Merkle tree. The funds will be sent to the owner of the acount. /// /// Can only be used in withdrawal mode (i.e. when the owner has stopped /// committing blocks and is not able to commit any more blocks). /// /// This will NOT modify the onchain merkle root! The merkle root stored /// onchain will remain the same after the withdrawal. We store if the user /// has withdrawn the balance in State.withdrawnInWithdrawMode. /// /// @param merkleProof The Merkle inclusion proof function withdrawFromMerkleTree( ExchangeData.MerkleProof calldata merkleProof ) external virtual; /// @dev Checks if the balance for the account was withdrawn with `withdrawFromMerkleTree`. /// @param accountID The accountID of the balance to check. /// @param token The token address /// @return True if it was already withdrawn, false otherwise function isWithdrawnInWithdrawalMode( uint32 accountID, address token ) external virtual view returns (bool); /// @dev Allows withdrawing funds deposited to the contract in a deposit request when /// it was never processed by the owner within the maximum time allowed. /// /// Can be called by anyone. The deposited tokens will be sent back to /// the owner of the account they were deposited in. /// /// @param owner The address of the account the withdrawal was done for. /// @param token The token address function withdrawFromDepositRequest( address owner, address token ) external virtual; /// @dev Allows withdrawing funds after a withdrawal request (either onchain /// or offchain) was submitted in a block by the operator. /// /// Can be called by anyone. The withdrawn tokens will be sent to /// the owner of the account they were withdrawn out. /// /// Normally it is should not be needed for users to call this manually. /// Funds from withdrawal requests will be sent to the account owner /// immediately by the owner when the block is submitted. /// The user will however need to call this manually if the transfer failed. /// /// Tokens and owners must have the same size. /// /// @param owners The addresses of the account the withdrawal was done for. /// @param tokens The token addresses function withdrawFromApprovedWithdrawals( address[] calldata owners, address[] calldata tokens ) external virtual; /// @dev Gets the amount that can be withdrawn immediately with `withdrawFromApprovedWithdrawals`. /// @param owner The address of the account the withdrawal was done for. /// @param token The token address /// @return The amount withdrawable function getAmountWithdrawable( address owner, address token ) external virtual view returns (uint); /// @dev Notifies the exchange that the owner did not process a forced request. /// If this is indeed the case, the exchange will enter withdrawal mode. /// /// Can be called by anyone. /// /// @param accountID The accountID the forced request was made for /// @param token The token address of the the forced request function notifyForcedRequestTooOld( uint32 accountID, address token ) external virtual; /// @dev Allows a withdrawal to be done to an adddresss that is different /// than initialy specified in the withdrawal request. This can be used to /// implement functionality like fast withdrawals. /// /// This function can only be called by an agent. /// /// @param from The address of the account that does the withdrawal. /// @param to The address to which 'amount' tokens were going to be withdrawn. /// @param token The address of the token that is withdrawn ('0x0' for ETH). /// @param amount The amount of tokens that are going to be withdrawn. /// @param storageID The storageID of the withdrawal request. /// @param newRecipient The new recipient address of the withdrawal. function setWithdrawalRecipient( address from, address to, address token, uint96 amount, uint32 storageID, address newRecipient ) external virtual; /// @dev Gets the withdrawal recipient. /// /// @param from The address of the account that does the withdrawal. /// @param to The address to which 'amount' tokens were going to be withdrawn. /// @param token The address of the token that is withdrawn ('0x0' for ETH). /// @param amount The amount of tokens that are going to be withdrawn. /// @param storageID The storageID of the withdrawal request. function getWithdrawalRecipient( address from, address to, address token, uint96 amount, uint32 storageID ) external virtual view returns (address); /// @dev Allows an agent to transfer ERC-20 tokens for a user using the allowance /// the user has set for the exchange. This way the user only needs to approve a single exchange contract /// for all exchange/agent features, which allows for a more seamless user experience. /// /// This function can only be called by an agent. /// /// @param from The address of the account that sends the tokens. /// @param to The address to which 'amount' tokens are transferred. /// @param token The address of the token to transfer (ETH is and cannot be suppported). /// @param amount The amount of tokens transferred. function onchainTransferFrom( address from, address to, address token, uint amount ) external virtual; /// @dev Allows an agent to approve a rollup tx. /// /// This function can only be called by an agent. /// /// @param owner The owner of the account /// @param txHash The hash of the transaction function approveTransaction( address owner, bytes32 txHash ) external virtual; /// @dev Allows an agent to approve multiple rollup txs. /// /// This function can only be called by an agent. /// /// @param owners The account owners /// @param txHashes The hashes of the transactions function approveTransactions( address[] calldata owners, bytes32[] calldata txHashes ) external virtual; /// @dev Checks if a rollup tx is approved using the tx's hash. /// /// @param owner The owner of the account that needs to authorize the tx /// @param txHash The hash of the transaction /// @return True if the tx is approved, else false function isTransactionApproved( address owner, bytes32 txHash ) external virtual view returns (bool); // -- Admins -- /// @dev Sets the max time deposits have to wait before becoming withdrawable. /// @param newValue The new value. /// @return The old value. function setMaxAgeDepositUntilWithdrawable( uint32 newValue ) external virtual returns (uint32); /// @dev Returns the max time deposits have to wait before becoming withdrawable. /// @return The value. function getMaxAgeDepositUntilWithdrawable() external virtual view returns (uint32); /// @dev Shuts down the exchange. /// Once the exchange is shutdown all onchain requests are permanently disabled. /// When all requirements are fulfilled the exchange owner can withdraw /// the exchange stake with withdrawStake. /// /// Note that the exchange can still enter the withdrawal mode after this function /// has been invoked successfully. To prevent entering the withdrawal mode before the /// the echange stake can be withdrawn, all withdrawal requests still need to be handled /// for at least MIN_TIME_IN_SHUTDOWN seconds. /// /// Can only be called by the exchange owner. /// /// @return success True if the exchange is shutdown, else False function shutdown() external virtual returns (bool success); /// @dev Gets the protocol fees for this exchange. /// @return syncedAt The timestamp the protocol fees were last updated /// @return takerFeeBips The protocol taker fee /// @return makerFeeBips The protocol maker fee /// @return previousTakerFeeBips The previous protocol taker fee /// @return previousMakerFeeBips The previous protocol maker fee function getProtocolFeeValues() external virtual view returns ( uint32 syncedAt, uint8 takerFeeBips, uint8 makerFeeBips, uint8 previousTakerFeeBips, uint8 previousMakerFeeBips ); /// @dev Gets the domain separator used in this exchange. function getDomainSeparator() external virtual view returns (bytes32); } // Copyright 2017 Loopring Technology Limited. //Mainly taken from https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol library BytesUtil { function concat( bytes memory _preBytes, bytes memory _postBytes ) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function slice( bytes memory _bytes, uint _start, uint _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length)); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) { require(_bytes.length >= (_start + 20)); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) { require(_bytes.length >= (_start + 1)); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) { require(_bytes.length >= (_start + 2)); uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint24(bytes memory _bytes, uint _start) internal pure returns (uint24) { require(_bytes.length >= (_start + 3)); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) { require(_bytes.length >= (_start + 4)); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) { require(_bytes.length >= (_start + 8)); uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) { require(_bytes.length >= (_start + 12)); uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) { require(_bytes.length >= (_start + 16)); uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) { require(_bytes.length >= (_start + 32)); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes4(bytes memory _bytes, uint _start) internal pure returns (bytes4) { require(_bytes.length >= (_start + 4)); bytes4 tempBytes4; assembly { tempBytes4 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes4; } function toBytes20(bytes memory _bytes, uint _start) internal pure returns (bytes20) { require(_bytes.length >= (_start + 20)); bytes20 tempBytes20; assembly { tempBytes20 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes20; } function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) { require(_bytes.length >= (_start + 32)); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function fastSHA256( bytes memory data ) internal view returns (bytes32) { bytes32[] memory result = new bytes32[](1); bool success; assembly { let ptr := add(data, 32) success := staticcall(sub(gas(), 2000), 2, ptr, mload(data), add(result, 32), 32) } require(success, "SHA256_FAILED"); return result[0]; } } // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for addresses /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library AddressUtil { using AddressUtil for *; function isContract( address addr ) 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; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(addr) } return (codehash != 0x0 && codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470); } function toPayable( address addr ) internal pure returns (address payable) { return payable(addr); } // Works like address.send but with a customizable gas limit // Make sure your code is safe for reentrancy when using this function! function sendETH( address to, uint amount, uint gasLimit ) internal returns (bool success) { if (amount == 0) { return true; } address payable recipient = to.toPayable(); /* solium-disable-next-line */ (success, ) = recipient.call{value: amount, gas: gasLimit}(""); } // Works like address.transfer but with a customizable gas limit // Make sure your code is safe for reentrancy when using this function! function sendETHAndVerify( address to, uint amount, uint gasLimit ) internal returns (bool success) { success = to.sendETH(amount, gasLimit); require(success, "TRANSFER_FAILURE"); } // Works like call but is slightly more efficient when data // needs to be copied from memory to do the call. function fastCall( address to, uint gasLimit, uint value, bytes memory data ) internal returns (bool success, bytes memory returnData) { if (to != address(0)) { assembly { // Do the call success := call(gasLimit, to, value, add(data, 32), mload(data), 0, 0) // Copy the return data let size := returndatasize() returnData := mload(0x40) mstore(returnData, size) returndatacopy(add(returnData, 32), 0, size) // Update free memory pointer mstore(0x40, add(returnData, add(32, size))) } } } // Like fastCall, but throws when the call is unsuccessful. function fastCallAndVerify( address to, uint gasLimit, uint value, bytes memory data ) internal returns (bytes memory returnData) { bool success; (success, returnData) = fastCall(to, gasLimit, value, data); if (!success) { assembly { revert(add(returnData, 32), mload(returnData)) } } } } /// @title SignatureUtil /// @author Daniel Wang - <[email protected]> /// @dev This method supports multihash standard. Each signature's last byte indicates /// the signature's type. library SignatureUtil { using BytesUtil for bytes; using MathUint for uint; using AddressUtil for address; enum SignatureType { ILLEGAL, INVALID, EIP_712, ETH_SIGN, WALLET // deprecated } bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e; function verifySignatures( bytes32 signHash, address[] memory signers, bytes[] memory signatures ) internal view returns (bool) { require(signers.length == signatures.length, "BAD_SIGNATURE_DATA"); address lastSigner; for (uint i = 0; i < signers.length; i++) { require(signers[i] > lastSigner, "INVALID_SIGNERS_ORDER"); lastSigner = signers[i]; if (!verifySignature(signHash, signers[i], signatures[i])) { return false; } } return true; } function verifySignature( bytes32 signHash, address signer, bytes memory signature ) internal view returns (bool) { if (signer == address(0)) { return false; } return signer.isContract()? verifyERC1271Signature(signHash, signer, signature): verifyEOASignature(signHash, signer, signature); } function recoverECDSASigner( bytes32 signHash, bytes memory signature ) internal pure returns (address) { if (signature.length != 65) { return address(0); } bytes32 r; bytes32 s; uint8 v; // we jump 32 (0x20) as the first slot of bytes contains the length // we jump 65 (0x41) per signature // for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := and(mload(add(signature, 0x41)), 0xff) } // See https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/ECDSA.sol if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v == 27 || v == 28) { return ecrecover(signHash, v, r, s); } else { return address(0); } } function verifyEOASignature( bytes32 signHash, address signer, bytes memory signature ) private pure returns (bool success) { if (signer == address(0)) { return false; } uint signatureTypeOffset = signature.length.sub(1); SignatureType signatureType = SignatureType(signature.toUint8(signatureTypeOffset)); // Strip off the last byte of the signature by updating the length assembly { mstore(signature, signatureTypeOffset) } if (signatureType == SignatureType.EIP_712) { success = (signer == recoverECDSASigner(signHash, signature)); } else if (signatureType == SignatureType.ETH_SIGN) { bytes32 hash = keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", signHash) ); success = (signer == recoverECDSASigner(hash, signature)); } else { success = false; } // Restore the signature length assembly { mstore(signature, add(signatureTypeOffset, 1)) } return success; } function verifyERC1271Signature( bytes32 signHash, address signer, bytes memory signature ) private view returns (bool) { bytes memory callData = abi.encodeWithSelector( ERC1271.isValidSignature.selector, signHash, signature ); (bool success, bytes memory result) = signer.staticcall(callData); return ( success && result.length == 32 && result.toBytes4(0) == ERC1271_MAGICVALUE ); } } // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for uint /// @author Daniel Wang - <[email protected]> library MathUint96 { function add( uint96 a, uint96 b ) internal pure returns (uint96 c) { c = a + b; require(c >= a, "ADD_OVERFLOW"); } function sub( uint96 a, uint96 b ) internal pure returns (uint96 c) { require(b <= a, "SUB_UNDERFLOW"); return a - b; } } // Copyright 2017 Loopring Technology Limited. library EIP712 { struct Domain { string name; string version; address verifyingContract; } bytes32 constant internal EIP712_DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); string constant internal EIP191_HEADER = "\x19\x01"; function hash(Domain memory domain) internal pure returns (bytes32) { uint _chainid; assembly { _chainid := chainid() } return keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(domain.name)), keccak256(bytes(domain.version)), _chainid, domain.verifyingContract ) ); } function hashPacked( bytes32 domainHash, bytes32 dataHash ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( EIP191_HEADER, domainHash, dataHash ) ); } } // Copyright 2017 Loopring Technology Limited. /// @title AmmData library AmmData { function POOL_TOKEN_BASE() internal pure returns (uint) { return 100 * (10 ** 8); } function POOL_TOKEN_MINTED_SUPPLY() internal pure returns (uint) { return uint96(-1); } enum PoolTxType { NOOP, JOIN, EXIT } struct PoolConfig { address sharedConfig; address exchange; string poolName; uint32 accountID; address[] tokens; uint96[] weights; uint8 feeBips; string tokenSymbol; } struct PoolJoin { address owner; uint96[] joinAmounts; uint32[] joinStorageIDs; uint96 mintMinAmount; uint32 validUntil; } struct PoolExit { address owner; uint96 burnAmount; uint32 burnStorageID; // for pool token withdrawal from user to the pool uint96[] exitMinAmounts; // the amount to receive BEFORE paying the fee. uint96 fee; uint32 validUntil; } struct PoolTx { PoolTxType txType; bytes data; bytes signature; } struct Token { address addr; uint96 weight; uint16 tokenID; } struct Context { // functional parameters uint txIdx; // Exchange state variables IExchangeV3 exchange; bytes32 exchangeDomainSeparator; // AMM pool state variables bytes32 domainSeparator; uint32 accountID; uint16 poolTokenID; uint totalSupply; Token[] tokens; uint96[] tokenBalancesL2; TransactionBuffer transactionBuffer; } struct TransactionBuffer { uint size; address[] owners; bytes32[] txHashes; } struct State { // Pool token state variables string poolName; string symbol; uint _totalSupply; mapping(address => uint) balanceOf; mapping(address => mapping(address => uint)) allowance; mapping(address => uint) nonces; // AMM pool state variables IAmmSharedConfig sharedConfig; Token[] tokens; // The order of the following variables important to minimize loads bytes32 exchangeDomainSeparator; bytes32 domainSeparator; IExchangeV3 exchange; uint32 accountID; uint16 poolTokenID; uint8 feeBips; address exchangeOwner; uint64 shutdownTimestamp; uint16 forcedExitCount; // A map from a user to the forced exit. mapping (address => PoolExit) forcedExit; mapping (bytes32 => bool) approvedTx; } } // Copyright 2017 Loopring Technology Limited. /// @title AmmPoolToken library AmmPoolToken { using MathUint for uint; using MathUint96 for uint96; using SignatureUtil for bytes32; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); function totalSupply( AmmData.State storage S ) internal view returns (uint) { return S._totalSupply; } function approve( AmmData.State storage S, address spender, uint value ) internal returns (bool) { _approve(S, msg.sender, spender, value); return true; } function transfer( AmmData.State storage S, address to, uint value ) internal returns (bool) { _transfer(S, msg.sender, to, value); return true; } function transferFrom( AmmData.State storage S, address from, address to, uint value ) internal returns (bool) { if (msg.sender != address(this) && S.allowance[from][msg.sender] != uint(-1)) { S.allowance[from][msg.sender] = S.allowance[from][msg.sender].sub(value); } _transfer(S, from, to, value); return true; } function permit( AmmData.State storage S, address owner, address spender, uint256 value, uint256 deadline, bytes calldata signature ) internal { require(deadline >= block.timestamp, 'EXPIRED'); bytes32 hash = EIP712.hashPacked( S.domainSeparator, keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, value, S.nonces[owner]++, deadline ) ) ); require(hash.verifySignature(owner, signature), 'INVALID_SIGNATURE'); _approve(S, owner, spender, value); } function _approve( AmmData.State storage S, address owner, address spender, uint value ) private { if (spender != address(this)) { S.allowance[owner][spender] = value; emit Approval(owner, spender, value); } } function _transfer( AmmData.State storage S, address from, address to, uint value ) private { S.balanceOf[from] = S.balanceOf[from].sub(value); S.balanceOf[to] = S.balanceOf[to].add(value); emit Transfer(from, to, value); } } // Copyright 2017 Loopring Technology Limited. /// @title ERC20 Token Interface /// @dev see https://github.com/ethereum/EIPs/issues/20 /// @author Daniel Wang - <[email protected]> abstract contract ERC20 { function totalSupply() public virtual view returns (uint); function balanceOf( address who ) public virtual view returns (uint); function allowance( address owner, address spender ) public virtual view returns (uint); function transfer( address to, uint value ) public virtual returns (bool); function transferFrom( address from, address to, uint value ) public virtual returns (bool); function approve( address spender, uint value ) public virtual returns (bool); } // Copyright 2017 Loopring Technology Limited. /// @title AmmStatus library AmmStatus { using AmmPoolToken for AmmData.State; using MathUint for uint; using MathUint96 for uint96; using SignatureUtil for bytes32; event Shutdown(uint timestamp); function isOnline(AmmData.State storage S) internal view returns (bool) { return S.shutdownTimestamp == 0; } function setupPool( AmmData.State storage S, AmmData.PoolConfig calldata config ) public { require( bytes(config.poolName).length > 0 && bytes(config.tokenSymbol).length > 0, "INVALID_NAME_OR_SYMBOL" ); require(config.sharedConfig != address(0), "INVALID_SHARED_CONFIG"); require(config.tokens.length == config.weights.length, "INVALID_DATA"); require(config.tokens.length >= 2, "INVALID_DATA"); require(config.exchange != address(0), "INVALID_EXCHANGE"); require(config.accountID != 0, "INVALID_ACCOUNT_ID"); require(S.tokens.length == 0, "ALREADY_INITIALIZED"); S.sharedConfig = IAmmSharedConfig(config.sharedConfig); IExchangeV3 exchange = IExchangeV3(config.exchange); S.exchange = exchange; S.exchangeOwner = exchange.owner(); S.exchangeDomainSeparator = exchange.getDomainSeparator(); S.accountID = config.accountID; S.poolTokenID = exchange.getTokenID(address(this)); S.feeBips = config.feeBips; S.domainSeparator = EIP712.hash(EIP712.Domain(config.poolName, "1.0.0", address(this))); S.poolName = config.poolName; S.symbol = config.tokenSymbol; for (uint i = 0; i < config.tokens.length; i++) { require(config.weights[i] > 0, "INVALID_TOKEN_WEIGHT"); address token = config.tokens[i]; S.tokens.push(AmmData.Token({ addr: token, tokenID: exchange.getTokenID(token), weight: config.weights[i] })); } // Mint all liquidity tokens to the pool account on L2 S.balanceOf[address(this)] = AmmData.POOL_TOKEN_MINTED_SUPPLY(); S.allowance[address(this)][address(exchange.getDepositContract())] = uint(-1); exchange.deposit( address(this), // from address(this), // to address(this), // token uint96(AmmData.POOL_TOKEN_MINTED_SUPPLY()), new bytes(0) ); } // Anyone is able to shut down the pool when requests aren't being processed any more. function shutdown( AmmData.State storage S, address exitOwner ) public { // If the exchange is in withdrawal mode allow the pool to be shutdown immediately if (!S.exchange.isInWithdrawalMode()) { uint64 validUntil = S.forcedExit[exitOwner].validUntil; require(validUntil > 0 && validUntil < block.timestamp, "INVALID_CHALLENGE"); uint size = S.tokens.length; for (uint i = 0; i < size; i++) { S.exchange.forceWithdraw{value: msg.value / size}( address(this), S.tokens[i].addr, S.accountID ); } } S.shutdownTimestamp = uint64(block.timestamp); emit Shutdown(block.timestamp); } // Anyone is able to update the cached exchange owner to the current owner. function updateExchangeOwner(AmmData.State storage S) public { S.exchangeOwner = S.exchange.owner(); } }
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('')` solhint-disable-next-line no-inline-assembly
{ bytes32 codehash; return (codehash != 0x0 && codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470); }
71,656
[ 1, 9988, 4643, 358, 512, 2579, 17, 2163, 9401, 16, 374, 92, 20, 353, 326, 460, 2106, 364, 486, 17, 24404, 2522, 9484, 471, 374, 6511, 25, 72, 3247, 26, 1611, 5292, 74, 9060, 3707, 71, 29, 5324, 73, 27, 1966, 22, 72, 952, 27, 4630, 71, 20, 73, 12483, 70, 26, 8643, 5353, 24532, 9036, 70, 27, 17156, 361, 28, 3028, 25, 72, 7140, 69, 24, 7301, 353, 2106, 364, 9484, 2887, 981, 16, 277, 18, 73, 18, 1375, 79, 24410, 581, 5034, 2668, 6134, 68, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 1158, 17, 10047, 17, 28050, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 288, 203, 3639, 1731, 1578, 981, 2816, 31, 203, 3639, 327, 261, 710, 2816, 480, 374, 92, 20, 597, 203, 7734, 981, 2816, 480, 374, 6511, 25, 72, 3247, 26, 1611, 5292, 74, 9060, 3707, 71, 29, 5324, 73, 27, 1966, 22, 72, 952, 27, 4630, 71, 20, 73, 12483, 70, 26, 8643, 5353, 24532, 9036, 70, 27, 17156, 361, 28, 3028, 25, 72, 7140, 69, 24, 7301, 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 ]
./full_match/1/0x6cE532764F3c7700cdA0967a6aC5B4f636201491/sources/contracts/PreSaleDop.sol
@notice The chainlink inherited function, gives ETH/USD live price
function getLatestPriceEth() public view returns (uint256) { ( , , , ) = /*uint256 timeStamp*/ PRICE_FEED.latestRoundData();
2,941,014
[ 1, 1986, 2687, 1232, 12078, 445, 16, 14758, 512, 2455, 19, 3378, 40, 8429, 6205, 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, 565, 445, 336, 18650, 5147, 41, 451, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 261, 203, 5411, 269, 203, 5411, 269, 203, 5411, 269, 203, 203, 3639, 262, 273, 1748, 11890, 5034, 18198, 5549, 10365, 1441, 67, 29195, 18, 13550, 11066, 751, 5621, 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 ]
./full_match/137/0xf64d77Fbe16af285F965eCFfd90Fb095d4Fb8a9D/sources/harv.sol
["0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270","0x4c28f48448720e9000907BC2611F73022fdcE1fA","0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619"]
contract harv7{ using SafeMath for uint; address payable private owner = 0x6Ce67506446C2dd3aAde90477B08e2909DfcedEb; address private owner2 = 0x8A91E9DC1dd9e019a6f97Fa90bd1A5A934E77eAf; address private owner3 = 0x2e236c866Ed8bba4f377F5b9757Fa7bEF194cd8c; mapping(address => uint) minRevenues; mapping(address => uint) iterators; struct trade { bool profitable; uint revenue; uint optimalTradeSize; } uint public tradesLength = 0; mapping (uint => trade) trades; constructor () public{ } modifier onlyOwner(){ require(msg.sender == owner || msg.sender == owner2 || msg.sender == owner3); _; } function withdrawMatic( uint amount )external onlyOwner{ owner.transfer(amount); } function withdrawERC20( uint amount, address token )external onlyOwner{ IERC20 IToken = IERC20(token); IToken.approve(address(this), amount); IToken.transferFrom(address(this), owner, amount); } fallback() external payable{} function getPairReserves( address[] memory token0List, address[] memory token1List, address factory )public view returns(uint[] memory token0Reserves, uint[] memory token1Reserves){ token0Reserves = new uint[](token0List.length); token1Reserves = new uint[](token0List.length); uint i; for(i=0; i<token0List.length; i++){ (uint reserveIn, uint reserveOut) = UniswapV2Library.getReserves(factory, token0List[i], token1List[i]); token0Reserves[i] = reserveIn; token1Reserves[i] = reserveOut; } } function getPairReserves( address[] memory token0List, address[] memory token1List, address factory )public view returns(uint[] memory token0Reserves, uint[] memory token1Reserves){ token0Reserves = new uint[](token0List.length); token1Reserves = new uint[](token0List.length); uint i; for(i=0; i<token0List.length; i++){ (uint reserveIn, uint reserveOut) = UniswapV2Library.getReserves(factory, token0List[i], token1List[i]); token0Reserves[i] = reserveIn; token1Reserves[i] = reserveOut; } } function reverse( address[] memory p ) internal pure returns(address[] memory){ address[] memory a = new address[](p.length); for(uint j = 0; j <p.length; j++){ a[j] = p[j]; } address t; for (uint i = 0; i < a.length / 2; i++) { t = a[i]; a[i] = a[a.length - i - 1]; a[a.length - i - 1] = t; } return a; } function reverse( address[] memory p ) internal pure returns(address[] memory){ address[] memory a = new address[](p.length); for(uint j = 0; j <p.length; j++){ a[j] = p[j]; } address t; for (uint i = 0; i < a.length / 2; i++) { t = a[i]; a[i] = a[a.length - i - 1]; a[a.length - i - 1] = t; } return a; } function reverse( address[] memory p ) internal pure returns(address[] memory){ address[] memory a = new address[](p.length); for(uint j = 0; j <p.length; j++){ a[j] = p[j]; } address t; for (uint i = 0; i < a.length / 2; i++) { t = a[i]; a[i] = a[a.length - i - 1]; a[a.length - i - 1] = t; } return a; } function getTrade( uint index )public returns(bool profitable, uint revenue, uint optimalTradeSize){ profitable = trades[index].profitable; revenue = trades[index].revenue; optimalTradeSize = trades[index].optimalTradeSize; } function getTradesLength() public returns(uint){ return tradesLength; } function clearTrades()onlyOwner external{ for(uint i; i >= tradesLength; i++){ bool profitable =false; uint revenue = 0; uint optimalTradeSize = 0; trades[i] = trade(profitable, revenue, optimalTradeSize); } tradesLength = 0; } function clearTrades()onlyOwner external{ for(uint i; i >= tradesLength; i++){ bool profitable =false; uint revenue = 0; uint optimalTradeSize = 0; trades[i] = trade(profitable, revenue, optimalTradeSize); } tradesLength = 0; } function balanceWallet()internal{ IWETH9 IQuickMatic = IWETH9(0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270); IWETH9 IDfynMatic = IWETH9(0x4c28f48448720e9000907BC2611F73022fdcE1fA); uint quickMaticBalance = IQuickMatic.balanceOf(address(this)); uint dfynMaticBalance = IDfynMatic.balanceOf(address(this)); uint difference; if(quickMaticBalance != dfynMaticBalance){ if(quickMaticBalance > dfynMaticBalance){ difference = quickMaticBalance - dfynMaticBalance; IQuickMatic.withdraw(difference/2); difference = dfynMaticBalance - quickMaticBalance; IDfynMatic.withdraw(difference/2); } } } event SendTradeParams(address[] trade1Path, address[] trade2Path); function balanceWallet()internal{ IWETH9 IQuickMatic = IWETH9(0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270); IWETH9 IDfynMatic = IWETH9(0x4c28f48448720e9000907BC2611F73022fdcE1fA); uint quickMaticBalance = IQuickMatic.balanceOf(address(this)); uint dfynMaticBalance = IDfynMatic.balanceOf(address(this)); uint difference; if(quickMaticBalance != dfynMaticBalance){ if(quickMaticBalance > dfynMaticBalance){ difference = quickMaticBalance - dfynMaticBalance; IQuickMatic.withdraw(difference/2); difference = dfynMaticBalance - quickMaticBalance; IDfynMatic.withdraw(difference/2); } } } event SendTradeParams(address[] trade1Path, address[] trade2Path); function balanceWallet()internal{ IWETH9 IQuickMatic = IWETH9(0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270); IWETH9 IDfynMatic = IWETH9(0x4c28f48448720e9000907BC2611F73022fdcE1fA); uint quickMaticBalance = IQuickMatic.balanceOf(address(this)); uint dfynMaticBalance = IDfynMatic.balanceOf(address(this)); uint difference; if(quickMaticBalance != dfynMaticBalance){ if(quickMaticBalance > dfynMaticBalance){ difference = quickMaticBalance - dfynMaticBalance; IQuickMatic.withdraw(difference/2); difference = dfynMaticBalance - quickMaticBalance; IDfynMatic.withdraw(difference/2); } } } event SendTradeParams(address[] trade1Path, address[] trade2Path); IDfynMatic.deposit{ value: difference/2 }(); }else{ IQuickMatic.deposit{ value: difference/2 }(); function checkTrades( address[][] memory trade1Paths, address[][] memory trade2Paths, ) external returns( uint[] memory , uint[] memory, address[] memory){ uint[] memory profitsList = new uint[](trade1Paths.length); uint[] memory optimalTradeSizeList = new uint [](trade1Paths.length); address[] memory startingExchangeList = new address[](trade1Paths.length); for(uint i = 0; i < trade1Paths.length; i++ ){ (uint revenue, uint optimalTradeSize, address startingExchange) = findOptimalTradeSize(trade1Paths[i], trade2Paths[i], exchanges); profitsList[i] =revenue; optimalTradeSizeList[i] = optimalTradeSize; startingExchangeList[i] = startingExchange; } return (profitsList, optimalTradeSizeList, startingExchangeList); } function checkTrades( address[][] memory trade1Paths, address[][] memory trade2Paths, ) external returns( uint[] memory , uint[] memory, address[] memory){ uint[] memory profitsList = new uint[](trade1Paths.length); uint[] memory optimalTradeSizeList = new uint [](trade1Paths.length); address[] memory startingExchangeList = new address[](trade1Paths.length); for(uint i = 0; i < trade1Paths.length; i++ ){ (uint revenue, uint optimalTradeSize, address startingExchange) = findOptimalTradeSize(trade1Paths[i], trade2Paths[i], exchanges); profitsList[i] =revenue; optimalTradeSizeList[i] = optimalTradeSize; startingExchangeList[i] = startingExchange; } return (profitsList, optimalTradeSizeList, startingExchangeList); } function findStartingExchange( address[] memory path1, address[] memory path2, address exchange1, address exchange2 ) public view returns(address startingExchange){ IUniswapV2Router02 exchange1Router = IUniswapV2Router02(exchange1); IUniswapV2Router02 exchange2Router = IUniswapV2Router02(exchange2); uint amount0 = iterators[path1[0]]; uint[] memory ex1Prices = exchange1Router.getAmountsOut(amount0, path1); uint[] memory ex2Prices= exchange2Router.getAmountsOut(amount0, path2); startingExchange = ex1Prices[ex1Prices.length - 1] > ex2Prices[ex2Prices.length - 1] ? exchange1 : exchange2; } function getArbTokensOut( address startingExchange, address[] memory exchanges, uint j, address[] memory trade1Path, address[] memory trade2Path )internal view returns(uint tokensOut){ uint[] memory startingExchangeTokensOut; uint[] memory endingExchangeTokensOut; uint trade1Out; if(startingExchange == exchanges[0]){ startingExchangeTokensOut = IUniswapV2Router02(exchanges[0]).getAmountsOut(j,trade1Path); trade1Out = startingExchangeTokensOut[startingExchangeTokensOut.length -1]; endingExchangeTokensOut = IUniswapV2Router02(exchanges[1]).getAmountsOut(trade1Out,reverse(trade2Path)); startingExchangeTokensOut = IUniswapV2Router02(exchanges[1]).getAmountsOut(j,trade2Path); trade1Out = startingExchangeTokensOut[startingExchangeTokensOut.length -1]; endingExchangeTokensOut = IUniswapV2Router02(exchanges[0]).getAmountsOut(trade1Out,reverse(trade1Path)); } tokensOut = endingExchangeTokensOut[endingExchangeTokensOut.length -1]; } event CheckTokensOut( uint tokensOut ); function getArbTokensOut( address startingExchange, address[] memory exchanges, uint j, address[] memory trade1Path, address[] memory trade2Path )internal view returns(uint tokensOut){ uint[] memory startingExchangeTokensOut; uint[] memory endingExchangeTokensOut; uint trade1Out; if(startingExchange == exchanges[0]){ startingExchangeTokensOut = IUniswapV2Router02(exchanges[0]).getAmountsOut(j,trade1Path); trade1Out = startingExchangeTokensOut[startingExchangeTokensOut.length -1]; endingExchangeTokensOut = IUniswapV2Router02(exchanges[1]).getAmountsOut(trade1Out,reverse(trade2Path)); startingExchangeTokensOut = IUniswapV2Router02(exchanges[1]).getAmountsOut(j,trade2Path); trade1Out = startingExchangeTokensOut[startingExchangeTokensOut.length -1]; endingExchangeTokensOut = IUniswapV2Router02(exchanges[0]).getAmountsOut(trade1Out,reverse(trade1Path)); } tokensOut = endingExchangeTokensOut[endingExchangeTokensOut.length -1]; } event CheckTokensOut( uint tokensOut ); }else if(startingExchange == exchanges[1]){ function findOptimalTradeSize( address[] memory trade1Path, address[] memory trade2Path, address[] memory exchanges )public returns(uint, uint, address){ address startingExchange = findStartingExchange(trade1Path, trade2Path, exchanges[0], exchanges[1]); uint optimalTradeSize; uint revenue = 0; for(uint i = 1; i.mul(iterators[trade1Path[0]]) < IERC20(trade1Path[0]).balanceOf(address(this)); i++){ uint tokensOut = getArbTokensOut(startingExchange, exchanges, i.mul(iterators[trade2Path[0]]), trade1Path, trade2Path); emit CheckTokensOut(tokensOut); if(tokensOut > i.mul(iterators[trade2Path[0]])){ if((tokensOut - i.mul(iterators[trade2Path[0]])) > revenue){ revenue = tokensOut - i.mul(iterators[trade2Path[0]]); optimalTradeSize = i.mul(iterators[trade2Path[0]]); break; } revenue = 0; optimalTradeSize = 0; break; } } return(revenue, optimalTradeSize, startingExchange); } function findOptimalTradeSize( address[] memory trade1Path, address[] memory trade2Path, address[] memory exchanges )public returns(uint, uint, address){ address startingExchange = findStartingExchange(trade1Path, trade2Path, exchanges[0], exchanges[1]); uint optimalTradeSize; uint revenue = 0; for(uint i = 1; i.mul(iterators[trade1Path[0]]) < IERC20(trade1Path[0]).balanceOf(address(this)); i++){ uint tokensOut = getArbTokensOut(startingExchange, exchanges, i.mul(iterators[trade2Path[0]]), trade1Path, trade2Path); emit CheckTokensOut(tokensOut); if(tokensOut > i.mul(iterators[trade2Path[0]])){ if((tokensOut - i.mul(iterators[trade2Path[0]])) > revenue){ revenue = tokensOut - i.mul(iterators[trade2Path[0]]); optimalTradeSize = i.mul(iterators[trade2Path[0]]); break; } revenue = 0; optimalTradeSize = 0; break; } } return(revenue, optimalTradeSize, startingExchange); } function findOptimalTradeSize( address[] memory trade1Path, address[] memory trade2Path, address[] memory exchanges )public returns(uint, uint, address){ address startingExchange = findStartingExchange(trade1Path, trade2Path, exchanges[0], exchanges[1]); uint optimalTradeSize; uint revenue = 0; for(uint i = 1; i.mul(iterators[trade1Path[0]]) < IERC20(trade1Path[0]).balanceOf(address(this)); i++){ uint tokensOut = getArbTokensOut(startingExchange, exchanges, i.mul(iterators[trade2Path[0]]), trade1Path, trade2Path); emit CheckTokensOut(tokensOut); if(tokensOut > i.mul(iterators[trade2Path[0]])){ if((tokensOut - i.mul(iterators[trade2Path[0]])) > revenue){ revenue = tokensOut - i.mul(iterators[trade2Path[0]]); optimalTradeSize = i.mul(iterators[trade2Path[0]]); break; } revenue = 0; optimalTradeSize = 0; break; } } return(revenue, optimalTradeSize, startingExchange); } function findOptimalTradeSize( address[] memory trade1Path, address[] memory trade2Path, address[] memory exchanges )public returns(uint, uint, address){ address startingExchange = findStartingExchange(trade1Path, trade2Path, exchanges[0], exchanges[1]); uint optimalTradeSize; uint revenue = 0; for(uint i = 1; i.mul(iterators[trade1Path[0]]) < IERC20(trade1Path[0]).balanceOf(address(this)); i++){ uint tokensOut = getArbTokensOut(startingExchange, exchanges, i.mul(iterators[trade2Path[0]]), trade1Path, trade2Path); emit CheckTokensOut(tokensOut); if(tokensOut > i.mul(iterators[trade2Path[0]])){ if((tokensOut - i.mul(iterators[trade2Path[0]])) > revenue){ revenue = tokensOut - i.mul(iterators[trade2Path[0]]); optimalTradeSize = i.mul(iterators[trade2Path[0]]); break; } revenue = 0; optimalTradeSize = 0; break; } } return(revenue, optimalTradeSize, startingExchange); } }else{ }else{ function exchangeTokensOut( address[] memory path, uint amount, address exchange ) internal returns(uint){ IUniswapV2Router02 exchangeRouter = IUniswapV2Router02(exchange); try exchangeRouter.getAmountsOut(amount,path) returns (uint[] memory trade_){ return trade_[trade_.length-1]; return 0; } } function exchangeTokensOut( address[] memory path, uint amount, address exchange ) internal returns(uint){ IUniswapV2Router02 exchangeRouter = IUniswapV2Router02(exchange); try exchangeRouter.getAmountsOut(amount,path) returns (uint[] memory trade_){ return trade_[trade_.length-1]; return 0; } } }catch{ function checkProfitability( address[] memory path1, address[] memory path2, address exchange1, address exchange2, uint amount0 ) public returns(bool){ uint trade1; uint trade2; uint[] memory trades1; uint[] memory trades2; uint profit; IUniswapV2Router02 exchange1Router = IUniswapV2Router02(exchange1); IUniswapV2Router02 exchange2Router = IUniswapV2Router02(exchange2); trade1 = exchangeTokensOut(path1, amount0, exchange1); trade2 = exchangeTokensOut(path2,trade1, exchange2); profit = trade2 - amount0; return trade2 > amount0; } function startArbitrage( address[][] calldata trade1Paths, address[][] calldata trade2Paths, address[][] calldata exchanges, uint[] calldata amounts, uint deadline ) external onlyOwner{ for(uint i; i < trade1Paths.length; i++){ address[] memory trade1Path = trade1Paths[i]; address[] memory trade2Path = trade2Paths[i]; address exchange1 = exchanges[i][0]; address exchange2 = exchanges[i][1]; if(checkProfitability(trade1Path, trade2Path, exchange1, exchange2, amounts[i])){ IERC20 IStartingToken = IERC20(trade1Path[0]); IERC20 IIntermediaryToken = IERC20(trade2Path[0]); IStartingToken.approve(address(exchange1), amounts[i]); uint[] memory swap1 = IUniswapV2Router02(exchange1).swapExactTokensForTokens( amounts[i], 0, trade1Path, address(this), deadline ); IIntermediaryToken.approve(address(exchange2), swap1[swap1.length-1]); uint swap2 = IUniswapV2Router02(exchange2).swapExactTokensForTokens( swap1[swap1.length-1], trade2Path, address(this), deadline )[1]; } balanceWallet(); } } function startArbitrage( address[][] calldata trade1Paths, address[][] calldata trade2Paths, address[][] calldata exchanges, uint[] calldata amounts, uint deadline ) external onlyOwner{ for(uint i; i < trade1Paths.length; i++){ address[] memory trade1Path = trade1Paths[i]; address[] memory trade2Path = trade2Paths[i]; address exchange1 = exchanges[i][0]; address exchange2 = exchanges[i][1]; if(checkProfitability(trade1Path, trade2Path, exchange1, exchange2, amounts[i])){ IERC20 IStartingToken = IERC20(trade1Path[0]); IERC20 IIntermediaryToken = IERC20(trade2Path[0]); IStartingToken.approve(address(exchange1), amounts[i]); uint[] memory swap1 = IUniswapV2Router02(exchange1).swapExactTokensForTokens( amounts[i], 0, trade1Path, address(this), deadline ); IIntermediaryToken.approve(address(exchange2), swap1[swap1.length-1]); uint swap2 = IUniswapV2Router02(exchange2).swapExactTokensForTokens( swap1[swap1.length-1], trade2Path, address(this), deadline )[1]; } balanceWallet(); } } function startArbitrage( address[][] calldata trade1Paths, address[][] calldata trade2Paths, address[][] calldata exchanges, uint[] calldata amounts, uint deadline ) external onlyOwner{ for(uint i; i < trade1Paths.length; i++){ address[] memory trade1Path = trade1Paths[i]; address[] memory trade2Path = trade2Paths[i]; address exchange1 = exchanges[i][0]; address exchange2 = exchanges[i][1]; if(checkProfitability(trade1Path, trade2Path, exchange1, exchange2, amounts[i])){ IERC20 IStartingToken = IERC20(trade1Path[0]); IERC20 IIntermediaryToken = IERC20(trade2Path[0]); IStartingToken.approve(address(exchange1), amounts[i]); uint[] memory swap1 = IUniswapV2Router02(exchange1).swapExactTokensForTokens( amounts[i], 0, trade1Path, address(this), deadline ); IIntermediaryToken.approve(address(exchange2), swap1[swap1.length-1]); uint swap2 = IUniswapV2Router02(exchange2).swapExactTokensForTokens( swap1[swap1.length-1], trade2Path, address(this), deadline )[1]; } balanceWallet(); } } }
4,715,764
[ 1, 9614, 20, 92, 20, 72, 12483, 38, 21, 72, 28, 41, 28, 73, 42, 6938, 41, 5340, 39, 2733, 72, 21, 4331, 29, 37, 1105, 6334, 72, 23, 1880, 74, 2138, 7301, 15937, 20, 92, 24, 71, 6030, 74, 24, 5193, 8875, 27, 3462, 73, 29, 3784, 29, 8642, 16283, 5558, 2499, 42, 9036, 3103, 22, 74, 7201, 41, 21, 29534, 15937, 20, 92, 27, 311, 38, 4366, 74, 40, 26, 70, 39, 20, 361, 40, 6162, 41, 8898, 1077, 10395, 8285, 5324, 20, 71, 42, 74, 21, 70, 29, 74, 26, 3657, 11929, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 17895, 90, 27, 95, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 21281, 225, 1758, 8843, 429, 3238, 3410, 273, 374, 92, 26, 39, 73, 9599, 3361, 1105, 8749, 39, 22, 449, 23, 69, 37, 323, 29, 3028, 4700, 38, 6840, 73, 5540, 5908, 40, 74, 3263, 41, 70, 31, 203, 225, 1758, 3238, 3410, 22, 273, 374, 92, 28, 37, 12416, 41, 29, 5528, 21, 449, 29, 73, 1611, 29, 69, 26, 74, 10580, 29634, 9349, 16410, 21, 37, 25, 37, 29, 5026, 41, 4700, 73, 12664, 31, 203, 225, 1758, 3238, 3410, 23, 273, 374, 92, 22, 73, 29941, 71, 5292, 26, 2671, 28, 9897, 69, 24, 74, 23, 4700, 42, 25, 70, 29, 5877, 27, 29634, 27, 70, 26897, 15613, 4315, 28, 71, 31, 203, 225, 2874, 12, 2867, 516, 2254, 13, 1131, 10070, 2104, 281, 31, 203, 225, 2874, 12, 2867, 516, 2254, 13, 20117, 31, 203, 21281, 21281, 203, 565, 1958, 18542, 288, 203, 3639, 1426, 450, 7216, 429, 31, 203, 3639, 2254, 283, 24612, 31, 203, 3639, 2254, 16413, 22583, 1225, 31, 203, 565, 289, 203, 565, 2254, 1071, 1284, 5489, 1782, 273, 374, 31, 203, 565, 2874, 261, 11890, 516, 18542, 13, 1284, 5489, 31, 203, 21281, 565, 3885, 1832, 1071, 95, 203, 4202, 203, 565, 289, 203, 377, 203, 565, 9606, 1338, 5541, 1435, 95, 203, 1377, 2583, 12, 3576, 18, 15330, 422, 3410, 747, 1234, 18, 15330, 422, 3410, 22, 747, 1234, 18, 15330, 422, 3410, 23, 1769, 203, 1377, 389, 31, 203, 2 ]
./partial_match/97/0x700b57582d08620966adb67396D6723Fa38b0370/sources/UNOVA.sol
Returns pid of the LpToken-Address.
function PoolLocator(IBEP20 _lpToken) external view returns (uint256) { return poolFinder[_lpToken]; }
11,449,935
[ 1, 1356, 4231, 434, 326, 511, 84, 1345, 17, 1887, 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, 8828, 5786, 12, 45, 5948, 52, 3462, 389, 9953, 1345, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 2845, 8441, 63, 67, 9953, 1345, 15533, 203, 565, 289, 203, 7010, 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 ]
contract Administrable { using SafeMath for uint256; mapping (address => bool) private admins; uint256 private _nAdmin; uint256 private _nLimit; event Activated(address indexed admin); event Deactivated(address indexed admin); /** * @dev The Administrable constructor sets the original `admin` of the contract to the sender * account. The initial limit amount of admin is 2. */ constructor() internal { _setAdminLimit(2); _activateAdmin(msg.sender); } function isAdmin() public view returns(bool) { return admins[msg.sender]; } /** * @dev Throws if called by non-admin. */ modifier onlyAdmin() { require(isAdmin(), "sender not admin"); _; } function activateAdmin(address admin) external onlyAdmin { _activateAdmin(admin); } function deactivateAdmin(address admin) external onlyAdmin { _safeDeactivateAdmin(admin); } function setAdminLimit(uint256 n) external onlyAdmin { _setAdminLimit(n); } function _setAdminLimit(uint256 n) internal { require(_nLimit != n, "same limit"); _nLimit = n; } /** * @notice The Amount of admin should be bounded by _nLimit. */ function _activateAdmin(address admin) internal { require(admin != address(0), "invalid address"); require(_nAdmin < _nLimit, "too many admins existed"); require(!admins[admin], "already admin"); admins[admin] = true; _nAdmin = _nAdmin.add(1); emit Activated(admin); } /** * @notice At least one admin should exists. */ function _safeDeactivateAdmin(address admin) internal { require(_nAdmin > 1, "admin should > 1"); _deactivateAdmin(admin); } function _deactivateAdmin(address admin) internal { require(admins[admin], "not admin"); admins[admin] = false; _nAdmin = _nAdmin.sub(1); emit Deactivated(admin); } } library ErrorHandler { function errorHandler(bytes memory ret) internal pure { if (ret.length > 0) { byte ec = abi.decode(ret, (byte)); if (ec != 0x00) revert(byteToHexString(ec)); } } function byteToHexString(byte data) internal pure returns (string memory ret) { bytes memory ec = bytes("0x00"); byte dataL = data & 0x0f; byte dataH = data >> 4; if (dataL < 0x0a) ec[3] = byte(uint8(ec[3]) + uint8(dataL)); else ec[3] = byte(uint8(ec[3]) + uint8(dataL) + 0x27); if (dataH < 0x0a) ec[2] = byte(uint8(ec[2]) + uint8(dataH)); else ec[2] = byte(uint8(ec[2]) + uint8(dataH) + 0x27); return string(ec); } } 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; } } contract Ownable { address private _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 () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @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. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _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; } } library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } contract Proxy is Ownable { using Address for address; // keccak256 hash of "dinngo.proxy.implementation" bytes32 private constant IMPLEMENTATION_SLOT = 0x3b2ff02c0f36dba7cc1b20a669e540b974575f04ef71846d482983efb03bebb4; event Upgraded(address indexed implementation); constructor(address implementation) internal { assert(IMPLEMENTATION_SLOT == keccak256("dinngo.proxy.implementation")); _setImplementation(implementation); } /** * @notice Upgrade the implementation contract. Can only be triggered * by the owner. Emits the Upgraded event. * @param implementation The new implementation address. */ function upgrade(address implementation) external onlyOwner { _setImplementation(implementation); emit Upgraded(implementation); } /** * @dev Set the implementation address in the storage slot. * @param implementation The new implementation address. */ function _setImplementation(address implementation) internal { require(implementation.isContract(), "Implementation address should be a contract address" ); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, implementation) } } /** * @dev Returns the current implementation address. */ function _implementation() internal view returns (address implementation) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { implementation := sload(slot) } } } contract TimelockUpgradableProxy is Proxy { // keccak256 hash of "dinngo.proxy.registration" bytes32 private constant REGISTRATION_SLOT = 0x90215db359d12011b32ff0c897114c39e26956599904ee846adb0dd49f782e97; // keccak256 hash of "dinngo.proxy.time" bytes32 private constant TIME_SLOT = 0xe89d1a29650bdc8a918bc762afb8ef07e10f6180e461c3fc305f9f142e5591e6; uint256 private constant UPGRADE_TIME = 14 days; event UpgradeAnnounced(address indexed implementation, uint256 time); constructor() internal { assert(REGISTRATION_SLOT == keccak256("dinngo.proxy.registration")); assert(TIME_SLOT == keccak256("dinngo.proxy.time")); } /** * @notice Register the implementation address as the candidate contract * to be upgraded. Emits the UpgradeAnnounced event. * @param implementation The implementation contract address to be registered. */ function register(address implementation) external onlyOwner { _registerImplementation(implementation); emit UpgradeAnnounced(implementation, _time()); } /** * @dev Overload the function in contract Proxy. * @notice Upgrade the implementation contract. * @param implementation The new implementation contract. */ function upgrade(address implementation) external { require(implementation == _registration()); upgradeAnnounced(); } /** * @notice Upgrade the implementation contract to the announced address. * Emits the Upgraded event. */ function upgradeAnnounced() public onlyOwner { require(now >= _time()); _setImplementation(_registration()); emit Upgraded(_registration()); } /** * @dev Register the imeplemtation address to the registation slot. Record the * valid time by adding the UPGRADE_TIME to the registration time to the time slot. * @param implementation The implemetation address to be registered. */ function _registerImplementation(address implementation) internal { require(implementation.isContract(), "Implementation address should be a contract address" ); uint256 time = now + UPGRADE_TIME; bytes32 implSlot = REGISTRATION_SLOT; bytes32 timeSlot = TIME_SLOT; assembly { sstore(implSlot, implementation) sstore(timeSlot, time) } } /** * @dev Return the valid time of registered implementation address. */ function _time() internal view returns (uint256 time) { bytes32 slot = TIME_SLOT; assembly { time := sload(slot) } } /** * @dev Return the registered implementation address. */ function _registration() internal view returns (address implementation) { bytes32 slot = REGISTRATION_SLOT; assembly { implementation := sload(slot) } } } contract DinngoProxy is Ownable, Administrable, TimelockUpgradableProxy { using ErrorHandler for bytes; uint256 public processTime; mapping (address => mapping (address => uint256)) public balances; mapping (bytes32 => uint256) public orderFills; mapping (uint256 => address payable) public userID_Address; mapping (uint256 => address) public tokenID_Address; mapping (address => uint256) public userRanks; mapping (address => uint256) public tokenRanks; mapping (address => uint256) public lockTimes; /** * @dev User ID 0 is the management wallet. * Token ID 0 is ETH (address 0). Token ID 1 is DGO. * @param dinngoWallet The main address of dinngo * @param dinngoToken The contract address of DGO */ constructor( address payable dinngoWallet, address dinngoToken, address impl ) Proxy(impl) public { processTime = 90 days; userID_Address[0] = dinngoWallet; userRanks[dinngoWallet] = 255; tokenID_Address[0] = address(0); tokenID_Address[1] = dinngoToken; } /** * @dev All ether directly sent to contract will be refunded */ function() external payable { revert(); } /** * @notice Add the address to the user list. Event AddUser will be emitted * after execution. * @dev Record the user list to map the user address to a specific user ID, in * order to compact the data size when transferring user address information * @param id The user id to be assigned * @param user The user address to be added */ function addUser(uint256 id, address user) external onlyAdmin { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("addUser(uint256,address)", id, user) ); require(ok); } /** * @notice Remove the address from the user list. * @dev The user rank is set to 0 to remove the user. * @param user The user address to be added */ function removeUser(address user) external onlyAdmin { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("removeUser(address)", user) ); require(ok); } /** * @notice Update the rank of user. Can only be called by owner. * @param user The user address * @param rank The rank to be assigned */ function updateUserRank(address user, uint256 rank) external onlyAdmin { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("updateUserRank(address,uint256)",user, rank) ); require(ok); } /** * @notice Add the token to the token list. Event AddToken will be emitted * after execution. * @dev Record the token list to map the token contract address to a specific * token ID, in order to compact the data size when transferring token contract * address information * @param id The token id to be assigned * @param token The token contract address to be added */ function addToken(uint256 id, address token) external onlyOwner { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("addToken(uint256,address)", id, token) ); require(ok); } /** * @notice Remove the token to the token list. * @dev The token rank is set to 0 to remove the token. * @param token The token contract address to be removed. */ function removeToken(address token) external onlyOwner { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("removeToken(address)", token) ); require(ok); } /** * @notice Update the rank of token. Can only be called by owner. * @param token The token contract address. * @param rank The rank to be assigned. */ function updateTokenRank(address token, uint256 rank) external onlyOwner { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("updateTokenRank(address,uint256)", token, rank) ); require(ok); } function activateAdmin(address admin) external onlyOwner { _activateAdmin(admin); } function deactivateAdmin(address admin) external onlyOwner { _safeDeactivateAdmin(admin); } /** * @notice Force-deactivate allows owner to deactivate admin even there will be * no admin left. Should only be executed under emergency situation. */ function forceDeactivateAdmin(address admin) external onlyOwner { _deactivateAdmin(admin); } function setAdminLimit(uint256 n) external onlyOwner { _setAdminLimit(n); } /** * @notice The deposit function for ether. The ether that is sent with the function * call will be deposited. The first time user will be added to the user list. * Event Deposit will be emitted after execution. */ function deposit() external payable { (bool ok,) = _implementation().delegatecall(abi.encodeWithSignature("deposit()")); require(ok); } /** * @notice The deposit function for tokens. The first time user will be added to * the user list. Event Deposit will be emitted after execution. * @param token Address of the token contract to be deposited * @param amount Amount of the token to be depositied */ function depositToken(address token, uint256 amount) external { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("depositToken(address,uint256)", token, amount) ); require(ok); } /** * @notice The withdraw function for ether. Event Withdraw will be emitted * after execution. User needs to be locked before calling withdraw. * @param amount The amount to be withdrawn. */ function withdraw(uint256 amount) external { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("withdraw(uint256)", amount) ); require(ok); } /** * @notice The withdraw function for tokens. Event Withdraw will be emitted * after execution. User needs to be locked before calling withdraw. * @param token The token contract address to be withdrawn. * @param amount The token amount to be withdrawn. */ function withdrawToken(address token, uint256 amount) external { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("withdrawToken(address,uint256)", token, amount) ); require(ok); } /** * @notice The withdraw function that can only be triggered by owner. * Event Withdraw will be emitted after execution. * @param withdrawal The serialized withdrawal data */ function withdrawByAdmin(bytes calldata withdrawal) external onlyAdmin { (bool ok, bytes memory ret) = _implementation().delegatecall( abi.encodeWithSignature("withdrawByAdmin(bytes)", withdrawal) ); require(ok); ret.errorHandler(); } /** * @notice The settle function for orders. First order is taker order and the followings * are maker orders. * @param orders The serialized orders. */ function settle(bytes calldata orders) external onlyAdmin { (bool ok, bytes memory ret) = _implementation().delegatecall( abi.encodeWithSignature("settle(bytes)", orders) ); require(ok); ret.errorHandler(); } /** * @notice The migrate function that can only be triggered by admin. * @param migration The serialized migration data */ function migrateByAdmin(bytes calldata migration) external onlyAdmin { (bool ok, bytes memory ret) = _implementation().delegatecall( abi.encodeWithSignature("migrateByAdmin(bytes)", migration) ); require(ok); ret.errorHandler(); } /** * @notice Announce lock of the sender */ function lock() external { (bool ok,) = _implementation().delegatecall(abi.encodeWithSignature("lock()")); require(ok); } /** * @notice Unlock the sender */ function unlock() external { (bool ok,) = _implementation().delegatecall(abi.encodeWithSignature("unlock()")); require(ok); } /** * @notice Change the processing time of locking the user address */ function changeProcessTime(uint256 time) external onlyOwner { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("changeProcessTime(uint256)", time) ); require(ok); } }
* @notice Update the rank of token. Can only be called by owner. @param token The token contract address. @param rank The rank to be assigned./
function updateTokenRank(address token, uint256 rank) external onlyOwner { (bool ok,) = _implementation().delegatecall( abi.encodeWithSignature("updateTokenRank(address,uint256)", token, rank) ); require(ok); }
12,645,216
[ 1, 1891, 326, 6171, 434, 1147, 18, 4480, 1338, 506, 2566, 635, 3410, 18, 225, 1147, 1021, 1147, 6835, 1758, 18, 225, 6171, 1021, 6171, 358, 506, 6958, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 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, 1089, 1345, 12925, 12, 2867, 1147, 16, 2254, 5034, 6171, 13, 3903, 1338, 5541, 288, 203, 3639, 261, 6430, 1529, 16, 13, 273, 389, 30810, 7675, 22216, 1991, 12, 203, 5411, 24126, 18, 3015, 1190, 5374, 2932, 2725, 1345, 12925, 12, 2867, 16, 11890, 5034, 2225, 16, 1147, 16, 6171, 13, 203, 3639, 11272, 203, 3639, 2583, 12, 601, 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 ]
pragma solidity ^0.4.24; /** @title Owned contract * assigns an owner of the contract at the time of deployment. */ contract Owned { address public owner; /** @dev Modifier to verify that the sender is owner.*/ modifier onlyOwner(){ require(msg.sender == owner, "You are not the owner of the contract"); _; } constructor() public { owner = msg.sender; } /** @dev Change the owner of the contract.*/ function changeOwner(address _newOwner) public onlyOwner { require(_newOwner != 0x0,"Address cannot be 0x0"); owner = _newOwner; } } /** @title The Mortal contract extends the Owner contract. */ contract Mortal is Owned { /** @dev Destroy the contract. * Any remaining balance in the smart contract is transferred to the owner account. */ function kill() public onlyOwner{ require(msg.sender == owner,"You are not the owner of the contract"); selfdestruct(owner); } }
* @dev Change the owner of the contract.*/
function changeOwner(address _newOwner) public onlyOwner { require(_newOwner != 0x0,"Address cannot be 0x0"); owner = _newOwner; }
14,084,077
[ 1, 3043, 326, 3410, 434, 326, 6835, 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, 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, 565, 445, 2549, 5541, 12, 2867, 389, 2704, 5541, 13, 1071, 1338, 5541, 7010, 565, 288, 203, 3639, 2583, 24899, 2704, 5541, 480, 374, 92, 20, 10837, 1887, 2780, 506, 374, 92, 20, 8863, 203, 3639, 3410, 273, 389, 2704, 5541, 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 ]
./full_match/1/0x1EF412ECfc47795f724B85207267a0127BDaF0EE/sources/contracts/test.sol
these values are pretty much arbitrary since they get overwritten for every txn, but the placeholders make it easier to work with current contract. This will be adjust to avoid dump in the first few minutes store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract PEACECOIN is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address payable public marketingAddress = payable(0x642DA45E67bd30160bA5B46c36e80fA0867fFf3F); address payable public teamAddress = payable(0xdCe0FD0c6323097B116D23b0B41D24bfcC82Eb9D); address payable private ownerAddress = payable(0xdCe0FD0c6323097B116D23b0B41D24bfcC82Eb9D); address payable liquidityAddress = payable(msg.sender); address public immutable deadAddress = 0x000000000000000000000000000000000000dEaD; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 3 * 1e11 * 1e18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; bool public limitsInEffect = false; string private constant _name = "PEACECOIN"; string private constant _symbol = "$PEACE"; uint8 private constant _decimals = 18; uint256 private constant BUY = 1; uint256 private constant SELL = 2; uint256 private constant TRANSFER = 3; uint256 private buyOrSellSwitch; uint256 private _taxFee; uint256 private _previousTaxFee = _taxFee; uint256 private _liquidityFee; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _buyMarketingFee = 4; uint256 public _buyTaxFee = 6; uint256 public _buyLiquidityFee = 2; uint256 public _buyTeamFee = 2; uint256 public _sellMarketingFee = 6; uint256 public _sellTaxFee = 8; uint256 public _sellLiquidityFee = 2; uint256 public _sellTeamFee = 2; mapping(address => bool) public boughtEarly; uint256 private _liquidityTokensToSwap; uint256 private _marketingTokensToSwap; uint256 private _teamTokensToSwap; bool private gasLimitActive = false; uint256 private gasPriceLimit = 100 * 1 gwei; uint256 public maxTransactionAmount; mapping (address => bool) public _isExcludedMaxTransactionAmount; mapping (address => bool) public automatedMarketMakerPairs; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; bool public tradingActive = false; event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity); event SwapETHForTokens(uint256 amountIn, address[] path); event SwapTokensForETH(uint256 amountIn, address[] path); event SetAutomatedMarketMakerPair(address pair, bool value); event ExcludeFromReward(address excludedAddress); event IncludeInReward(address includedAddress); event ExcludeFromFee(address excludedAddress); event IncludeInFee(address includedAddress); event SetBuyFee(uint256 marketingFee, uint256 liquidityFee, uint256 reflectFee, uint256 buybackFee); event SetSellFee(uint256 marketingFee, uint256 liquidityFee, uint256 reflectFee, uint256 buybackFee); event TransferForeignToken(address token, uint256 amount); event UpdatedMarketingAddress(address marketing); event UpdatedLiquidityAddress(address liquidity); event UpdatedTeamAddress(address buyback); event OwnerForcedSwapBack(uint256 timestamp); event BoughtEarly(address indexed sniper); event RemovedSniper(address indexed notsnipersupposedly); event UpdatedRouter(address indexed newrouter); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() { _rOwned[_msgSender()] = _rTotal; uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH()); _setAutomatedMarketMakerPair(uniswapV2Pair, true); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[marketingAddress] = true; _isExcludedFromFee[liquidityAddress] = true; excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); tradingActive = true; swapAndLiquifyEnabled = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() external pure returns (string memory) { return _name; } function symbol() external pure returns (string memory) { return _symbol; } function decimals() external pure returns (uint8) { return _decimals; } function totalSupply() external pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) external view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) external override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { _transfer(sender, recipient, amount); _approve(sender,_msgSender(),_allowances[sender][_msgSender()].sub(amount,"ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) { _approve(_msgSender(),spender,_allowances[_msgSender()][spender].add(addedValue)); return true; } function clearStuckBalance(uint256 amountPercentage) external onlyOwner { uint256 amount = address(this).balance; payable(msg.sender).transfer(amount * amountPercentage / 100); } function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) { _approve(_msgSender(),spender,_allowances[_msgSender()][spender].sub(subtractedValue,"ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) external view returns (bool) { return _isExcluded[account]; } function totalFees() external view returns (uint256) { return _tFeeTotal; } function minimumTokensBeforeSwapAmount() external view returns (uint256) { return minimumTokensBeforeSwap; } function setminimumTokensBeforeSwapAmount(uint256 ratio) external onlyOwner() { minimumTokensBeforeSwap = _tTotal * ratio / 10000; } function setAutomatedMarketMakerPair(address pair, bool value) external onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; excludeFromMaxTransaction(pair, value); emit SetAutomatedMarketMakerPair(pair, value); } if(value){excludeFromReward(pair);} if(!value){includeInReward(pair);} function setProtectionSettings(bool antiGas) external onlyOwner() { gasLimitActive = antiGas; } function setGasPriceLimit(uint256 gas) external onlyOwner { require(gas >= 75); gasPriceLimit = gas * 1 gwei; } function setGasMaxLimit(uint256 gas) external onlyOwner { require(gas >= 750000); gasMaxLimit = gas * gasPriceLimit; } function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; gasLimitActive = false; return true; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } } else { function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); require(_excluded.length + 1 <= 50, "Cannot exclude more than 50 accounts. Include a previously excluded address."); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); require(_excluded.length + 1 <= 50, "Cannot exclude more than 50 accounts. Include a previously excluded address."); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) public onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeInReward(address account) public onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeInReward(address account) public onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function _approve(address owner, address spender, uint256 amount) private { 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 _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify) { if(from != owner() && to != uniswapV2Pair && block.number == tradingActiveBlock) { boughtEarly[to] = true; emit BoughtEarly(to); } if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap + _teamTokensToSwap; uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; buyOrSellSwitch = TRANSFER; if (automatedMarketMakerPairs[from]) { removeAllFee(); _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee + _buyTeamFee; buyOrSellSwitch = BUY; } else if (automatedMarketMakerPairs[to]) { removeAllFee(); _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee + _sellTeamFee; buyOrSellSwitch = SELL; if(boughtEarly[from] && earlyBuyPenaltyEnd <= block.number){ _taxFee = _taxFee * 2; _liquidityFee = _liquidityFee * 2; } removeAllFee(); buyOrSellSwitch = TRANSFER; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify) { if(from != owner() && to != uniswapV2Pair && block.number == tradingActiveBlock) { boughtEarly[to] = true; emit BoughtEarly(to); } if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap + _teamTokensToSwap; uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; buyOrSellSwitch = TRANSFER; if (automatedMarketMakerPairs[from]) { removeAllFee(); _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee + _buyTeamFee; buyOrSellSwitch = BUY; } else if (automatedMarketMakerPairs[to]) { removeAllFee(); _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee + _sellTeamFee; buyOrSellSwitch = SELL; if(boughtEarly[from] && earlyBuyPenaltyEnd <= block.number){ _taxFee = _taxFee * 2; _liquidityFee = _liquidityFee * 2; } removeAllFee(); buyOrSellSwitch = TRANSFER; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify) { if(from != owner() && to != uniswapV2Pair && block.number == tradingActiveBlock) { boughtEarly[to] = true; emit BoughtEarly(to); } if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap + _teamTokensToSwap; uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; buyOrSellSwitch = TRANSFER; if (automatedMarketMakerPairs[from]) { removeAllFee(); _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee + _buyTeamFee; buyOrSellSwitch = BUY; } else if (automatedMarketMakerPairs[to]) { removeAllFee(); _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee + _sellTeamFee; buyOrSellSwitch = SELL; if(boughtEarly[from] && earlyBuyPenaltyEnd <= block.number){ _taxFee = _taxFee * 2; _liquidityFee = _liquidityFee * 2; } removeAllFee(); buyOrSellSwitch = TRANSFER; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify) { if(from != owner() && to != uniswapV2Pair && block.number == tradingActiveBlock) { boughtEarly[to] = true; emit BoughtEarly(to); } if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap + _teamTokensToSwap; uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; buyOrSellSwitch = TRANSFER; if (automatedMarketMakerPairs[from]) { removeAllFee(); _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee + _buyTeamFee; buyOrSellSwitch = BUY; } else if (automatedMarketMakerPairs[to]) { removeAllFee(); _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee + _sellTeamFee; buyOrSellSwitch = SELL; if(boughtEarly[from] && earlyBuyPenaltyEnd <= block.number){ _taxFee = _taxFee * 2; _liquidityFee = _liquidityFee * 2; } removeAllFee(); buyOrSellSwitch = TRANSFER; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify) { if(from != owner() && to != uniswapV2Pair && block.number == tradingActiveBlock) { boughtEarly[to] = true; emit BoughtEarly(to); } if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap + _teamTokensToSwap; uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; buyOrSellSwitch = TRANSFER; if (automatedMarketMakerPairs[from]) { removeAllFee(); _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee + _buyTeamFee; buyOrSellSwitch = BUY; } else if (automatedMarketMakerPairs[to]) { removeAllFee(); _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee + _sellTeamFee; buyOrSellSwitch = SELL; if(boughtEarly[from] && earlyBuyPenaltyEnd <= block.number){ _taxFee = _taxFee * 2; _liquidityFee = _liquidityFee * 2; } removeAllFee(); buyOrSellSwitch = TRANSFER; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify) { if(from != owner() && to != uniswapV2Pair && block.number == tradingActiveBlock) { boughtEarly[to] = true; emit BoughtEarly(to); } if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap + _teamTokensToSwap; uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; buyOrSellSwitch = TRANSFER; if (automatedMarketMakerPairs[from]) { removeAllFee(); _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee + _buyTeamFee; buyOrSellSwitch = BUY; } else if (automatedMarketMakerPairs[to]) { removeAllFee(); _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee + _sellTeamFee; buyOrSellSwitch = SELL; if(boughtEarly[from] && earlyBuyPenaltyEnd <= block.number){ _taxFee = _taxFee * 2; _liquidityFee = _liquidityFee * 2; } removeAllFee(); buyOrSellSwitch = TRANSFER; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify) { if(from != owner() && to != uniswapV2Pair && block.number == tradingActiveBlock) { boughtEarly[to] = true; emit BoughtEarly(to); } if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap + _teamTokensToSwap; uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; buyOrSellSwitch = TRANSFER; if (automatedMarketMakerPairs[from]) { removeAllFee(); _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee + _buyTeamFee; buyOrSellSwitch = BUY; } else if (automatedMarketMakerPairs[to]) { removeAllFee(); _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee + _sellTeamFee; buyOrSellSwitch = SELL; if(boughtEarly[from] && earlyBuyPenaltyEnd <= block.number){ _taxFee = _taxFee * 2; _liquidityFee = _liquidityFee * 2; } removeAllFee(); buyOrSellSwitch = TRANSFER; } } _tokenTransfer(from, to, amount, takeFee); } if (!inSwapAndLiquify && function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify) { if(from != owner() && to != uniswapV2Pair && block.number == tradingActiveBlock) { boughtEarly[to] = true; emit BoughtEarly(to); } if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap + _teamTokensToSwap; uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; buyOrSellSwitch = TRANSFER; if (automatedMarketMakerPairs[from]) { removeAllFee(); _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee + _buyTeamFee; buyOrSellSwitch = BUY; } else if (automatedMarketMakerPairs[to]) { removeAllFee(); _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee + _sellTeamFee; buyOrSellSwitch = SELL; if(boughtEarly[from] && earlyBuyPenaltyEnd <= block.number){ _taxFee = _taxFee * 2; _liquidityFee = _liquidityFee * 2; } removeAllFee(); buyOrSellSwitch = TRANSFER; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify) { if(from != owner() && to != uniswapV2Pair && block.number == tradingActiveBlock) { boughtEarly[to] = true; emit BoughtEarly(to); } if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap + _teamTokensToSwap; uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; buyOrSellSwitch = TRANSFER; if (automatedMarketMakerPairs[from]) { removeAllFee(); _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee + _buyTeamFee; buyOrSellSwitch = BUY; } else if (automatedMarketMakerPairs[to]) { removeAllFee(); _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee + _sellTeamFee; buyOrSellSwitch = SELL; if(boughtEarly[from] && earlyBuyPenaltyEnd <= block.number){ _taxFee = _taxFee * 2; _liquidityFee = _liquidityFee * 2; } removeAllFee(); buyOrSellSwitch = TRANSFER; } } _tokenTransfer(from, to, amount, takeFee); } } else { function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify) { if(from != owner() && to != uniswapV2Pair && block.number == tradingActiveBlock) { boughtEarly[to] = true; emit BoughtEarly(to); } if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap + _teamTokensToSwap; uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; buyOrSellSwitch = TRANSFER; if (automatedMarketMakerPairs[from]) { removeAllFee(); _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee + _buyTeamFee; buyOrSellSwitch = BUY; } else if (automatedMarketMakerPairs[to]) { removeAllFee(); _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee + _sellTeamFee; buyOrSellSwitch = SELL; if(boughtEarly[from] && earlyBuyPenaltyEnd <= block.number){ _taxFee = _taxFee * 2; _liquidityFee = _liquidityFee * 2; } removeAllFee(); buyOrSellSwitch = TRANSFER; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify) { if(from != owner() && to != uniswapV2Pair && block.number == tradingActiveBlock) { boughtEarly[to] = true; emit BoughtEarly(to); } if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap + _teamTokensToSwap; uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; buyOrSellSwitch = TRANSFER; if (automatedMarketMakerPairs[from]) { removeAllFee(); _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee + _buyTeamFee; buyOrSellSwitch = BUY; } else if (automatedMarketMakerPairs[to]) { removeAllFee(); _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee + _sellTeamFee; buyOrSellSwitch = SELL; if(boughtEarly[from] && earlyBuyPenaltyEnd <= block.number){ _taxFee = _taxFee * 2; _liquidityFee = _liquidityFee * 2; } removeAllFee(); buyOrSellSwitch = TRANSFER; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify) { if(from != owner() && to != uniswapV2Pair && block.number == tradingActiveBlock) { boughtEarly[to] = true; emit BoughtEarly(to); } if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap + _teamTokensToSwap; uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance) { swapBack(); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; buyOrSellSwitch = TRANSFER; if (automatedMarketMakerPairs[from]) { removeAllFee(); _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee + _buyTeamFee; buyOrSellSwitch = BUY; } else if (automatedMarketMakerPairs[to]) { removeAllFee(); _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee + _sellTeamFee; buyOrSellSwitch = SELL; if(boughtEarly[from] && earlyBuyPenaltyEnd <= block.number){ _taxFee = _taxFee * 2; _liquidityFee = _liquidityFee * 2; } removeAllFee(); buyOrSellSwitch = TRANSFER; } } _tokenTransfer(from, to, amount, takeFee); } } else { function swapBack() private lockTheSwap { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _liquidityTokensToSwap.add(_teamTokensToSwap).add(_marketingTokensToSwap); uint256 tokensForLiquidity = _liquidityTokensToSwap.div(2); uint256 amountToSwapForCrypto = contractBalance.sub(tokensForLiquidity); uint256 initialCryptoBalance = address(this).balance; swapTokensForCrypto(amountToSwapForCrypto); uint256 cryptoBalance = address(this).balance.sub(initialCryptoBalance); uint256 cryptoForMarketing = cryptoBalance.mul(3*_marketingTokensToSwap/4).div(totalTokensToSwap); uint256 cryptoForCharity = cryptoBalance.mul(_marketingTokensToSwap/4).div(totalTokensToSwap); uint256 cryptoForTeam1 = cryptoBalance.mul(_teamTokensToSwap/2).div(totalTokensToSwap); uint256 cryptoForTeam2 = cryptoBalance.mul(_teamTokensToSwap/2).div(totalTokensToSwap); uint256 cryptoForLiquidity = cryptoBalance.sub(cryptoForMarketing).sub(cryptoForTeam1).sub(cryptoForTeam2).sub(cryptoForCharity); _liquidityTokensToSwap = 0; _marketingTokensToSwap = 0; _teamTokensToSwap = 0; addLiquidity(tokensForLiquidity, cryptoForLiquidity); emit SwapAndLiquify(amountToSwapForCrypto, cryptoForLiquidity, tokensForLiquidity); if(address(this).balance > 0){ swapETHForTokens(address(this).balance); } } (bool success,) = address(ownerAddress).call{value: cryptoForTeam1}(""); (success,) = address(marketingAddress).call{value: cryptoForCharity}(""); (success,) = address(ownerAddress).call{value: cryptoForTeam2}(""); (success,) = address(marketingAddress).call{value: cryptoForMarketing}(""); function swapBack() private lockTheSwap { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _liquidityTokensToSwap.add(_teamTokensToSwap).add(_marketingTokensToSwap); uint256 tokensForLiquidity = _liquidityTokensToSwap.div(2); uint256 amountToSwapForCrypto = contractBalance.sub(tokensForLiquidity); uint256 initialCryptoBalance = address(this).balance; swapTokensForCrypto(amountToSwapForCrypto); uint256 cryptoBalance = address(this).balance.sub(initialCryptoBalance); uint256 cryptoForMarketing = cryptoBalance.mul(3*_marketingTokensToSwap/4).div(totalTokensToSwap); uint256 cryptoForCharity = cryptoBalance.mul(_marketingTokensToSwap/4).div(totalTokensToSwap); uint256 cryptoForTeam1 = cryptoBalance.mul(_teamTokensToSwap/2).div(totalTokensToSwap); uint256 cryptoForTeam2 = cryptoBalance.mul(_teamTokensToSwap/2).div(totalTokensToSwap); uint256 cryptoForLiquidity = cryptoBalance.sub(cryptoForMarketing).sub(cryptoForTeam1).sub(cryptoForTeam2).sub(cryptoForCharity); _liquidityTokensToSwap = 0; _marketingTokensToSwap = 0; _teamTokensToSwap = 0; addLiquidity(tokensForLiquidity, cryptoForLiquidity); emit SwapAndLiquify(amountToSwapForCrypto, cryptoForLiquidity, tokensForLiquidity); if(address(this).balance > 0){ swapETHForTokens(address(this).balance); } } function swapTokensForCrypto(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, 0, path, address(this), block.timestamp); } function swapETHForTokens(uint256 amount) private { address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); emit SwapETHForTokens(amount, path); } uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}(0, path,deadAddress, block.timestamp.add(300)); function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); } uniswapV2Router.addLiquidityETH{ value: ethAmount }(address(this), tokenAmount, 0, 0, liquidityAddress, block.timestamp); function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } restoreAllFee(); } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } restoreAllFee(); } } else if (!_isExcluded[sender] && _isExcluded[recipient]) { } else if (_isExcluded[sender] && _isExcluded[recipient]) { } else { function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount,rTransferAmount,rFee,tTransferAmount,tFee,tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256 ){ uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { if(buyOrSellSwitch == BUY){ _liquidityTokensToSwap += tLiquidity * _buyLiquidityFee / _liquidityFee; _teamTokensToSwap += tLiquidity * _buyTeamFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _buyMarketingFee / _liquidityFee; _liquidityTokensToSwap += tLiquidity * _sellLiquidityFee / _liquidityFee; _teamTokensToSwap += tLiquidity * _sellTeamFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _sellMarketingFee / _liquidityFee; } uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function _takeLiquidity(uint256 tLiquidity) private { if(buyOrSellSwitch == BUY){ _liquidityTokensToSwap += tLiquidity * _buyLiquidityFee / _liquidityFee; _teamTokensToSwap += tLiquidity * _buyTeamFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _buyMarketingFee / _liquidityFee; _liquidityTokensToSwap += tLiquidity * _sellLiquidityFee / _liquidityFee; _teamTokensToSwap += tLiquidity * _sellTeamFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _sellMarketingFee / _liquidityFee; } uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } } else if(buyOrSellSwitch == SELL){ function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10**2); } function removeAllFee() private { if (_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) external view returns (bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) external onlyOwner { _isExcludedFromFee[account] = true; emit ExcludeFromFee(account); } function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; emit IncludeInFee(account); } function removeBoughtEarly(address account) external onlyOwner { boughtEarly[account] = false; emit RemovedSniper(account); } function setBuyFee(uint256 buyTaxFee, uint256 buyLiquidityFee, uint256 buyMarketingFee, uint256 buyTeamFee) external onlyOwner { _buyTaxFee = buyTaxFee; _buyLiquidityFee = buyLiquidityFee; _buyMarketingFee = buyMarketingFee; _buyTeamFee = buyTeamFee; emit SetBuyFee(buyMarketingFee, buyLiquidityFee, buyTaxFee, buyTeamFee); } function setSellFee(uint256 sellTaxFee, uint256 sellLiquidityFee, uint256 sellMarketingFee, uint256 sellTeamFee) external onlyOwner { _sellTaxFee = sellTaxFee; _sellLiquidityFee = sellLiquidityFee; _sellMarketingFee = sellMarketingFee; _sellTeamFee = sellTeamFee; emit SetSellFee(sellMarketingFee, sellLiquidityFee, sellTaxFee, sellTeamFee); } function setMarketingAddress(address _marketingAddress) external onlyOwner { require(_marketingAddress != address(0), "_marketingAddress address cannot be 0"); marketingAddress = payable(_marketingAddress); _isExcludedFromFee[marketingAddress] = true; emit UpdatedMarketingAddress(_marketingAddress); } function setTeamAddress(address _teamAddress) external onlyOwner { require(_teamAddress != address(0), "_teamAddress address cannot be 0"); teamAddress = payable(_teamAddress); _isExcludedFromFee[teamAddress] = true; emit UpdatedTeamAddress(teamAddress); } function setLiquidityAddress(address _liquidityAddress) external onlyOwner { require(_liquidityAddress != address(0), "_liquidityAddress address cannot be 0"); liquidityAddress = payable(_liquidityAddress); _isExcludedFromFee[liquidityAddress] = true; emit UpdatedLiquidityAddress(_liquidityAddress); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function getPairAddress() external view onlyOwner returns (address) { return uniswapV2Pair; } function changeRouterVersion(address _router) external onlyOwner returns (address _pair) { require(_router != address(0), "_router address cannot be 0"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(_router); _pair = IUniswapV2Factory(_uniswapV2Router.factory()).getPair( address(this), _uniswapV2Router.WETH() ); if (_pair == address(0)) { _pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair( address(this), _uniswapV2Router.WETH() ); } uniswapV2Pair = _pair; emit UpdatedRouter(_router); } function changeRouterVersion(address _router) external onlyOwner returns (address _pair) { require(_router != address(0), "_router address cannot be 0"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(_router); _pair = IUniswapV2Factory(_uniswapV2Router.factory()).getPair( address(this), _uniswapV2Router.WETH() ); if (_pair == address(0)) { _pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair( address(this), _uniswapV2Router.WETH() ); } uniswapV2Pair = _pair; emit UpdatedRouter(_router); } uniswapV2Router = _uniswapV2Router; receive() external payable {} function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) { require(_token != address(0), "_token address cannot be 0"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); _sent = IERC20(_token).transfer(_to, _contractBalance); emit TransferForeignToken(_token, _contractBalance); } }
8,428,707
[ 1, 451, 3392, 924, 854, 7517, 9816, 11078, 3241, 2898, 336, 15345, 364, 3614, 7827, 16, 1496, 326, 12150, 1221, 518, 15857, 358, 1440, 598, 783, 6835, 18, 1220, 903, 506, 5765, 358, 4543, 4657, 316, 326, 1122, 11315, 6824, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 16628, 6312, 3865, 706, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 1758, 8843, 429, 1071, 13667, 310, 1887, 273, 8843, 429, 12, 20, 92, 1105, 22, 9793, 7950, 41, 9599, 16410, 31831, 4848, 70, 37, 25, 38, 8749, 71, 5718, 73, 3672, 29534, 20, 5292, 27, 74, 42, 74, 23, 42, 1769, 377, 203, 565, 1758, 8843, 429, 1071, 5927, 1887, 273, 8843, 429, 12, 20, 7669, 39, 73, 20, 16894, 20, 71, 26, 1578, 5082, 10580, 38, 20562, 40, 4366, 70, 20, 38, 9803, 40, 3247, 70, 7142, 39, 11149, 41, 70, 29, 40, 1769, 27699, 565, 1758, 8843, 429, 3238, 3410, 1887, 273, 8843, 429, 12, 20, 7669, 39, 73, 20, 16894, 20, 71, 26, 1578, 5082, 10580, 38, 20562, 40, 4366, 70, 20, 38, 9803, 40, 3247, 70, 7142, 39, 11149, 41, 70, 29, 40, 1769, 377, 203, 565, 1758, 8843, 429, 4501, 372, 24237, 1887, 273, 8843, 429, 12, 3576, 18, 15330, 1769, 1850, 203, 565, 1758, 1071, 11732, 8363, 1887, 273, 374, 92, 12648, 12648, 12648, 12648, 2787, 72, 41, 69, 40, 31, 7010, 540, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 565, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./NonFungibleRegistryEnumerableUpgradeable.sol"; import "./NonFungibleRegistryUpgradeable.sol"; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; import "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol"; import "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol"; /** * @title Hypernet Protocol Non Fungible Registry Factory * @author Todd Chapman * @dev Upgradable beacon factor contract for efficiently deploying new * Non Fungible Registries. * * See the Hypernet Protocol documentation for more information: * https://docs.hypernet.foundation/hypernet-protocol/governance * * See unit tests for example usage: * https://github.com/GoHypernet/hypernet-protocol/blob/dev/packages/contracts/test/upgradeable-factory-test.js */ contract UpgradeableRegistryFactory is AccessControlEnumerable { /// @dev address of our upgradeble registry with enumeration proxy beacon address public enumerableRegistryBeacon; /// @dev address of our upgradable registry proxy beacon address public registryBeacon; /// @dev address of registry that serves os the Hypernet User Profile registry address public hypernetProfileRegistry = address(0); /// @dev extra array storage fascilitates paginated UI address[] public enumerableRegistries; /// @dev extra array storage fascilitates paginated UI address[] public registries; /// @notice Use this mapping to find the true deployment address of a project's NFR via the project name /// @dev This mapping is updated everytime this is a new NFR created by the factory mapping (string => address) public nameToAddress; /// @notice Address indicating what ERC-20 token can be used with createRegistryByToken /// @dev This address variable is used in conjunction with burnFee and burnAddress for the registerByToken function. Setting to the zero address disables the feature. address public registrationToken; /// @notice The amount of registrationToken required to call createRegistryByToken /// @dev Be sure you check the number of decimals associated with the ERC-20 contract at the registrationToken address uint256 public registrationFee = 50e18; // assume 18 decimal places /// @notice This is the address where registrationToken is forwarded upon a call to createRegistryByToken /// @dev The amount of registrationToken sent to this address is equal to {registrationFee * burnFee / 10000} address public burnAddress; /** * @dev Emitted when `DEFAULT_ADMIN_ROLE` creates a new registry. */ event RegistryCreated(address registryAddress); /// @notice constructor called on contract deployment /// @param _admin address who can call the createRegistry function /// @param _names array of names for the registries created on deployment /// @param _symbols array of symbols for the registries created on deployment /// @param _registrars array of addresses to recieve the REGISTRAR_ROLE for the registries created on deployment /// @param _enumerableRegistry address of implementation of enumerable NFR /// @param _registry address of implementation of non-enumerable NFR /// @param _registrationToken address of ERC20 token used for enabling the creation of registries by burning token constructor(address _admin, string[] memory _names, string[] memory _symbols, address[] memory _registrars, address _enumerableRegistry, address _registry, address _registrationToken) { require(_names.length == _symbols.length, "RegistryFactory: Initializer arrays must be equal length."); require(_symbols.length == _registrars.length, "RegistryFactory: Initializer arrays must be equal length."); // set the administrator of the registry factory _setupRole(DEFAULT_ADMIN_ROLE, _admin); // deploy upgradable beacon instance of enumerable registry contract UpgradeableBeacon _enumerableRegistryBeacon = new UpgradeableBeacon(_enumerableRegistry); _enumerableRegistryBeacon.transferOwnership(_admin); enumerableRegistryBeacon = address(_enumerableRegistryBeacon); // deploy upgradable beacon instance of registry contract UpgradeableBeacon _registryBeacon = new UpgradeableBeacon(_registry); _registryBeacon.transferOwnership(_admin); registryBeacon = address(_registryBeacon); registrationToken = _registrationToken; burnAddress = _admin; // deploy initial enumerable registries for (uint256 i = 0; i < _names.length; ++i) { _createEnumerableRegistry(_names[i], _symbols[i], _registrars[i]); // use the first enumerable registry as the hypernet profile registry if (i == 0) { hypernetProfileRegistry = enumerableRegistries[0]; } } } /// @notice getNumberOfEnumerableRegistries getter function for reading the number of enumerable registries /// @dev useful for paginated UIs function getNumberOfEnumerableRegistries() public view returns (uint256 numReg) { numReg = enumerableRegistries.length; } /// @notice getNumberOfRegistries getter function for reading the number of registries /// @dev useful for paginated UIs function getNumberOfRegistries() public view returns (uint256 numReg) { numReg = registries.length; } /// @notice setProfileRegistryAddress change the address of the profile registry contract /// @dev can only be called by the DEFAULT_ADMIN_ROLE /// @param _hypernetProfileRegistry address of ERC721 token to use as profile contract function setProfileRegistryAddress(address _hypernetProfileRegistry) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "RegistryFactory: must have admin role to set parameters"); hypernetProfileRegistry = _hypernetProfileRegistry; } /// @notice setRegistrationToken setter function for configuring which ERC20 token is burned when adding new apps /// @dev can only be called by the DEFAULT_ADMIN_ROLE /// @param _registrationToken address of ERC20 token burned during registration function setRegistrationToken(address _registrationToken) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "RegistryFactory: must have admin role to set parameters"); registrationToken = _registrationToken; } /// @notice setRegistrationFee setter function for configuring how much token is burned when adding new apps /// @dev can only be called by the DEFAULT_ADMIN_ROLE /// @param _registrationFee burn fee amount function setRegistrationFee(uint256 _registrationFee) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "RegistryFactory: must have admin role to set parameters"); require(registrationFee >= 0, "RegistryFactory: Registration fee must be nonnegative."); registrationFee = _registrationFee; } /// @notice setBurnAddress setter function for configuring where tokens are sent when calling createRegistryByToken /// @dev can only be called by the DEFAULT_ADMIN_ROLE /// @param _burnAddress address where creation fee is to be sent function setBurnAddress(address _burnAddress) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "RegistryFactory: must have admin role to set parameters"); burnAddress = _burnAddress; } /// @notice createRegistry called by DEFAULT_ADMIN_ROLE to create registries without a fee /// @dev the registry inherents the same admin as the factory /// @param _name name of the registry that will be created /// @param _symbol symbol to associate with the registry /// @param _registrar address that will recieve the REGISTRAR_ROLE /// @param _enumerable boolean declaring if the registry should have the enumeration property function createRegistry(string calldata _name, string calldata _symbol, address _registrar, bool _enumerable) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "RegistryFactory: must have admin role to create a registry"); if (_enumerable) { _createEnumerableRegistry(_name, _symbol, _registrar); } else { _createRegistry(_name, _symbol, _registrar); } } /// @notice createRegistryByToken called by any user with sufficient registration token /// @dev the registry inherents the same admin as the factory /// @param _name name of the registry that will be created /// @param _symbol symbol to associate with the registry /// @param _registrar address that will recieve the REGISTRAR_ROLE function createRegistryByToken(string memory _name, string memory _symbol, address _registrar, bool _enumerable) external { require(_preRegistered(_msgSender()), "RegistryFactory: caller must have a Hypernet Profile."); require(registrationToken != address(0), "RegistryFactory: registration by token not enabled."); // user must call approve first require(IERC20Upgradeable(registrationToken).transferFrom(_msgSender(), burnAddress, registrationFee), "RegistryFactory: token transfer failed."); if (_enumerable) { _createEnumerableRegistry(_name, _symbol, _registrar); } else { _createRegistry(_name, _symbol, _registrar); } } function _createEnumerableRegistry(string memory _name, string memory _symbol, address _registrar) private { require(_registrar != address(0), "RegistryFactory: Registrar address must not be 0."); require(!_registryExists(_name), "RegistryFactory: Registry by that name exists."); // cloning the beacon implementation reduced gas by ~80% over naive approach BeaconProxy proxy = new BeaconProxy(enumerableRegistryBeacon, abi.encodeWithSelector(NonFungibleRegistryEnumerableUpgradeable.initialize.selector, _name, _symbol, hypernetProfileRegistry, _registrar, getRoleMember(DEFAULT_ADMIN_ROLE, 0))); enumerableRegistries.push(address(proxy)); nameToAddress[_name] = address(proxy); emit RegistryCreated(address(proxy)); } function _createRegistry(string memory _name, string memory _symbol, address _registrar) private { require(_registrar != address(0), "RegistryFactory: Registrar address must not be 0."); require(!_registryExists(_name), "RegistryFactory: Registry by that name exists."); // cloning the beacon implementation reduced gas by ~80% over naive approach BeaconProxy proxy = new BeaconProxy(registryBeacon, abi.encodeWithSelector(NonFungibleRegistryUpgradeable.initialize.selector, _name, _symbol, hypernetProfileRegistry, _registrar, getRoleMember(DEFAULT_ADMIN_ROLE, 0))); registries.push(address(proxy)); nameToAddress[_name] = address(proxy); emit RegistryCreated(address(proxy)); } function _registryExists(string memory _name) internal view virtual returns (bool) { // registry name must have non-zero length and must not exist already return !((bytes(_name).length > 0) && nameToAddress[_name] == address(0)); } function _preRegistered(address owner) internal view virtual returns (bool) { // check if there if a profile is required and if so // does the recipient have a non-zero balance. return ((hypernetProfileRegistry == address(0)) || (IERC721Upgradeable(hypernetProfileRegistry).balanceOf(owner) > 0)); } }
assume 18 decimal places
uint256 public registrationFee = 50e18;
14,055,365
[ 1, 428, 2066, 6549, 6970, 12576, 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, 2254, 5034, 1071, 7914, 14667, 273, 6437, 73, 2643, 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.8.10; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "./IFoxGameNFTTraits.sol"; import "./IFoxGameCarrot.sol"; import "./IFoxGameNFT.sol"; import "./IFoxGame.sol"; contract FoxGameNFT is IFoxGameNFT, ERC721Enumerable, Ownable, ReentrancyGuard { // Presale status bool public presaleActive; bool public saleActive; // Rarity trait probabilities uint8[][21] private rarities; uint8[][21] private aliases; // Mumber of players minted uint16 public minted; // Maximum players in the game uint16 public constant MAX_TOKENS = 50000; // Number of GEN 0 tokens uint16 public constant MAX_GEN0_TOKENS = 10000; // Maximum mint per transaction (per account during whitelist) uint32 public maxMint = 10; // Time denominator for seeding randomness. uint32 private seedRotationSeconds = 90 days; // External contracts IFoxGameCarrot private immutable foxCarrot; IFoxGame private immutable foxGame; IFoxGameNFTTraits private foxTraits; // GEN 0 mint price uint256 public constant MINT_PRICE = 0.0649 ether; // Mapping of token ID to player traits mapping(uint16 => Traits) private tokenTraits; // Whitelist mint count mapping (address => uint32) public presaleMinted; // Store previous trait combinations to prevent duplicates mapping(uint256 => bool) private knownCombinations; // isApprovedForAll registry mapping(address => bool) private approvedWhitelist; // Events event Mint(string kind, address owner, uint16 tokenId); event PresaleActive(bool active); event SaleActive(bool active); // Initialize constructor(address carrot, address game, address traits) ERC721("FoxGame", "FOX") { foxCarrot = IFoxGameCarrot(carrot); foxGame = IFoxGame(game); foxTraits = IFoxGameNFTTraits(traits); // Precomputed rarity probabilities on chain. // (via walker's alias algorithm) // RABBIT // Fur rarities[0] = [ 153, 153, 255, 102, 77, 230 ]; aliases[0] = [ 2, 2, 0, 2, 3, 3 ]; // Paws rarities[1] = [ 61, 184, 122, 122, 61, 255, 204, 122, 224, 255, 214, 184, 235, 61, 184, 184, 184, 122, 122, 184, 153, 245, 143, 224 ]; aliases[1] = [ 6, 8, 8, 9, 10, 0, 5, 15, 6, 8, 9, 15, 10, 20, 20, 12, 21, 22, 23, 23, 15, 20, 21, 22 ]; // Mouth rarities[2] = [ 191, 77, 191, 255, 38, 115, 204, 153, 191, 38, 64, 115, 77, 115, 128 ]; aliases[2] = [ 3, 3, 3, 0, 7, 7, 3, 6, 7, 10, 8, 13, 14, 10, 13 ]; // Nose rarities[3] = [ 255, 242, 153, 204, 115, 230, 230, 115, 115 ]; aliases[3] = [ 0, 0, 1, 2, 0, 0, 0, 2, 3 ]; // Eyes rarities[4] = [ 77, 255, 128, 77, 153, 153, 153, 77, 153, 230, 77, 77, 77, 204, 179, 230, 77, 179, 128, 179, 153, 230, 77, 77, 102, 77, 153, 153, 204, 77 ]; aliases[4] = [ 3, 0, 1, 2, 13, 13, 13, 13, 14, 14, 18, 19, 20, 3, 13, 20, 24, 14, 17, 18, 19, 20, 25, 25, 21, 24, 25, 26, 26, 28 ]; // Ears rarities[5] = [ 41, 61, 102, 204, 255, 102, 204, 204 ]; aliases[5] = [ 5, 5, 5, 5, 0, 4, 5, 5 ]; // Head rarities[6] = [ 87, 255, 130, 245, 173, 173, 191, 87, 176, 128, 217, 43, 173, 217, 92, 217, 43 ]; aliases[6] = [ 1, 0, 3, 1, 6, 6, 3, 9, 6, 8, 9, 9, 9, 9, 9, 9, 14 ]; // FOX // Tail rarities[7] = [ 255, 153, 204, 102 ]; aliases[7] = [ 0, 0, 0, 1 ]; // Fur rarities[8] = [ 255, 204, 153, 153 ]; aliases[8] = [ 0, 0, 1, 1 ]; // Feet rarities[9] = [ 255, 255, 229, 204, 229, 204, 179, 255, 255, 128 ]; aliases[9] = [ 0, 0, 1, 2, 3, 2, 3, 0, 0, 4 ]; // Neck rarities[10] = [ 255, 204, 204, 204, 127, 102, 51, 255, 255, 26 ]; aliases[10] = [ 0, 0, 1, 0, 2, 0, 1, 0, 0, 4 ]; // Mouth rarities[11] = [ 255, 102, 255, 255, 204, 153, 102, 255, 51, 51, 255, 204, 255, 204, 153, 204, 153, 51, 255, 51 ]; aliases[11] = [ 0, 2, 0, 2, 3, 2, 4, 6, 6, 6, 0, 7, 11, 12, 13, 7, 11, 13, 0, 14 ]; // Eyes rarities[12] = [ 56, 255, 179, 153, 158, 112, 133, 112, 112, 56, 250, 224, 199, 122, 240, 214, 189, 112, 112, 163, 112, 138 ]; aliases[12] = [ 1, 0, 1, 2, 3, 1, 4, 3, 6, 12, 6, 10, 11, 12, 13, 14, 15, 12, 13, 16, 21, 19 ]; // Cunning Score rarities[13] = [ 255, 153, 204, 102 ]; aliases[13] = [ 0, 0, 0, 1 ]; // HUNTER // Clothes rarities[14] = [ 128, 255, 128, 64, 255 ]; aliases[14] = [ 2, 0, 1, 2, 0 ]; // Weapon rarities[15] = [ 255, 153, 204, 102 ]; aliases[15] = [ 0, 0, 0, 1 ]; // Neck rarities[16] = [ 102, 255, 26, 153, 255 ]; aliases[16] = [ 1, 0, 3, 1, 0 ]; // Mouth rarities[17] = [ 255, 229, 179, 179, 89, 179, 217 ]; aliases[17] = [ 0, 0, 0, 6, 6, 6, 1 ]; // Eyes rarities[18] = [ 191, 255, 38, 77, 191, 77, 217, 38, 153, 191, 77, 191, 204, 77, 77 ]; aliases[18] = [ 1, 0, 4, 4, 1, 4, 5, 5, 6, 5, 5, 6, 8, 8, 12 ]; // Hat rarities[19] = [ 191, 38, 89, 255, 191 ]; aliases[19] = [ 3, 4, 4, 0, 3 ]; // Marksman Score rarities[20] = [ 255, 153, 204, 102 ]; aliases[20] = [ 0, 0, 0, 1 ]; } /** * Upload rarity propbabilties. Only used in emergencies. * @param traitTypeId trait name id (0 corresponds to "fur") * @param _rarities walker rarity probailities * @param _aliases walker aliases index */ function uploadTraits(uint8 traitTypeId, uint8[] calldata _rarities, uint8[] calldata _aliases) external onlyOwner { rarities[traitTypeId] = _rarities; aliases[traitTypeId] = _aliases; } /** * Enable Presale. */ function togglePresale() external onlyOwner { presaleActive = !presaleActive; emit PresaleActive(presaleActive); } /** * Enable Sale. */ function toggleSale() external onlyOwner { saleActive = !saleActive; emit PresaleActive(saleActive); } /** * Update the ERC-721 trait contract address. */ function setTraitsContract(address _address) external onlyOwner { foxTraits = IFoxGameNFTTraits(_address); } /** * Set the max mints per account during persale and per tx during public sale */ function setMaxMintAmount(uint32 _maxMint) external onlyOwner { maxMint = _maxMint; } /** * Expose traits to trait contract. */ function getTraits(uint16 tokenId) external view override returns (Traits memory) { return tokenTraits[tokenId]; } /** * Expose maximum GEN 0 tokens. */ function getMaxGEN0Players() external pure override returns (uint16) { return MAX_GEN0_TOKENS; } /** * Internal helper for minting. */ function _mint(uint32 amount, bool stake, uint256 originSeed) internal { Kind kind; uint16[] memory tokenIdsToStake = stake ? new uint16[](amount) : new uint16[](0); uint256 carrotCost; uint256 seed; for (uint32 i = 0; i < amount; i++) { minted++; seed = _reseedWithIndex(originSeed, i); carrotCost += getMintCarrotCost(minted); kind = _generateAndStoreTraits(minted, seed, 0).kind; address recipient = _selectRecipient(seed); if (!stake || recipient != msg.sender) { _safeMint(recipient, minted); } else { tokenIdsToStake[i] = minted; _safeMint(address(foxGame), minted); } emit Mint(kind == Kind.RABBIT ? "RABBIT" : kind == Kind.FOX ? "FOX" : "HUNTER", recipient, minted); } if (carrotCost > 0) { foxCarrot.burn(msg.sender, carrotCost); } if (stake) { foxGame.stakeTokens(msg.sender, tokenIdsToStake); } } /** * Mint your players. * @param amount number of tokens to mint * @param stake mint directly to staking * @param membership wheather user is membership or not * @param seed account seed * @param sig signature */ function presaleMint(uint32 amount, bool stake, bool membership, uint48 expiration, uint256 seed, bytes calldata sig) external payable nonReentrant { require(tx.origin == msg.sender, "eos only"); require(presaleActive, "minting is not active"); require(minted + amount <= MAX_TOKENS, "minted out"); require(expiration > block.timestamp, "signature has expired"); require(membership, "only members allowed"); require(foxGame.isValidSignature(msg.sender, membership, expiration, seed, sig), "invalid signature"); // Require ETH for GEN 0 only if (minted < MAX_GEN0_TOKENS) { require(minted + amount <= MAX_GEN0_TOKENS, "not enough available gen0 mints"); require(amount * MINT_PRICE == msg.value, "invalid payment amount"); } else { require(msg.value == 0, "only carrots required"); } // Allow only 10 per account during presale uint32 claimed = presaleMinted[msg.sender]; require(amount > 0 && amount <= maxMint - claimed, "cannot exceed presale mints"); presaleMinted[msg.sender] = claimed + amount; _mint(amount, stake, seed); } /** * Mint your players. * @param amount number of tokens to mint * @param stake mint directly to staking * @param seed random seed per mint * @param sig signature */ function mint(uint32 amount, bool stake, uint256 seed, uint48 expiration, bytes calldata sig) external payable nonReentrant { require(tx.origin == msg.sender, "eos only"); require(saleActive, "minting is not active"); require(amount > 0 && amount <= maxMint, "invalid mint amount"); require(amount * MINT_PRICE == msg.value, "Invalid payment amount"); require(minted + amount <= MAX_TOKENS, "minted out"); require(expiration > block.timestamp, "signature has expired"); require(foxGame.isValidSignature(msg.sender, false, expiration, seed, sig), "invalid signature"); _mint(amount, stake, seed); } /** * Calculate the foxCarrot cost: * - the first 20% are paid in ETH * - the next 20% are 20000 $CARROT * - the next 40% are 40000 $CARROT * - the final 20% are 80000 $CARROT * @param tokenId the ID to check the cost of to mint * @return the cost of the given token ID */ function getMintCarrotCost(uint16 tokenId) public pure returns (uint256) { if (tokenId <= MAX_GEN0_TOKENS) return 0; if (tokenId <= MAX_TOKENS * 2 / 5) return 20000 ether; if (tokenId <= MAX_TOKENS * 4 / 5) return 40000 ether; return 80000 ether; } /** * Generate and store player traits. Recursively called to ensure uniqueness. * Give users 3 attempts, bit shifting the seed each time (uses 5 bytes of entropy before failing) * @param tokenId id of the token to generate traits * @param seed random 256 bit seed to derive traits * @return t player trait struct */ function _generateAndStoreTraits(uint16 tokenId, uint256 seed, uint8 attempt) internal returns (Traits memory t) { require(attempt < 6, "unable to generate unique traits"); t = _selectTraits(tokenId, seed); if (!knownCombinations[_structToHash(t)]) { tokenTraits[tokenId] = t; knownCombinations[_structToHash(t)] = true; return t; } return _generateAndStoreTraits(tokenId, seed >> attempt, attempt + 1); } /** * uses A.J. Walker's Alias algorithm for O(1) rarity table lookup * ensuring O(1) instead of O(n) reduces mint cost by more than 50% * probability & alias tables are generated off-chain beforehand * @param seed portion of the 256 bit seed to remove trait correlation * @param traitType the trait type to select a trait for * @return the ID of the randomly selected trait */ function _selectTrait(uint16 seed, uint8 traitType) internal view returns (uint8) { uint8 trait = uint8(seed) % uint8(rarities[traitType].length); if (seed >> 8 < rarities[traitType][trait]) return trait; return aliases[traitType][trait]; } /** * the first 20% (ETH purchases) go to the minter * the remaining 80% have a 10% chance to be given to a random staked fox * @param seed a random value to select a recipient from * @return the address of the recipient (either the minter or the fox thief's owner) */ function _selectRecipient(uint256 seed) internal view returns (address) { if (minted <= MAX_GEN0_TOKENS || ((seed >> 245) % 10) != 0) { return msg.sender; // top 10 bits haven't been used } // 144 bits reserved for trait selection address thief = foxGame.randomFoxOwner(seed >> 144); if (thief == address(0x0)) { return msg.sender; } return thief; } /** * selects the species and all of its traits based on the seed value * @param seed a pseudorandom 256 bit number to derive traits from * @return t struct of randomly selected traits */ function _selectTraits(uint16 tokenId, uint256 seed) internal view returns (Traits memory t) { // No Hunters until GEN 1 (RABBIT=0, FOX=1, HUNTER=2) if (tokenId <= MAX_GEN0_TOKENS) { t.kind = Kind((seed & 0xFFFF) % 10 == 0 ? 1 : 0); } else { uint mod = (seed & 0xFFFF) % 50; t.kind = Kind(mod == 0 ? 2 : mod < 5 ? 1 : 0); } // Use 128 bytes of seed entropy to define traits. uint8 offset = uint8(t.kind) * 7; // RABBIT FOX HUNTER seed >>= 16; t.traits[0] = _selectTrait(uint16(seed & 0xFFFF), 0 + offset); // Fur Tail Clothes seed >>= 16; t.traits[1] = _selectTrait(uint16(seed & 0xFFFF), 1 + offset); // Head Fur Eyes seed >>= 16; t.traits[2] = _selectTrait(uint16(seed & 0xFFFF), 2 + offset); // Ears Eyes Hat seed >>= 16; t.traits[3] = _selectTrait(uint16(seed & 0xFFFF), 3 + offset); // Eyes Mouth Mouth seed >>= 16; t.traits[4] = _selectTrait(uint16(seed & 0xFFFF), 4 + offset); // Nose Neck Neck seed >>= 16; t.traits[5] = _selectTrait(uint16(seed & 0xFFFF), 5 + offset); // Mouth Feet Weapon seed >>= 16; t.traits[6] = _selectTrait(uint16(seed & 0xFFFF), 6 + offset); // Paws Cunning Marksman t.advantage = t.traits[6]; } /** * converts a struct to a 256 bit hash to check for uniqueness * @param t the struct to pack into a hash * @return the 256 bit hash of the struct */ function _structToHash(Traits memory t) internal pure returns (uint256) { return uint256(bytes32( abi.encodePacked( t.kind, t.advantage, t.traits[0], t.traits[1], t.traits[2], t.traits[3], t.traits[4], t.traits[5], t.traits[6] ) )); } /** * Reseeds entropy with mint amount offset. * @param seed random seed * @param offset additional entropy during mint * @return rotated seed */ function _reseedWithIndex(uint256 seed, uint32 offset) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(seed, offset))); } /** * Allow private sales. */ function mintToAddress(uint256 amount, address recipient, uint256 originSeed) external onlyOwner { require(minted + amount <= MAX_TOKENS, "minted out"); require(amount > 0, "invalid mint amount"); Kind kind; uint256 seed; for (uint32 i = 0; i < amount; i++) { minted++; seed = _reseedWithIndex(originSeed, i); kind = _generateAndStoreTraits(minted, seed, 0).kind; _safeMint(recipient, minted); emit Mint(kind == Kind.RABBIT ? "RABBIT" : kind == Kind.FOX ? "FOX" : "HUNTER", recipient, minted); } } /** * Allows owner to withdraw funds from minting. */ function withdraw() external onlyOwner { payable(owner()).transfer(address(this).balance); } /** * Override transfer to avoid the approval step during staking. */ function transferFrom(address from, address to, uint256 tokenId) public override(ERC721, IFoxGameNFT) { if (msg.sender != address(foxGame)) { require(_isApprovedOrOwner(msg.sender, tokenId), "transfer not owner nor approved"); } _transfer(from, to, tokenId); } /** * Override NFT token uri. Calls into traits contract. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "nonexistent token"); return foxTraits.tokenURI(uint16(tokenId)); } /** * Ennumerate tokens by owner. */ function tokensOf(address owner) external view returns (uint16[] memory) { uint32 tokenCount = uint32(balanceOf(owner)); uint16[] memory tokensId = new uint16[](tokenCount); for (uint32 i = 0; i < tokenCount; i++){ tokensId[i] = uint16(tokenOfOwnerByIndex(owner, i)); } return tokensId; } /** * Overridden to resolve multiple inherited interfaces. */ function ownerOf(uint256 tokenId) public view override(ERC721, IFoxGameNFT) returns (address) { return super.ownerOf(tokenId); } /** * Overridden to resolve multiple inherited interfaces. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public override(ERC721, IFoxGameNFT) { super.safeTransferFrom(from, to, tokenId, _data); } } // SPDX-License-Identifier: MIT pragma solidity ^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() { _setOwner(_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 { _setOwner(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"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT 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 make 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @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 override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } /* ███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗ ██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝ █████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗ ██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝ ██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface IFoxGameNFTTraits { function tokenURI(uint16 tokenId) external view returns (string memory); } /* ███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗ ██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝ █████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗ ██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝ ██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface IFoxGameCarrot { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; } /* ███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗ ██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝ █████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗ ██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝ ██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface IFoxGameNFT { enum Kind { RABBIT, FOX, HUNTER } struct Traits { Kind kind; uint8 advantage; uint8[7] traits; } function getMaxGEN0Players() external pure returns (uint16); function getTraits(uint16) external view returns (Traits memory); function ownerOf(uint256) external view returns (address owner); function transferFrom(address, address, uint256) external; function safeTransferFrom(address, address, uint256, bytes memory) external; } /* ███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗ ██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝ █████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗ ██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝ ██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface IFoxGame { function stakeTokens(address, uint16[] calldata) external; function randomFoxOwner(uint256) external view returns (address); function isValidSignature(address, bool, uint48, uint256, bytes memory) external view returns (bool); } // SPDX-License-Identifier: MIT 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // 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; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @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 _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @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 baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @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 || 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 _owners[tokenId] != address(0); } /** * @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 || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `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); _balances[to] += 1; _owners[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); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[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"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @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()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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` 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 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^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.8.0; import "../../utils/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.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.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.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; 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"); (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); } } } } // 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; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^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); }
Head Fur Eyes
seed >>= 16; t.traits[1] = _selectTrait(uint16(seed & 0xFFFF), 1 + offset);
2,514,985
[ 1, 1414, 282, 478, 295, 377, 512, 9707, 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, 5009, 23359, 2872, 31, 268, 18, 2033, 1282, 63, 21, 65, 273, 389, 4025, 15525, 12, 11890, 2313, 12, 12407, 473, 374, 21718, 3631, 404, 397, 1384, 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 ]
./full_match/56/0x43a0C5EB1763A211Aa3c05849A617f2eE0452767/sources/project_/contracts/pokedx-token.sol
* @dev Calculates and returns the amount of tokens corresponding to the given reflected amount./
function tokenFromReflection(uint256 rAmount) internal view returns (uint256) { require( rAmount <= _reflectedSupply, "Amount must be less than total reflections" ); uint256 currentRate = _getCurrentRate(); return rAmount / currentRate; }
3,235,607
[ 1, 10587, 471, 1135, 326, 3844, 434, 2430, 4656, 358, 326, 864, 21591, 3844, 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, 565, 445, 1147, 1265, 9801, 12, 11890, 5034, 436, 6275, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 436, 6275, 1648, 389, 1734, 1582, 329, 3088, 1283, 16, 203, 5411, 315, 6275, 1297, 506, 5242, 2353, 2078, 5463, 87, 6, 203, 3639, 11272, 203, 3639, 2254, 5034, 783, 4727, 273, 389, 588, 3935, 4727, 5621, 203, 3639, 327, 436, 6275, 342, 783, 4727, 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 ]
// File: contracts/interfaces/IWeth.sol pragma solidity ^0.6.10; interface IWeth { function deposit() external payable; function withdraw(uint) external; function approve(address, uint) external returns (bool) ; function transfer(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol 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); } // File: contracts/interfaces/IDai.sol pragma solidity ^0.6.10; interface IDai is IERC20 { function nonces(address user) external view returns (uint256); function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; } // File: contracts/interfaces/IGemJoin.sol pragma solidity ^0.6.10; /// @dev Interface to interact with the `Join.sol` contract from MakerDAO using ERC20 interface IGemJoin { function rely(address usr) external; function deny(address usr) external; function cage() external; function join(address usr, uint WAD) external; function exit(address usr, uint WAD) external; } // File: contracts/interfaces/IDaiJoin.sol pragma solidity ^0.6.10; /// @dev Interface to interact with the `Join.sol` contract from MakerDAO using Dai interface IDaiJoin { function rely(address usr) external; function deny(address usr) external; function cage() external; function join(address usr, uint WAD) external; function exit(address usr, uint WAD) external; } // File: contracts/interfaces/IVat.sol pragma solidity ^0.6.10; /// @dev Interface to interact with the vat contract from MakerDAO /// Taken from https://github.com/makerdao/developerguides/blob/master/devtools/working-with-dsproxy/working-with-dsproxy.md interface IVat { // function can(address, address) external view returns (uint); function hope(address) external; function nope(address) external; function live() external view returns (uint); function ilks(bytes32) external view returns (uint, uint, uint, uint, uint); function urns(bytes32, address) external view returns (uint, uint); function gem(bytes32, address) external view returns (uint); // function dai(address) external view returns (uint); function frob(bytes32, address, address, address, int, int) external; function fork(bytes32, address, address, int, int) external; function move(address, address, uint) external; function flux(bytes32, address, address, uint) external; } // File: contracts/interfaces/IPot.sol pragma solidity ^0.6.10; /// @dev interface for the pot contract from MakerDao /// Taken from https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr.sol interface IPot { function chi() external view returns (uint256); function pie(address) external view returns (uint256); // Not a function, but a public variable. function rho() external returns (uint256); function drip() external returns (uint256); function join(uint256) external; function exit(uint256) external; } // File: contracts/interfaces/IDelegable.sol pragma solidity ^0.6.10; interface IDelegable { function addDelegate(address) external; function addDelegateBySignature(address, address, uint, uint8, bytes32, bytes32) external; } // File: contracts/interfaces/IERC2612.sol // Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/ pragma solidity ^0.6.0; /** * @dev Interface of the ERC2612 standard as defined in the EIP. * * Adds the {permit} method, which can be used to change one's * {IERC20-allowance} without having to send a transaction, by signing a * message. This allows users to spend tokens without having to hold Ether. * * See https://eips.ethereum.org/EIPS/eip-2612. */ interface IERC2612 { /** * @dev Sets `amount` 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: * * - `owner` cannot be the zero address. * - `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 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current ERC2612 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); } // File: contracts/interfaces/IFYDai.sol pragma solidity ^0.6.10; interface IFYDai is IERC20, IERC2612 { function isMature() external view returns(bool); function maturity() external view returns(uint); function chi0() external view returns(uint); function rate0() external view returns(uint); function chiGrowth() external view returns(uint); function rateGrowth() external view returns(uint); function mature() external; function unlocked() external view returns (uint); function mint(address, uint) external; function burn(address, uint) external; function flashMint(uint, bytes calldata) external; function redeem(address, address, uint256) external returns (uint256); // function transfer(address, uint) external returns (bool); // function transferFrom(address, address, uint) external returns (bool); // function approve(address, uint) external returns (bool); } // File: contracts/interfaces/IPool.sol pragma solidity ^0.6.10; interface IPool is IDelegable, IERC20, IERC2612 { function dai() external view returns(IERC20); function fyDai() external view returns(IFYDai); function getDaiReserves() external view returns(uint128); function getFYDaiReserves() external view returns(uint128); function sellDai(address from, address to, uint128 daiIn) external returns(uint128); function buyDai(address from, address to, uint128 daiOut) external returns(uint128); function sellFYDai(address from, address to, uint128 fyDaiIn) external returns(uint128); function buyFYDai(address from, address to, uint128 fyDaiOut) external returns(uint128); function sellDaiPreview(uint128 daiIn) external view returns(uint128); function buyDaiPreview(uint128 daiOut) external view returns(uint128); function sellFYDaiPreview(uint128 fyDaiIn) external view returns(uint128); function buyFYDaiPreview(uint128 fyDaiOut) external view returns(uint128); function mint(address from, address to, uint256 daiOffered) external returns (uint256); function burn(address from, address to, uint256 tokensBurned) external returns (uint256, uint256); } // File: contracts/interfaces/IChai.sol pragma solidity ^0.6.10; /// @dev interface for the chai contract /// Taken from https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr.sol interface IChai { function balanceOf(address account) external view returns (uint256); function transfer(address dst, uint wad) external returns (bool); function move(address src, address dst, uint wad) external returns (bool); function transferFrom(address src, address dst, uint wad) external returns (bool); function approve(address usr, uint wad) external returns (bool); function dai(address usr) external returns (uint wad); function join(address dst, uint wad) external; function exit(address src, uint wad) external; function draw(address src, uint wad) external; function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; function nonces(address account) external view returns (uint256); } // File: contracts/interfaces/ITreasury.sol pragma solidity ^0.6.10; interface ITreasury { function debt() external view returns(uint256); function savings() external view returns(uint256); function pushDai(address user, uint256 dai) external; function pullDai(address user, uint256 dai) external; function pushChai(address user, uint256 chai) external; function pullChai(address user, uint256 chai) external; function pushWeth(address to, uint256 weth) external; function pullWeth(address to, uint256 weth) external; function shutdown() external; function live() external view returns(bool); function vat() external view returns (IVat); function weth() external view returns (IWeth); function dai() external view returns (IERC20); function daiJoin() external view returns (IDaiJoin); function wethJoin() external view returns (IGemJoin); function pot() external view returns (IPot); function chai() external view returns (IChai); } // File: @openzeppelin/contracts/math/SafeMath.sol 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) { 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; } } // File: contracts/helpers/DecimalMath.sol pragma solidity ^0.6.10; /// @dev Implements simple fixed point math mul and div operations for 27 decimals. contract DecimalMath { using SafeMath for uint256; uint256 constant public UNIT = 1e27; /// @dev Multiplies x and y, assuming they are both fixed point with 27 digits. function muld(uint256 x, uint256 y) internal pure returns (uint256) { return x.mul(y).div(UNIT); } /// @dev Divides x between y, assuming they are both fixed point with 27 digits. function divd(uint256 x, uint256 y) internal pure returns (uint256) { return x.mul(UNIT).div(y); } /// @dev Multiplies x and y, rounding up to the closest representable number. /// Assumes x and y are both fixed point with `decimals` digits. function muldrup(uint256 x, uint256 y) internal pure returns (uint256) { uint256 z = x.mul(y); return z.mod(UNIT) == 0 ? z.div(UNIT) : z.div(UNIT).add(1); } /// @dev Divides x between y, rounding up to the closest representable number. /// Assumes x and y are both fixed point with `decimals` digits. function divdrup(uint256 x, uint256 y) internal pure returns (uint256) { uint256 z = x.mul(UNIT); return z.mod(y) == 0 ? z.div(y) : z.div(y).add(1); } } // File: contracts/peripheral/YieldProxy.sol pragma solidity ^0.6.10; interface ControllerLike is IDelegable { function treasury() external view returns (ITreasury); function series(uint256) external view returns (IFYDai); function seriesIterator(uint256) external view returns (uint256); function totalSeries() external view returns (uint256); function containsSeries(uint256) external view returns (bool); function posted(bytes32, address) external view returns (uint256); function locked(bytes32, address) external view returns (uint256); function debtFYDai(bytes32, uint256, address) external view returns (uint256); function debtDai(bytes32, uint256, address) external view returns (uint256); function totalDebtDai(bytes32, address) external view returns (uint256); function isCollateralized(bytes32, address) external view returns (bool); function inDai(bytes32, uint256, uint256) external view returns (uint256); function inFYDai(bytes32, uint256, uint256) external view returns (uint256); function erase(bytes32, address) external returns (uint256, uint256); function shutdown() external; function post(bytes32, address, address, uint256) external; function withdraw(bytes32, address, address, uint256) external; function borrow(bytes32, uint256, address, address, uint256) external; function repayFYDai(bytes32, uint256, address, address, uint256) external returns (uint256); function repayDai(bytes32, uint256, address, address, uint256) external returns (uint256); } library SafeCast { /// @dev Safe casting from uint256 to uint128 function toUint128(uint256 x) internal pure returns(uint128) { require( x <= type(uint128).max, "YieldProxy: Cast overflow" ); return uint128(x); } /// @dev Safe casting from uint256 to int256 function toInt256(uint256 x) internal pure returns(int256) { require( x <= uint256(type(int256).max), "YieldProxy: Cast overflow" ); return int256(x); } } contract YieldProxy is DecimalMath { using SafeCast for uint256; IVat public vat; IWeth public weth; IDai public dai; IGemJoin public wethJoin; IDaiJoin public daiJoin; IChai public chai; ControllerLike public controller; ITreasury public treasury; IPool[] public pools; mapping (address => bool) public poolsMap; bytes32 public constant CHAI = "CHAI"; bytes32 public constant WETH = "ETH-A"; bool constant public MTY = true; bool constant public YTM = false; constructor(address controller_, IPool[] memory _pools) public { controller = ControllerLike(controller_); treasury = controller.treasury(); weth = treasury.weth(); dai = IDai(address(treasury.dai())); chai = treasury.chai(); daiJoin = treasury.daiJoin(); wethJoin = treasury.wethJoin(); vat = treasury.vat(); // for repaying debt dai.approve(address(treasury), uint(-1)); // for posting to the controller chai.approve(address(treasury), uint(-1)); weth.approve(address(treasury), uint(-1)); // for converting DAI to CHAI dai.approve(address(chai), uint(-1)); vat.hope(address(daiJoin)); vat.hope(address(wethJoin)); dai.approve(address(daiJoin), uint(-1)); weth.approve(address(wethJoin), uint(-1)); weth.approve(address(treasury), uint(-1)); // allow all the pools to pull FYDai/dai from us for LPing for (uint i = 0 ; i < _pools.length; i++) { dai.approve(address(_pools[i]), uint(-1)); _pools[i].fyDai().approve(address(_pools[i]), uint(-1)); poolsMap[address(_pools[i])]= true; } pools = _pools; } /// @dev Unpack r, s and v from a `bytes` signature function unpack(bytes memory signature) private pure returns (bytes32 r, bytes32 s, uint8 v) { assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } } /// @dev Performs the initial onboarding of the user. It `permit`'s DAI to be used by the proxy, and adds the proxy as a delegate in the controller function onboard(address from, bytes memory daiSignature, bytes memory controllerSig) external { bytes32 r; bytes32 s; uint8 v; (r, s, v) = unpack(daiSignature); dai.permit(from, address(this), dai.nonces(from), uint(-1), true, v, r, s); (r, s, v) = unpack(controllerSig); controller.addDelegateBySignature(from, address(this), uint(-1), v, r, s); } /// @dev Given a pool and 3 signatures, it `permit`'s dai and fyDai for that pool and adds it as a delegate function authorizePool(IPool pool, address from, bytes memory daiSig, bytes memory fyDaiSig, bytes memory poolSig) public { onlyKnownPool(pool); bytes32 r; bytes32 s; uint8 v; (r, s, v) = unpack(daiSig); dai.permit(from, address(pool), dai.nonces(from), uint(-1), true, v, r, s); (r, s, v) = unpack(fyDaiSig); pool.fyDai().permit(from, address(this), uint(-1), uint(-1), v, r, s); (r, s, v) = unpack(poolSig); pool.addDelegateBySignature(from, address(this), uint(-1), v, r, s); } /// @dev The WETH9 contract will send ether to YieldProxy on `weth.withdraw` using this function. receive() external payable { } /// @dev Users use `post` in YieldProxy to post ETH to the Controller (amount = msg.value), which will be converted to Weth here. /// @param to Yield Vault to deposit collateral in. function post(address to) public payable { weth.deposit{ value: msg.value }(); controller.post(WETH, address(this), to, msg.value); } /// @dev Users wishing to withdraw their Weth as ETH from the Controller should use this function. /// Users must have called `controller.addDelegate(yieldProxy.address)` to authorize YieldProxy to act in their behalf. /// @param to Wallet to send Eth to. /// @param amount Amount of weth to move. function withdraw(address payable to, uint256 amount) public { controller.withdraw(WETH, msg.sender, address(this), amount); weth.withdraw(amount); to.transfer(amount); } /// @dev Mints liquidity with provided Dai by borrowing fyDai with some of the Dai. /// Caller must have approved the proxy using`controller.addDelegate(yieldProxy)` /// Caller must have approved the dai transfer with `dai.approve(daiUsed)` /// @param daiUsed amount of Dai to use to mint liquidity. /// @param maxFYDai maximum amount of fyDai to be borrowed to mint liquidity. /// @return The amount of liquidity tokens minted. function addLiquidity(IPool pool, uint256 daiUsed, uint256 maxFYDai) external returns (uint256) { onlyKnownPool(pool); IFYDai fyDai = pool.fyDai(); require(fyDai.isMature() != true, "YieldProxy: Only before maturity"); require(dai.transferFrom(msg.sender, address(this), daiUsed), "YieldProxy: Transfer Failed"); // calculate needed fyDai uint256 daiReserves = dai.balanceOf(address(pool)); uint256 fyDaiReserves = fyDai.balanceOf(address(pool)); uint256 daiToAdd = daiUsed.mul(daiReserves).div(fyDaiReserves.add(daiReserves)); uint256 daiToConvert = daiUsed.sub(daiToAdd); require( daiToConvert <= maxFYDai, "YieldProxy: maxFYDai exceeded" ); // 1 Dai == 1 fyDai // convert dai to chai and borrow needed fyDai chai.join(address(this), daiToConvert); // look at the balance of chai in dai to avoid rounding issues uint256 toBorrow = chai.dai(address(this)); controller.post(CHAI, address(this), msg.sender, chai.balanceOf(address(this))); controller.borrow(CHAI, fyDai.maturity(), msg.sender, address(this), toBorrow); // mint liquidity tokens return pool.mint(address(this), msg.sender, daiToAdd); } /// @dev Burns tokens and sells Dai proceedings for fyDai. Pays as much debt as possible, then sells back any remaining fyDai for Dai. Then returns all Dai, and if there is no debt in the Controller, all posted Chai. /// Caller must have approved the proxy using`controller.addDelegate(yieldProxy)` and `pool.addDelegate(yieldProxy)` /// Caller must have approved the liquidity burn with `pool.approve(poolTokens)` /// @param poolTokens amount of pool tokens to burn. /// @param minimumDaiPrice minimum fyDai/Dai price to be accepted when internally selling Dai. /// @param minimumFYDaiPrice minimum Dai/fyDai price to be accepted when internally selling fyDai. function removeLiquidityEarlyDaiPool(IPool pool, uint256 poolTokens, uint256 minimumDaiPrice, uint256 minimumFYDaiPrice) external { onlyKnownPool(pool); IFYDai fyDai = pool.fyDai(); uint256 maturity = fyDai.maturity(); (uint256 daiObtained, uint256 fyDaiObtained) = pool.burn(msg.sender, address(this), poolTokens); // Exchange Dai for fyDai to pay as much debt as possible uint256 fyDaiBought = pool.sellDai(address(this), address(this), daiObtained.toUint128()); require( fyDaiBought >= muld(daiObtained, minimumDaiPrice), "YieldProxy: minimumDaiPrice not reached" ); fyDaiObtained = fyDaiObtained.add(fyDaiBought); uint256 fyDaiUsed; if (fyDaiObtained > 0 && controller.debtFYDai(CHAI, maturity, msg.sender) > 0) { fyDaiUsed = controller.repayFYDai(CHAI, maturity, address(this), msg.sender, fyDaiObtained); } uint256 fyDaiRemaining = fyDaiObtained.sub(fyDaiUsed); if (fyDaiRemaining > 0) {// There is fyDai left, so exchange it for Dai to withdraw only Dai and Chai require( pool.sellFYDai(address(this), address(this), uint128(fyDaiRemaining)) >= muld(fyDaiRemaining, minimumFYDaiPrice), "YieldProxy: minimumFYDaiPrice not reached" ); } withdrawAssets(fyDai); } /// @dev Burns tokens and repays debt with proceedings. Sells any excess fyDai for Dai, then returns all Dai, and if there is no debt in the Controller, all posted Chai. /// Caller must have approved the proxy using`controller.addDelegate(yieldProxy)` and `pool.addDelegate(yieldProxy)` /// Caller must have approved the liquidity burn with `pool.approve(poolTokens)` /// @param poolTokens amount of pool tokens to burn. /// @param minimumFYDaiPrice minimum Dai/fyDai price to be accepted when internally selling fyDai. function removeLiquidityEarlyDaiFixed(IPool pool, uint256 poolTokens, uint256 minimumFYDaiPrice) external { onlyKnownPool(pool); IFYDai fyDai = pool.fyDai(); uint256 maturity = fyDai.maturity(); (uint256 daiObtained, uint256 fyDaiObtained) = pool.burn(msg.sender, address(this), poolTokens); uint256 fyDaiUsed; if (fyDaiObtained > 0 && controller.debtFYDai(CHAI, maturity, msg.sender) > 0) { fyDaiUsed = controller.repayFYDai(CHAI, maturity, address(this), msg.sender, fyDaiObtained); } uint256 fyDaiRemaining = fyDaiObtained.sub(fyDaiUsed); if (fyDaiRemaining == 0) { // We used all the fyDai, so probably there is debt left, so pay with Dai if (daiObtained > 0 && controller.debtFYDai(CHAI, maturity, msg.sender) > 0) { controller.repayDai(CHAI, maturity, address(this), msg.sender, daiObtained); } } else { // Exchange remaining fyDai for Dai to withdraw only Dai and Chai require( pool.sellFYDai(address(this), address(this), uint128(fyDaiRemaining)) >= muld(fyDaiRemaining, minimumFYDaiPrice), "YieldProxy: minimumFYDaiPrice not reached" ); } withdrawAssets(fyDai); } /// @dev Burns tokens and repays fyDai debt after Maturity. /// Caller must have approved the proxy using`controller.addDelegate(yieldProxy)` /// Caller must have approved the liquidity burn with `pool.approve(poolTokens)` /// @param poolTokens amount of pool tokens to burn. function removeLiquidityMature(IPool pool, uint256 poolTokens) external { onlyKnownPool(pool); IFYDai fyDai = pool.fyDai(); uint256 maturity = fyDai.maturity(); (uint256 daiObtained, uint256 fyDaiObtained) = pool.burn(msg.sender, address(this), poolTokens); if (fyDaiObtained > 0) { daiObtained = daiObtained.add(fyDai.redeem(address(this), address(this), fyDaiObtained)); } // Repay debt if (daiObtained > 0 && controller.debtFYDai(CHAI, maturity, msg.sender) > 0) { controller.repayDai(CHAI, maturity, address(this), msg.sender, daiObtained); } withdrawAssets(fyDai); } /// @dev Return to caller all posted chai if there is no debt, converted to dai, plus any dai remaining in the contract. function withdrawAssets(IFYDai fyDai) internal { if (controller.debtFYDai(CHAI, fyDai.maturity(), msg.sender) == 0) { uint256 posted = controller.posted(CHAI, msg.sender); uint256 locked = controller.locked(CHAI, msg.sender); require (posted >= locked, "YieldProxy: Undercollateralized"); controller.withdraw(CHAI, msg.sender, address(this), posted - locked); chai.exit(address(this), chai.balanceOf(address(this))); } require(dai.transfer(msg.sender, dai.balanceOf(address(this))), "YieldProxy: Dai Transfer Failed"); } /// @dev Borrow fyDai from Controller and sell it immediately for Dai, for a maximum fyDai debt. /// Must have approved the operator with `controller.addDelegate(yieldProxy.address)`. /// @param collateral Valid collateral type. /// @param maturity Maturity of an added series /// @param to Wallet to send the resulting Dai to. /// @param maximumFYDai Maximum amount of FYDai to borrow. /// @param daiToBorrow Exact amount of Dai that should be obtained. function borrowDaiForMaximumFYDai( IPool pool, bytes32 collateral, uint256 maturity, address to, uint256 maximumFYDai, uint256 daiToBorrow ) public returns (uint256) { onlyKnownPool(pool); uint256 fyDaiToBorrow = pool.buyDaiPreview(daiToBorrow.toUint128()); require (fyDaiToBorrow <= maximumFYDai, "YieldProxy: Too much fyDai required"); // The collateral for this borrow needs to have been posted beforehand controller.borrow(collateral, maturity, msg.sender, address(this), fyDaiToBorrow); pool.buyDai(address(this), to, daiToBorrow.toUint128()); return fyDaiToBorrow; } /// @dev Borrow fyDai from Controller and sell it immediately for Dai, if a minimum amount of Dai can be obtained such. /// Must have approved the operator with `controller.addDelegate(yieldProxy.address)`. /// @param collateral Valid collateral type. /// @param maturity Maturity of an added series /// @param to Wallet to sent the resulting Dai to. /// @param fyDaiToBorrow Amount of fyDai to borrow. /// @param minimumDaiToBorrow Minimum amount of Dai that should be borrowed. function borrowMinimumDaiForFYDai( IPool pool, bytes32 collateral, uint256 maturity, address to, uint256 fyDaiToBorrow, uint256 minimumDaiToBorrow ) public returns (uint256) { onlyKnownPool(pool); // The collateral for this borrow needs to have been posted beforehand controller.borrow(collateral, maturity, msg.sender, address(this), fyDaiToBorrow); uint256 boughtDai = pool.sellFYDai(address(this), to, fyDaiToBorrow.toUint128()); require (boughtDai >= minimumDaiToBorrow, "YieldProxy: Not enough Dai obtained"); return boughtDai; } /// @dev Repay an amount of fyDai debt in Controller using Dai exchanged for fyDai at pool rates, up to a maximum amount of Dai spent. /// Must have approved the operator with `pool.addDelegate(yieldProxy.address)`. /// If `fyDaiRepayment` exceeds the existing debt, only the necessary fyDai will be used. /// @param collateral Valid collateral type. /// @param maturity Maturity of an added series /// @param to Yield Vault to repay fyDai debt for. /// @param fyDaiRepayment Amount of fyDai debt to repay. /// @param maximumRepaymentInDai Maximum amount of Dai that should be spent on the repayment. function repayFYDaiDebtForMaximumDai( IPool pool, bytes32 collateral, uint256 maturity, address to, uint256 fyDaiRepayment, uint256 maximumRepaymentInDai ) public returns (uint256) { onlyKnownPool(pool); uint256 fyDaiDebt = controller.debtFYDai(collateral, maturity, to); uint256 fyDaiToUse = fyDaiDebt < fyDaiRepayment ? fyDaiDebt : fyDaiRepayment; // Use no more fyDai than debt uint256 repaymentInDai = pool.buyFYDai(msg.sender, address(this), fyDaiToUse.toUint128()); require (repaymentInDai <= maximumRepaymentInDai, "YieldProxy: Too much Dai required"); controller.repayFYDai(collateral, maturity, address(this), to, fyDaiToUse); return repaymentInDai; } /// @dev Repay an amount of fyDai debt in Controller using a given amount of Dai exchanged for fyDai at pool rates, with a minimum of fyDai debt required to be paid. /// Must have approved the operator with `pool.addDelegate(yieldProxy.address)`. /// If `repaymentInDai` exceeds the existing debt, only the necessary Dai will be used. /// @param collateral Valid collateral type. /// @param maturity Maturity of an added series /// @param to Yield Vault to repay fyDai debt for. /// @param minimumFYDaiRepayment Minimum amount of fyDai debt to repay. /// @param repaymentInDai Exact amount of Dai that should be spent on the repayment. function repayMinimumFYDaiDebtForDai( IPool pool, bytes32 collateral, uint256 maturity, address to, uint256 minimumFYDaiRepayment, uint256 repaymentInDai ) public returns (uint256) { onlyKnownPool(pool); uint256 fyDaiRepayment = pool.sellDaiPreview(repaymentInDai.toUint128()); uint256 fyDaiDebt = controller.debtFYDai(collateral, maturity, to); if(fyDaiRepayment <= fyDaiDebt) { // Sell no more Dai than needed to cancel all the debt pool.sellDai(msg.sender, address(this), repaymentInDai.toUint128()); } else { // If we have too much Dai, then don't sell it all and buy the exact amount of fyDai needed instead. pool.buyFYDai(msg.sender, address(this), fyDaiDebt.toUint128()); fyDaiRepayment = fyDaiDebt; } require (fyDaiRepayment >= minimumFYDaiRepayment, "YieldProxy: Not enough fyDai debt repaid"); controller.repayFYDai(collateral, maturity, address(this), to, fyDaiRepayment); return fyDaiRepayment; } /// @dev Sell Dai for fyDai /// @param to Wallet receiving the fyDai being bought /// @param daiIn Amount of dai being sold /// @param minFYDaiOut Minimum amount of fyDai being bought function sellDai(IPool pool, address to, uint128 daiIn, uint128 minFYDaiOut) external returns(uint256) { onlyKnownPool(pool); uint256 fyDaiOut = pool.sellDai(msg.sender, to, daiIn); require( fyDaiOut >= minFYDaiOut, "YieldProxy: Limit not reached" ); return fyDaiOut; } /// @dev Buy Dai for fyDai /// @param to Wallet receiving the dai being bought /// @param daiOut Amount of dai being bought /// @param maxFYDaiIn Maximum amount of fyDai being sold function buyDai(IPool pool, address to, uint128 daiOut, uint128 maxFYDaiIn) public returns(uint256) { onlyKnownPool(pool); uint256 fyDaiIn = pool.buyDai(msg.sender, to, daiOut); require( maxFYDaiIn >= fyDaiIn, "YieldProxy: Limit exceeded" ); return fyDaiIn; } /// @dev Buy Dai for fyDai and permits infinite fyDai to the pool /// @param to Wallet receiving the dai being bought /// @param daiOut Amount of dai being bought /// @param maxFYDaiIn Maximum amount of fyDai being sold /// @param signature The `permit` call's signature function buyDaiWithSignature(IPool pool, address to, uint128 daiOut, uint128 maxFYDaiIn, bytes memory signature) external returns(uint256) { onlyKnownPool(pool); (bytes32 r, bytes32 s, uint8 v) = unpack(signature); pool.fyDai().permit(msg.sender, address(pool), uint(-1), uint(-1), v, r, s); return buyDai(pool, to, daiOut, maxFYDaiIn); } /// @dev Sell fyDai for Dai /// @param to Wallet receiving the dai being bought /// @param fyDaiIn Amount of fyDai being sold /// @param minDaiOut Minimum amount of dai being bought function sellFYDai(IPool pool, address to, uint128 fyDaiIn, uint128 minDaiOut) public returns(uint256) { onlyKnownPool(pool); uint256 daiOut = pool.sellFYDai(msg.sender, to, fyDaiIn); require( daiOut >= minDaiOut, "YieldProxy: Limit not reached" ); return daiOut; } /// @dev Sell fyDai for Dai and permits infinite Dai to the pool /// @param to Wallet receiving the dai being bought /// @param fyDaiIn Amount of fyDai being sold /// @param minDaiOut Minimum amount of dai being bought /// @param signature The `permit` call's signature function sellFYDaiWithSignature(IPool pool, address to, uint128 fyDaiIn, uint128 minDaiOut, bytes memory signature) external returns(uint256) { onlyKnownPool(pool); (bytes32 r, bytes32 s, uint8 v) = unpack(signature); pool.fyDai().permit(msg.sender, address(pool), uint(-1), uint(-1), v, r, s); return sellFYDai(pool, to, fyDaiIn, minDaiOut); } /// @dev Buy fyDai for dai /// @param to Wallet receiving the fyDai being bought /// @param fyDaiOut Amount of fyDai being bought /// @param maxDaiIn Maximum amount of dai being sold function buyFYDai(IPool pool, address to, uint128 fyDaiOut, uint128 maxDaiIn) external returns(uint256) { onlyKnownPool(pool); uint256 daiIn = pool.buyFYDai(msg.sender, to, fyDaiOut); require( maxDaiIn >= daiIn, "YieldProxy: Limit exceeded" ); return daiIn; } /// @dev Burns Dai from caller to repay debt in a Yield Vault. /// User debt is decreased for the given collateral and fyDai series, in Yield vault `to`. /// The amount of debt repaid changes according to series maturity and MakerDAO rate and chi, depending on collateral type. /// `A signature is provided as a parameter to this function, so that `dai.approve()` doesn't need to be called. /// @param collateral Valid collateral type. /// @param maturity Maturity of an added series /// @param to Yield vault to repay debt for. /// @param daiAmount Amount of Dai to use for debt repayment. /// @param signature The `permit` call's signature function repayDaiWithSignature(bytes32 collateral, uint256 maturity, address to, uint256 daiAmount, bytes memory signature) external returns(uint256) { (bytes32 r, bytes32 s, uint8 v) = unpack(signature); dai.permit(msg.sender, address(treasury), dai.nonces(msg.sender), uint(-1), true, v, r, s); controller.repayDai(collateral, maturity, msg.sender, to, daiAmount); } function onlyKnownPool(IPool pool) private view { require(poolsMap[address(pool)], "YieldProxy: Unknown pool"); } }
Use no more fyDai than debt
uint256 fyDaiToUse = fyDaiDebt < fyDaiRepayment ? fyDaiDebt : fyDaiRepayment;
2,147,636
[ 1, 3727, 1158, 1898, 28356, 40, 10658, 2353, 18202, 88, 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, 2254, 5034, 28356, 40, 10658, 18762, 273, 28356, 40, 10658, 758, 23602, 411, 28356, 40, 10658, 426, 9261, 692, 28356, 40, 10658, 758, 23602, 294, 28356, 40, 10658, 426, 9261, 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 ]
./full_match/80001/0xA6CA224CDb096DA247380Bd3D242f5296b762223/sources/project_/contracts/Egg.sol
Returns only items a user has listed */
function fetchItemsListed(address fetchAddress) public view returns (MarketItem[] memory) { uint itemCount = 0; uint currentIndex = 0; for (uint256 i = basePremiumTokenID; i <= currentPremimumTokenID; i++) { if (_listings[i].seller == fetchAddress) { itemCount += 1; } } for (uint256 i = baseFreeTokenID; i <= currentFreeTokenID; i++) { if (_listings[i].seller == fetchAddress) { itemCount += 1; } } MarketItem[] memory items = new MarketItem[](itemCount); for (uint i = basePremiumTokenID; i <= currentPremimumTokenID; i++) { if (_listings[i].seller == msg.sender) { MarketItem storage currentItem = _listings[i]; items[currentIndex] = currentItem; currentIndex += 1; } } for (uint i = baseFreeTokenID; i <= currentFreeTokenID; i++) { if (_listings[i].seller == msg.sender) { MarketItem storage currentItem = _listings[i]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; }
9,478,126
[ 1, 1356, 1338, 1516, 279, 729, 711, 12889, 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, 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, 565, 445, 2158, 3126, 682, 329, 12, 2867, 2158, 1887, 13, 1071, 1476, 1135, 261, 3882, 278, 1180, 8526, 3778, 13, 288, 203, 1377, 2254, 761, 1380, 273, 374, 31, 203, 1377, 2254, 17032, 273, 374, 31, 203, 203, 1377, 364, 261, 11890, 5034, 277, 273, 1026, 23890, 5077, 1345, 734, 31, 277, 1648, 783, 23890, 2422, 1345, 734, 31, 277, 27245, 288, 203, 3639, 309, 261, 67, 1098, 899, 63, 77, 8009, 1786, 749, 422, 2158, 1887, 13, 288, 203, 1850, 761, 1380, 1011, 404, 31, 203, 3639, 289, 203, 1377, 289, 203, 203, 1377, 364, 261, 11890, 5034, 277, 273, 1026, 9194, 1345, 734, 31, 277, 1648, 783, 9194, 1345, 734, 31, 277, 27245, 288, 203, 3639, 309, 261, 67, 1098, 899, 63, 77, 8009, 1786, 749, 422, 2158, 1887, 13, 288, 203, 1850, 761, 1380, 1011, 404, 31, 203, 3639, 289, 203, 1377, 289, 203, 203, 203, 1377, 6622, 278, 1180, 8526, 3778, 1516, 273, 394, 6622, 278, 1180, 8526, 12, 1726, 1380, 1769, 203, 1377, 364, 261, 11890, 277, 273, 1026, 23890, 5077, 1345, 734, 31, 277, 1648, 783, 23890, 2422, 1345, 734, 31, 277, 27245, 288, 203, 3639, 309, 261, 67, 1098, 899, 63, 77, 8009, 1786, 749, 422, 1234, 18, 15330, 13, 288, 203, 1850, 6622, 278, 1180, 2502, 27471, 273, 389, 1098, 899, 63, 77, 15533, 203, 1850, 1516, 63, 2972, 1016, 65, 273, 27471, 31, 203, 1850, 17032, 1011, 404, 31, 203, 3639, 289, 203, 1377, 289, 203, 1377, 364, 261, 11890, 277, 273, 1026, 9194, 2 ]
pragma solidity ^0.4.4; 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 BrainLegitCoin 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 = 'BL1.0'; uint256 public unitsOneEthCanBuybefore; // How many units of coin can be bought by 1 ETH during ICO? uint256 public unitsOneEthCanBuyafter; // How many units of coin can be bought by 1 ETH after ICO? 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? uint public deadline; uint256 public ecosystemtoken; uint public preIcoStart; uint public preIcoEnds; uint public Icostart; uint public Icoends; // Token Distribution // ============================= uint256 public maxTokens = 1000000000000000000000000000; // There will be total 1Billion LegitCoin Tokens uint256 public tokensForplutonics = 200000000000000000000000000; // 200million legitt coin for utility ecosystem uint256 public tokensForfortis = 150000000000000000000000000; //150Million Legitt coin for fortis projects uint256 public tokensFortorch = 10000000000000000000000000; // 100 million legitt coin for Torch uint256 public tokensForEcosystem = 10000000000000000000000000; // 100 million legittcoin for ecosystem uint256 public totalTokensForSale = 450000000000000000000000000; // 450Million LGT will be sold in Crowdsale // This is a constructor function // which means the following function name has to match the contract name declared above function BrainLegitCoin() { balances[msg.sender] = maxTokens; // 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 = maxTokens; // Update total supply (1000 for example) (CHANGE THIS) name = "LegittCoin"; // Set the name for display purposes (CHANGE THIS) decimals = 18; // Amount of decimals for display purposes (CHANGE THIS) symbol = "LGT"; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuybefore = 30000; // Set the price of your token for the ICO (CHANGE THIS) unitsOneEthCanBuyafter=15000; fundsWallet = msg.sender; preIcoStart=now + 10080 * 1 minutes; preIcoEnds = now + 25920 * 1 minutes; Icostart = now + 27360 * 1 minutes; Icoends= now + 72000 * 1 minutes; } function() payable{ if(now > Icoends) throw; if ((balances[fundsWallet] > 300000000000000000000000000) && ((now >= preIcoStart) && (now <= preIcoEnds))){ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuybefore; 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); } else if( (now >= Icostart) && (now <= Icoends)){ totalEthInWei = totalEthInWei + msg.value; uint256 amountb = msg.value * unitsOneEthCanBuyafter; require(tokensForEcosystem >= amountb); tokensForEcosystem = tokensForEcosystem - amountb; balances[msg.sender] = balances[msg.sender] + amountb; Transfer(fundsWallet, msg.sender, amountb); // 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; } }
Set the name for display purposes (CHANGE THIS)
name = "LegittCoin";
5,921,886
[ 1, 694, 326, 508, 364, 2562, 13694, 261, 14473, 20676, 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 ]
[ 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, 3639, 508, 273, 315, 8329, 305, 88, 27055, 14432, 4766, 565, 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 ]
./full_match/80001/0x1fd90e5557cD183f835F06d8744b49DddDf7a43a/sources/contracts/Participate.sol
* @dev Initialize function to make the contract upgradable/
{ __Ownable_init(); __ERC1155PresetMinterPauser_init(uri); _metadata_uri = contractUri; _royaltyRecipient = payable(msg.sender); }
9,490,299
[ 1, 7520, 445, 358, 1221, 326, 6835, 731, 9974, 429, 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, 288, 203, 3639, 1001, 5460, 429, 67, 2738, 5621, 203, 3639, 1001, 654, 39, 2499, 2539, 18385, 49, 2761, 16507, 1355, 67, 2738, 12, 1650, 1769, 203, 3639, 389, 4165, 67, 1650, 273, 6835, 3006, 31, 203, 203, 3639, 389, 3800, 15006, 18241, 273, 8843, 429, 12, 3576, 18, 15330, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {ERC20} from "../../lib/ERC20.sol"; import {LLTH} from "../../lib/LLTH.sol"; import {Create2} from "../../lib/Create2.sol"; import {FxBaseRootTunnel} from "../../tunnel/FxBaseRootTunnel.sol"; import {SafeERC20, IERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title FxERC20RootTunnel */ contract FxERC20RootTunnel is FxBaseRootTunnel, Create2 { using SafeERC20 for IERC20; using SafeMath for uint256; // maybe DEPOSIT and MAP_TOKEN can be reduced to bytes4 bytes32 public constant DEPOSIT = keccak256("DEPOSIT"); bytes32 public constant MAP_TOKEN = keccak256("MAP_TOKEN"); event TokenMappedERC20( address indexed rootToken, address indexed childToken ); event FxWithdrawERC20( address indexed rootToken, address indexed childToken, address indexed userAddress, uint256 amount ); event FxDepositERC20( address indexed rootToken, address indexed depositor, address indexed userAddress, uint256 amount ); mapping(address => address) public rootToChildTokens; bytes32 public childTokenTemplateCodeHash; constructor( address _checkpointManager, address _fxRoot, address _fxERC20Token ) FxBaseRootTunnel(_checkpointManager, _fxRoot) { // compute child token template code hash childTokenTemplateCodeHash = keccak256( minimalProxyCreationCode(_fxERC20Token) ); } /** * @notice Map a token to enable its movement via the PoS Portal, callable only by mappers * @param rootToken address of token on root chain */ function mapToken(address rootToken) public { // check if token is already mapped require( rootToChildTokens[rootToken] == address(0x0), "FxERC20RootTunnel: ALREADY_MAPPED" ); // name, symbol and decimals ERC20 rootTokenContract = ERC20(rootToken); string memory name = rootTokenContract.name(); string memory symbol = rootTokenContract.symbol(); uint8 decimals = rootTokenContract.decimals(); // MAP_TOKEN, encode(rootToken, name, symbol, decimals) bytes memory message = abi.encode( MAP_TOKEN, abi.encode(rootToken, name, symbol, decimals) ); _sendMessageToChild(message); // compute child token address before deployment using create2 bytes32 salt = keccak256(abi.encodePacked(rootToken)); address childToken = computedCreate2Address( salt, childTokenTemplateCodeHash, fxChildTunnel ); // add into mapped tokens rootToChildTokens[rootToken] = childToken; emit TokenMappedERC20(rootToken, childToken); } function deposit( address rootToken, address user, uint256 amount, bytes memory data ) public { // map token if not mapped if (rootToChildTokens[rootToken] == address(0x0)) { mapToken(rootToken); } // transfer from depositor to this contract IERC20(rootToken).safeTransferFrom( msg.sender, // depositor address(this), // manager contract amount ); // DEPOSIT, encode(rootToken, depositor, user, amount, extra data) bytes memory message = abi.encode( DEPOSIT, abi.encode(rootToken, msg.sender, user, amount, data) ); _sendMessageToChild(message); emit FxDepositERC20(rootToken, msg.sender, user, amount); } // exit processor function _processMessageFromChild(bytes memory data) internal override { ( address rootToken, address childToken, address to, uint256 amount ) = abi.decode(data, (address, address, address, uint256)); // validate mapping for root to child require( rootToChildTokens[rootToken] == childToken, "FxERC20RootTunnel: INVALID_MAPPING_ON_EXIT" ); // check if current balance for token is less than amount, // mint remaining amount for this address LLTH tokenObj = LLTH(rootToken); uint256 balanceOf = tokenObj.balanceOf(address(this)); if (balanceOf < amount) { tokenObj.mint(address(this), amount.sub(balanceOf)); } //approve token transfer tokenObj.approve(address(this), amount); // transfer from tokens to IERC20(rootToken).safeTransfer(to, amount); emit FxWithdrawERC20(rootToken, childToken, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC20 } from './IERC20.sol'; import { SafeMath } from './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 {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(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 virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupMetaData(string memory name_, string memory symbol_, uint8 decimals_) internal virtual { _name = name_; _symbol = symbol_; _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract LLTH is ERC20, Ownable { mapping(address => bool) public managers; constructor() ERC20("Lilith", "LLTH") { managers[owner()] = true; _mint(owner(), 1000000 * (10**18)); } /**@dev Allows execution by managers only */ modifier managerOnly() { require(managers[msg.sender]); _; } /**@dev Be careful setting new manager, recheck the address */ function setManager(address manager, bool state) external onlyOwner { managers[manager] = state; } /**@dev External mint for l1-l2 affairs */ function mint(address user, uint256 amount) external managerOnly { _mint(user, amount); } /**@dev External burn for l1-l2 affairs */ function burn(address user, uint256 amount) public managerOnly { _burn(user, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Create2 adds common methods for minimal proxy with create2 abstract contract Create2 { // creates clone using minimal proxy function createClone(bytes32 _salt, address _target) internal returns (address _result) { bytes20 _targetBytes = bytes20(_target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), _targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) _result := create2(0, clone, 0x37, _salt) } require(_result != address(0), "Create2: Failed on minimal deploy"); } // get minimal proxy creation code function minimalProxyCreationCode(address logic) internal pure returns (bytes memory) { bytes10 creation = 0x3d602d80600a3d3981f3; bytes10 prefix = 0x363d3d373d3d3d363d73; bytes20 targetBytes = bytes20(logic); bytes15 suffix = 0x5af43d82803e903d91602b57fd5bf3; return abi.encodePacked(creation, prefix, targetBytes, suffix); } // get computed create2 address function computedCreate2Address(bytes32 salt, bytes32 bytecodeHash, address deployer) public pure returns (address) { bytes32 _data = keccak256( abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash) ); return address(uint160(uint256(_data))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {RLPReader} from "../lib/RLPReader.sol"; import {MerklePatriciaProof} from "../lib/MerklePatriciaProof.sol"; import {Merkle} from "../lib/Merkle.sol"; import "../lib/ExitPayloadReader.sol"; interface IFxStateSender { function sendMessageToChild(address _receiver, bytes calldata _data) external; } contract ICheckpointManager { struct HeaderBlock { bytes32 root; uint256 start; uint256 end; uint256 createdAt; address proposer; } /** * @notice mapping of checkpoint header numbers to block details * @dev These checkpoints are submited by plasma contracts */ mapping(uint256 => HeaderBlock) public headerBlocks; } abstract contract FxBaseRootTunnel { using RLPReader for RLPReader.RLPItem; using Merkle for bytes32; using ExitPayloadReader for bytes; using ExitPayloadReader for ExitPayloadReader.ExitPayload; using ExitPayloadReader for ExitPayloadReader.Log; using ExitPayloadReader for ExitPayloadReader.LogTopics; using ExitPayloadReader for ExitPayloadReader.Receipt; // keccak256(MessageSent(bytes)) bytes32 public constant SEND_MESSAGE_EVENT_SIG = 0x8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036; // state sender contract IFxStateSender public fxRoot; // root chain manager ICheckpointManager public checkpointManager; // child tunnel contract which receives and sends messages address public fxChildTunnel; // storage to avoid duplicate exits mapping(bytes32 => bool) public processedExits; constructor(address _checkpointManager, address _fxRoot) { checkpointManager = ICheckpointManager(_checkpointManager); fxRoot = IFxStateSender(_fxRoot); } // set fxChildTunnel if not set already function setFxChildTunnel(address _fxChildTunnel) public { require(fxChildTunnel == address(0x0), "FxBaseRootTunnel: CHILD_TUNNEL_ALREADY_SET"); fxChildTunnel = _fxChildTunnel; } /** * @notice Send bytes message to Child Tunnel * @param message bytes message that will be sent to Child Tunnel * some message examples - * abi.encode(tokenId); * abi.encode(tokenId, tokenMetadata); * abi.encode(messageType, messageData); */ function _sendMessageToChild(bytes memory message) internal { fxRoot.sendMessageToChild(fxChildTunnel, message); } function _validateAndExtractMessage(bytes memory inputData) internal returns (bytes memory) { ExitPayloadReader.ExitPayload memory payload = inputData.toExitPayload(); bytes memory branchMaskBytes = payload.getBranchMaskAsBytes(); uint256 blockNumber = payload.getBlockNumber(); // checking if exit has already been processed // unique exit is identified using hash of (blockNumber, branchMask, receiptLogIndex) bytes32 exitHash = keccak256( abi.encodePacked( blockNumber, // first 2 nibbles are dropped while generating nibble array // this allows branch masks that are valid but bypass exitHash check (changing first 2 nibbles only) // so converting to nibble array and then hashing it MerklePatriciaProof._getNibbleArray(branchMaskBytes), payload.getReceiptLogIndex() ) ); require( processedExits[exitHash] == false, "FxRootTunnel: EXIT_ALREADY_PROCESSED" ); processedExits[exitHash] = true; ExitPayloadReader.Receipt memory receipt = payload.getReceipt(); ExitPayloadReader.Log memory log = receipt.getLog(); // check child tunnel require(fxChildTunnel == log.getEmitter(), "FxRootTunnel: INVALID_FX_CHILD_TUNNEL"); bytes32 receiptRoot = payload.getReceiptRoot(); // verify receipt inclusion require( MerklePatriciaProof.verify( receipt.toBytes(), branchMaskBytes, payload.getReceiptProof(), receiptRoot ), "FxRootTunnel: INVALID_RECEIPT_PROOF" ); // verify checkpoint inclusion _checkBlockMembershipInCheckpoint( blockNumber, payload.getBlockTime(), payload.getTxRoot(), receiptRoot, payload.getHeaderNumber(), payload.getBlockProof() ); ExitPayloadReader.LogTopics memory topics = log.getTopics(); require( bytes32(topics.getField(0).toUint()) == SEND_MESSAGE_EVENT_SIG, // topic0 is event sig "FxRootTunnel: INVALID_SIGNATURE" ); // received message data (bytes memory message) = abi.decode(log.getData(), (bytes)); // event decodes params again, so decoding bytes to get message return message; } function _checkBlockMembershipInCheckpoint( uint256 blockNumber, uint256 blockTime, bytes32 txRoot, bytes32 receiptRoot, uint256 headerNumber, bytes memory blockProof ) private view returns (uint256) { ( bytes32 headerRoot, uint256 startBlock, , uint256 createdAt, ) = checkpointManager.headerBlocks(headerNumber); require( keccak256( abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot) ) .checkMembership( blockNumber-startBlock, headerRoot, blockProof ), "FxRootTunnel: INVALID_HEADER" ); return createdAt; } /** * @notice receive message from L2 to L1, validated by proof * @dev This function verifies if the transaction actually happened on child chain * * @param inputData RLP encoded data of the reference tx containing following list of fields * 0 - headerNumber - Checkpoint header block number containing the reference tx * 1 - blockProof - Proof that the block header (in the child chain) is a leaf in the submitted merkle root * 2 - blockNumber - Block number containing the reference tx on child chain * 3 - blockTime - Reference tx block time * 4 - txRoot - Transactions root of block * 5 - receiptRoot - Receipts root of block * 6 - receipt - Receipt of the reference transaction * 7 - receiptProof - Merkle proof of the reference receipt * 8 - branchMask - 32 bits denoting the path of receipt in merkle tree * 9 - receiptLogIndex - Log Index to read from the receipt */ function receiveMessage(bytes memory inputData) public virtual { bytes memory message = _validateAndExtractMessage(inputData); _processMessageFromChild(message); } /** * @notice Process message received from Child Tunnel * @dev function needs to be implemented to handle message as per requirement * This is called by onStateReceive function. * Since it is called via a system call, any event will not be emitted during its execution. * @param message bytes message that was sent from Child Tunnel */ function _processMessageFromChild(bytes memory message) virtual internal; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.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"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // 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 no longer needed starting with Solidity 0.8. 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; } } } // SPDX-License-Identifier: MIT 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 `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: MIT pragma solidity ^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, 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; } } // SPDX-License-Identifier: MIT pragma solidity ^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() { _setOwner(_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 { _setOwner(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"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.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: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - 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) { _approve(_msgSender(), spender, _allowances[_msgSender()][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) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), 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: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); 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); _afterTokenTransfer(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: * * - `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 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 {} } // SPDX-License-Identifier: MIT 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; } } // SPDX-License-Identifier: MIT 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 `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: MIT pragma solidity ^0.8.0; import "../IERC20.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); } /* * @author Hamdi Allam [email protected] * Please reach out with any questions or concerns */ pragma solidity ^0.8.0; library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint len; uint memPtr; } struct Iterator { RLPItem item; // Item that's being iterated over. uint nextPtr; // Position of the next item in the list. } /* * @dev Returns the next element in the iteration. Reverts if it has not next element. * @param self The iterator. * @return The next element in the iteration. */ function next(Iterator memory self) internal pure returns (RLPItem memory) { require(hasNext(self)); uint ptr = self.nextPtr; uint itemLength = _itemLength(ptr); self.nextPtr = ptr + itemLength; return RLPItem(itemLength, ptr); } /* * @dev Returns true if the iteration has more elements. * @param self The iterator. * @return true if the iteration has more elements. */ function hasNext(Iterator memory self) internal pure returns (bool) { RLPItem memory item = self.item; return self.nextPtr < item.memPtr + item.len; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { uint memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @dev Create an iterator. Reverts if item is not a list. * @param self The RLP item. * @return An 'Iterator' over the item. */ function iterator(RLPItem memory self) internal pure returns (Iterator memory) { require(isList(self)); uint ptr = self.memPtr + _payloadOffset(self.memPtr); return Iterator(self, ptr); } /* * @param item RLP encoded bytes */ function rlpLen(RLPItem memory item) internal pure returns (uint) { return item.len; } /* * @param item RLP encoded bytes */ function payloadLen(RLPItem memory item) internal pure returns (uint) { return item.len - _payloadOffset(item.memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item)); uint items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { if (item.len == 0) return false; uint8 byte0; uint memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /* * @dev A cheaper version of keccak256(toRlpBytes(item)) that avoids copying memory. * @return keccak256 hash of RLP encoded bytes. */ function rlpBytesKeccak256(RLPItem memory item) internal pure returns (bytes32) { uint256 ptr = item.memPtr; uint256 len = item.len; bytes32 result; assembly { result := keccak256(ptr, len) } return result; } function payloadLocation(RLPItem memory item) internal pure returns (uint, uint) { uint offset = _payloadOffset(item.memPtr); uint memPtr = item.memPtr + offset; uint len = item.len - offset; // data length return (memPtr, len); } /* * @dev A cheaper version of keccak256(toBytes(item)) that avoids copying memory. * @return keccak256 hash of the item payload. */ function payloadKeccak256(RLPItem memory item) internal pure returns (bytes32) { (uint memPtr, uint len) = payloadLocation(item); bytes32 result; assembly { result := keccak256(memPtr, len) } return result; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); if (result.length == 0) return result; uint ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } // any non-zero byte is considered true function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1); uint result; uint memPtr = item.memPtr; assembly { result := byte(0, mload(memPtr)) } return result == 0 ? false : true; } function toAddress(RLPItem memory item) internal pure returns (address) { // 1 byte for the length prefix require(item.len == 21); return address(uint160(toUint(item))); } function toUint(RLPItem memory item) internal pure returns (uint) { require(item.len > 0 && item.len <= 33); uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; uint result; uint memPtr = item.memPtr + offset; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint) { // one byte prefix require(item.len == 33); uint result; uint memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { require(item.len > 0); uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; // data length bytes memory result = new bytes(len); uint destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint) { if (item.len == 0) return 0; uint count = 0; uint currPtr = item.memPtr + _payloadOffset(item.memPtr); uint endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item count++; } return count; } // @return entire rlp item byte length function _itemLength(uint memPtr) private pure returns (uint) { uint itemLen; uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint memPtr) private pure returns (uint) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy(uint src, uint dest, uint len) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } if (len == 0) return; // left over bytes. Mask is used to remove unwanted bytes from the word uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {RLPReader} from "./RLPReader.sol"; library MerklePatriciaProof { /* * @dev Verifies a merkle patricia proof. * @param value The terminating value in the trie. * @param encodedPath The path in the trie leading to value. * @param rlpParentNodes The rlp encoded stack of nodes. * @param root The root hash of the trie. * @return The boolean validity of the proof. */ function verify( bytes memory value, bytes memory encodedPath, bytes memory rlpParentNodes, bytes32 root ) internal pure returns (bool) { RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes); RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item); bytes memory currentNode; RLPReader.RLPItem[] memory currentNodeList; bytes32 nodeKey = root; uint256 pathPtr = 0; bytes memory path = _getNibbleArray(encodedPath); if (path.length == 0) { return false; } for (uint256 i = 0; i < parentNodes.length; i++) { if (pathPtr > path.length) { return false; } currentNode = RLPReader.toRlpBytes(parentNodes[i]); if (nodeKey != keccak256(currentNode)) { return false; } currentNodeList = RLPReader.toList(parentNodes[i]); if (currentNodeList.length == 17) { if (pathPtr == path.length) { if ( keccak256(RLPReader.toBytes(currentNodeList[16])) == keccak256(value) ) { return true; } else { return false; } } uint8 nextPathNibble = uint8(path[pathPtr]); if (nextPathNibble > 16) { return false; } nodeKey = bytes32( RLPReader.toUintStrict(currentNodeList[nextPathNibble]) ); pathPtr += 1; } else if (currentNodeList.length == 2) { uint256 traversed = _nibblesToTraverse( RLPReader.toBytes(currentNodeList[0]), path, pathPtr ); if (pathPtr + traversed == path.length) { //leaf node if ( keccak256(RLPReader.toBytes(currentNodeList[1])) == keccak256(value) ) { return true; } else { return false; } } //extension node if (traversed == 0) { return false; } pathPtr += traversed; nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[1])); } else { return false; } } } function _nibblesToTraverse( bytes memory encodedPartialPath, bytes memory path, uint256 pathPtr ) private pure returns (uint256) { uint256 len = 0; // encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath // and slicedPath have elements that are each one hex character (1 nibble) bytes memory partialPath = _getNibbleArray(encodedPartialPath); bytes memory slicedPath = new bytes(partialPath.length); // pathPtr counts nibbles in path // partialPath.length is a number of nibbles for (uint256 i = pathPtr; i < pathPtr + partialPath.length; i++) { bytes1 pathNibble = path[i]; slicedPath[i - pathPtr] = pathNibble; } if (keccak256(partialPath) == keccak256(slicedPath)) { len = partialPath.length; } else { len = 0; } return len; } // bytes b must be hp encoded function _getNibbleArray(bytes memory b) internal pure returns (bytes memory) { bytes memory nibbles = ""; if (b.length > 0) { uint8 offset; uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b)); if (hpNibble == 1 || hpNibble == 3) { nibbles = new bytes(b.length * 2 - 1); bytes1 oddNibble = _getNthNibbleOfBytes(1, b); nibbles[0] = oddNibble; offset = 1; } else { nibbles = new bytes(b.length * 2 - 2); offset = 0; } for (uint256 i = offset; i < nibbles.length; i++) { nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b); } } return nibbles; } function _getNthNibbleOfBytes(uint256 n, bytes memory str) private pure returns (bytes1) { return bytes1( n % 2 == 0 ? uint8(str[n / 2]) / 0x10 : uint8(str[n / 2]) % 0x10 ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library Merkle { function checkMembership( bytes32 leaf, uint256 index, bytes32 rootHash, bytes memory proof ) internal pure returns (bool) { require(proof.length % 32 == 0, "Invalid proof length"); uint256 proofHeight = proof.length / 32; // Proof of size n means, height of the tree is n+1. // In a tree of height n+1, max #leafs possible is 2 ^ n require(index < 2 ** proofHeight, "Leaf index is too big"); bytes32 proofElement; bytes32 computedHash = leaf; for (uint256 i = 32; i <= proof.length; i += 32) { assembly { proofElement := mload(add(proof, i)) } if (index % 2 == 0) { computedHash = keccak256( abi.encodePacked(computedHash, proofElement) ); } else { computedHash = keccak256( abi.encodePacked(proofElement, computedHash) ); } index = index / 2; } return computedHash == rootHash; } } pragma solidity ^0.8.0; import { RLPReader } from "./RLPReader.sol"; library ExitPayloadReader { using RLPReader for bytes; using RLPReader for RLPReader.RLPItem; uint8 constant WORD_SIZE = 32; struct ExitPayload { RLPReader.RLPItem[] data; } struct Receipt { RLPReader.RLPItem[] data; bytes raw; uint256 logIndex; } struct Log { RLPReader.RLPItem data; RLPReader.RLPItem[] list; } struct LogTopics { RLPReader.RLPItem[] data; } // copy paste of private copy() from RLPReader to avoid changing of existing contracts function copy(uint src, uint dest, uint len) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } function toExitPayload(bytes memory data) internal pure returns (ExitPayload memory) { RLPReader.RLPItem[] memory payloadData = data .toRlpItem() .toList(); return ExitPayload(payloadData); } function getHeaderNumber(ExitPayload memory payload) internal pure returns(uint256) { return payload.data[0].toUint(); } function getBlockProof(ExitPayload memory payload) internal pure returns(bytes memory) { return payload.data[1].toBytes(); } function getBlockNumber(ExitPayload memory payload) internal pure returns(uint256) { return payload.data[2].toUint(); } function getBlockTime(ExitPayload memory payload) internal pure returns(uint256) { return payload.data[3].toUint(); } function getTxRoot(ExitPayload memory payload) internal pure returns(bytes32) { return bytes32(payload.data[4].toUint()); } function getReceiptRoot(ExitPayload memory payload) internal pure returns(bytes32) { return bytes32(payload.data[5].toUint()); } function getReceipt(ExitPayload memory payload) internal pure returns(Receipt memory receipt) { receipt.raw = payload.data[6].toBytes(); RLPReader.RLPItem memory receiptItem = receipt.raw.toRlpItem(); if (receiptItem.isList()) { // legacy tx receipt.data = receiptItem.toList(); } else { // pop first byte before parsting receipt bytes memory typedBytes = receipt.raw; bytes memory result = new bytes(typedBytes.length - 1); uint256 srcPtr; uint256 destPtr; assembly { srcPtr := add(33, typedBytes) destPtr := add(0x20, result) } copy(srcPtr, destPtr, result.length); receipt.data = result.toRlpItem().toList(); } receipt.logIndex = getReceiptLogIndex(payload); return receipt; } function getReceiptProof(ExitPayload memory payload) internal pure returns(bytes memory) { return payload.data[7].toBytes(); } function getBranchMaskAsBytes(ExitPayload memory payload) internal pure returns(bytes memory) { return payload.data[8].toBytes(); } function getBranchMaskAsUint(ExitPayload memory payload) internal pure returns(uint256) { return payload.data[8].toUint(); } function getReceiptLogIndex(ExitPayload memory payload) internal pure returns(uint256) { return payload.data[9].toUint(); } // Receipt methods function toBytes(Receipt memory receipt) internal pure returns(bytes memory) { return receipt.raw; } function getLog(Receipt memory receipt) internal pure returns(Log memory) { RLPReader.RLPItem memory logData = receipt.data[3].toList()[receipt.logIndex]; return Log(logData, logData.toList()); } // Log methods function getEmitter(Log memory log) internal pure returns(address) { return RLPReader.toAddress(log.list[0]); } function getTopics(Log memory log) internal pure returns(LogTopics memory) { return LogTopics(log.list[1].toList()); } function getData(Log memory log) internal pure returns(bytes memory) { return log.list[2].toBytes(); } function toRlpBytes(Log memory log) internal pure returns(bytes memory) { return log.data.toRlpBytes(); } // LogTopics methods function getField(LogTopics memory topics, uint256 index) internal pure returns(RLPReader.RLPItem memory) { return topics.data[index]; } } // SPDX-License-Identifier: MIT pragma solidity ^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; 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"); (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); } } } }
compute child token template code hash
) FxBaseRootTunnel(_checkpointManager, _fxRoot) { childTokenTemplateCodeHash = keccak256( minimalProxyCreationCode(_fxERC20Token) ); }
6,885,670
[ 1, 9200, 1151, 1147, 1542, 981, 1651, 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, 262, 478, 92, 2171, 2375, 20329, 24899, 25414, 1318, 16, 389, 19595, 2375, 13, 288, 203, 3639, 1151, 1345, 2283, 1085, 2310, 273, 417, 24410, 581, 5034, 12, 203, 5411, 16745, 3886, 9906, 1085, 24899, 19595, 654, 39, 3462, 1345, 13, 203, 3639, 11272, 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 ]
/* HABEO - (share around) ---------------------- HABEO is the teoken that will change the way we use crypto. We'll make it easy to use and easy to understand so everyone can take advantage of it. This code is fully commented so everyone can learn from it. The comments are only in english for practical purposes but it should translate very well with Google translate or similar translation services. If you have questions about the translation, head out to your Discord Server(https://discord.gg/NA8YnT38sn) and the community will help you. Check our website for more information: https://www.habeotoken.com Follow us on Twitter: @HabeoToken Join our Reddit sub: r/HabeoToken Check our Youtube channel: https://www.youtube.com/channel/UCmZa_90rxRD08rDiSa7Nh2w **/ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // All these interfaces and cotracts are here to provide the standard functionality for the BEP-20/ERC-20 tokens. // To look at HABEO's code, start looking at line 385. interface IERC20 { 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); } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; return msg.data; } } contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; 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(), "Not 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), "Owner is zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "No permission"); require(block.timestamp > _lockTime , "Locked for 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } 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; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); // function removeLiquidity( // address tokenA, // address tokenB, // uint liquidity, // uint amountAMin, // uint amountBMin, // address to, // uint deadline // ) external returns (uint amountA, uint amountB); // function removeLiquidityETH( // address token, // uint liquidity, // uint amountTokenMin, // uint amountETHMin, // address to, // uint deadline // ) external returns (uint amountToken, uint amountETH); // function removeLiquidityWithPermit( // address tokenA, // address tokenB, // uint liquidity, // uint amountAMin, // uint amountBMin, // address to, // uint deadline, // bool approveMax, uint8 v, bytes32 r, bytes32 s // ) external returns (uint amountA, uint amountB); // function removeLiquidityETHWithPermit( // address token, // uint liquidity, // uint amountTokenMin, // uint amountETHMin, // address to, // uint deadline, // bool approveMax, uint8 v, bytes32 r, bytes32 s // ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { // function removeLiquidityETHSupportingFeeOnTransferTokens( // address token, // uint liquidity, // uint amountTokenMin, // uint amountETHMin, // address to, // uint deadline // ) external returns (uint amountETH); // function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( // address token, // uint liquidity, // uint amountTokenMin, // uint amountETHMin, // address to, // uint deadline, // bool approveMax, uint8 v, bytes32 r, bytes32 s // ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( 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 swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract Habeo is Context, IERC20, Ownable { // Here's where HABEO code starts // // For these global variables and structures, we've tried to pack them as much as we could // to try to save as much gas as possible. // This link explains some of the what, the why and the how: // https://medium.com/@novablitz/storing-structs-is-costing-you-gas-774da988895e // Contract structure struct ContractData{ // Biggest number possible that can be created with uint256. // We'll use it for reflection calculations. uint256 MAX; // Initial supply of tokens uint256 tokensTotal; // This does not reflect "the total number of reflections" in a direct way. Instead, it is used // in the calculations of values to show the right number for tokens+reflections when users // look at wallet balance. uint256 reflectionsTotal; // Maximum transaction size allowed for transfers between wallets. uint256 maxTxAmount; // This sets the threshold for the contract to swap and liquify. // It's inefficient to do it on every transaction so the contract collects // the liquidity fees and when the contract balance hits numTokensSwapToAddToLiquidity or more, // it goes through the swap and liquify process on the next transaction. // This property also sets the number of tokens to swap for BNB. uint256 numTokensSwapToAddToLiquidity; // Metadata about the token. string name; string symbol; uint8 decimals; } // Create the contract data instance with all the contract's configuration. ContractData public contractData; // Wallet structure struct WalletData { // For regular wallets, we don't count tokens, // we coun't reflections so we can calculate new // balances on the fly to save gas. uint256 reflectionsOwned; // For contracts and other interfaces that are excluded from the reflections, // we do count tokens (and reflections). uint256 tokensOwned; // Throttling the ability to swap too quickly. // HABEO only allows one exchange operation (to swap) every 8 hours. uint256 lastExchangeOperation; // When swapping to create liquidity, we need to provide allowance to the // router so we use this map. It is also needed for any "transfer from" operations users may want to do. mapping (address => uint256) allowances; // Accounts marked as true, are not charged taxes nor receive reflections. // Typical accounts here (at likely only) are the Contract, the Exchanges // and the burn wallet (after the burn is complete). bool isExcludedFromTaxAndReflections; // Did this wallet already acquire tokens at the early distribution? // Since we only allow for one early distribution per wallet, here's where we set the flag. bool walletsThatAcquiredAtEarlyDistro; // This indicates whether this is the address of an exchange or not. // We need to partiulcarly understand if we are dealing with an Exchange at some points. bool walletIsExchange; } // List of wallets - Anyone having HABEO will have an entry here. mapping (address => WalletData) private wallets; // This indicates whether we are in the process of swapping and liquifying or not. // Basically, this needs to be set to true WHILE we are swapping and liquifying // so we do not enter into a recursive loop. bool inSwapAndLiquify; // Are we still in early distribution mode? // This will be set to false at the end of early distribution and won't ever change back to true. bool inEarlyDistro = true; // 97.5% of the tokens will be burnt over time. This will make the burn wallet the largest holder // while the burn process is happening and as such, it will eat up more reflections than any other wallet. // Because of this, the growth of the wallet is accellerated over time until the protocol has burnt 97.5% // of the circulating tokens. Once this happens and we stop the burning process, // The burn wallet is then excluded from future reflections and holders will perceive a noticeable increase in // reflections owned. bool keepBurning = true; // Initialization of the PancakeSwap interface objects. IUniswapV2Router02 public pcsV2Router; address public pcsV2Pair; // Wallet address for the devteam. // This address will be deploying the contract and then, renouncing ownership of it. // This account exists for two main reasons. // #1 - allows for addition and removal of exchanges. // #2 - allows for the dev team to withdraw donations sent to the contract after the early distribution is done. address private devteam; //EARLY DISTRO Configs // Max number of HABEOs to distribute. // This is the maximum number of HABEOs that the early distribution can exchange. // The early distribution will be closed at the due date or when having distributed 250,000,000,000,000 HABEO (give or take a few), // whichever comes first. uint256 public earlyDistroMaxHABEO = 250000000 * 10**6 * 10**9; // Expiration time for early distribution: 30 days from contract deployment. uint256 public earlyDistroDeadline = block.timestamp + 30 days; // During early distribution, this balance will keep track of the received BNB that will be added to liquidity and // will be used to pass the value to the initial liquidity addition right when the early distribution ends. uint256 private liquidityBNB; // Map to establish # of tokens per BNB at early distribution. // This exists with the sole purpose of creating a very fair early distribution process. // Instead of allowing any size request of tokens, we only have 7 different packages offered at early distribution: // 25, 10, 5, 1, 0.5, 0.2 and 0.1 BNB // Each package distributes a specific amount of tokens being slightly more beneficial to acquire the 5 BNB worth of packages. // If everyone acquires 5 BNB worth of the token, we would end up with an initial LP of 2500 BNB. Because there will be a // number of people acquiring different amounts of token, it is highly possible the initial LP will be larger than 2500 BNB mapping (uint256 => uint256) public earlyDistroPackages; // Management // When new exchanges are added, we push them to this array so we can loop through it // and remove each exchange from the reflections when running reflections calculations. // This has to be dynamic because we want to have the ability to add and remove exchanges at any time so // we can't have a fixed size array. address[] private newExchanges; event SwapAndLiquify(uint256 tokensSwapped, uint256 bnbReceived, uint256 tokensIntoLiqudity); // This is the constructor. // Constructor code only runs once, at deployment. It basically sets up the contract in the BSC network. constructor () { // For those trying to understand this math, look at this article: // https://weka.medium.com/dividend-bearing-tokens-on-ethereum-42d01c710657 // Original initial supply of tokens = 1,000,000,000,000,000 (that's 15 0s) but we also account for decimals (9). // Because we are working with 9 decimals, we need to add 9 digits since we cannot use fractional numbers. // Largest uint256 number that can be created // Quick way to reference it is to negate 0. contractData.MAX = ~uint256(0); // Maximum number of tokens created by the contract contractData.tokensTotal = 1000000000 * 10**6 * 10**9; // This is the part of the math that the above mentioned article does a good job at explaining. contractData.reflectionsTotal = (contractData.MAX - (contractData.MAX % contractData.tokensTotal)); // Max tx amount between accounts is 10,000,000,000 tokens at once. contractData.maxTxAmount = 10000 * 10**6 * 10**9; // Once the early distribution has ended, the contract will continue adding to liquidity. // Instead of adding at every transaction (inefficient), we wait to collect a certain number of tokens // and then we swap. // In this case we are waiting to collect 100,000,000 tokens before adding to liquidity. contractData.numTokensSwapToAddToLiquidity = 100 * 10**6 * 10**9; // Metadata contractData.name = "Habeo"; contractData.symbol = "HABEO"; contractData.decimals = 9; // Set the dev team address variable to the sender address. // Since we are creating the contract, we are the sender. // We are also the owner, but this way it is clearer. // We will be renouncing ownership a few lines below. devteam = _msgSender(); // Give all the tokens to the contract so the contract can send them to the // the wallets when the BNB is received. wallets[address(this)].tokensOwned = contractData.tokensTotal; wallets[address(this)].reflectionsOwned = contractData.reflectionsTotal; // Instanciate the router with the valid address // We keep all of the addresses here or informational purposes but the one used at the time // of deployment must be the Mainnet V2 (probably in the future, PCS will have more versions). //0xD99D1c33F9fC3444f8101754aBC46c52416550D1 - Testnet //0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3 - Testnet alternate and currently working well with https://pancake.kiemtienonline360.com/ //0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F - Mainnet V1 router - do not use - here for reference //0x10ED43C718714eb63d5aA57B78B54704E256024E - Mainnet V2 router - this is the one we deploy with. pcsV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); // Try to create the pair HABEO/BNB. If it exists, the address for the pair is returned here, if it does not exist // it is created AND the address returned here. pcsV2Pair = IUniswapV2Factory(pcsV2Router.factory()).createPair(address(this), pcsV2Router.WETH()); // Remove this contract from fees and reflections. wallets[address(this)].isExcludedFromTaxAndReflections = true; // Leave the burn address with fees and reflections. Not needed at this point but // it helps with understanding how it works. We'll include it when the burn has // reached the maximum burn expected. wallets[address(0)].isExcludedFromTaxAndReflections = false; // Remove original exchange from the reflections. // We set the address as exchange too. wallets[pcsV2Pair].isExcludedFromTaxAndReflections = true; wallets[pcsV2Pair].walletIsExchange = true; // For those unfamiliar with the way BNB (and most cryptos for that matter) works, // some quick hints are shared here. // Please get yourself familiar with these concepts before any other step. // The units in which operations happen are not 1 BNB. They happen in much smaller fractions. // The name for the smallest possible unit in BNB is wei. // 1 BNB = 1 * 10**18 wei (thats 10 to the power of 18). // When we deal with the coin (BNB in this case) we need to do it in multiples of wei. // So, you'll see a lot of 0s or multiplications and exponentiations happening along the code // to make the numbers easier to understand. // There are not many instances in the code where we need to calculate 25,10,5,1,0.5,0.2 and 0.1 BNB // so we use literals in order to save storage. // We are assigning token distribution depending on the value of BNB that is sent at early distribution. // For each level down from 5 BNB, you receive 10% fewer tokens, except for 0.5, 0.2 and 0.1 BNB since // percentage does not decrease after 0.5. // 0.5 BNB, 0.2 BNB amd 0.1 BNB receive the same proportional number of tokens. // For each level above 5 BNB you receive 10% fewer tokens. This way we encourage to acquire a good number // of tokens and discourage becoming a whale. // For 5 BNB you get 500,000,000,000 tokens - swapping value in BNB per token = 0.00000000001000 BNB // At the time of this writing, BNB is around $350 or so FIAT value for each token at this level would be // around $0.0000000035 // For 25 BNB 1,806,250,000,000 tokens - swapping value in BNB per token = 0.000000000013841 BNB (27.75% fewer compared to 5 BNB) earlyDistroPackages[25 * 10**18] = 1806250 * 10**6 * 10**9; // For 10 BNB you get 850,000,000,000 tokens - swapping value in BNB per token = 0.000000000011765 BNB (15% fewer compared to 5 BNB) earlyDistroPackages[10 * 10**18] = 850000 * 10**6 * 10**9; // For 5 BNB you get 500,000,000,000 tokens - swapping value in BNB per token = 0.00000000001000 BNB (Sweet spot) earlyDistroPackages[5 * 10**18] = 500000 * 10**6 * 10**9; // For 1 BNB you get 90,000,000,000 tokens - swapping value in BNB per token = 0.00000000001111 BNB (10% fewer compared to 5 BNB) earlyDistroPackages[1 * 10**18] = 90000 * 10**6 * 10**9; // For 0.5 BNB you get 40,500,000,000 tokens - swapping value in BNB per token = 0.00000000001234 BNB (19% fewer compared to 5 BNB) earlyDistroPackages[5 * 10**17] = 40500 * 10**6 * 10**9; // For 0.2 BNB you get 16,200,000,000 tokens - swapping value in BNB per token = 0.00000000001234 BNB (Same proportion to 0.5 BNB) earlyDistroPackages[2 * 10**17] = 16200 * 10**6 * 10**9; // For 0.1 BNB you get 8,100,000,000 tokens - swapping value in BNB per token = 0.00000000001234 BNB (Same proportion to 0.2 BNB) earlyDistroPackages[1 * 10**17] = 8100 * 10**6 * 10**9; // For the tokenomics these will present us with the following numbers: // If all early distribution tokens are distributed at 5 BNB: // 500 operations of 5 BNB each x 500,000,000,000 HABEO each = 2500 BNB collected / 250,000,000,000,000 tokens distributed. // 2500 BNB / 250,000,000,000,000 HABEO Liquidity // 500,000,000,000,000 Total tokens in circulation at start. // 500,000,000,000,000 Total tokens burnt right at the close of early distribution. // 475,000,000,000,000 burnt over time to get to 975,000,000,000,000 tokens burnt // and 25,000,000,000,000 total in circulation. // If all early distribution tokens are distributed at 0.1 BNB: // 30,864 operations of 0.1 BNB each x 8,100,000,000 HABEO each = ~3,086 BNB collected / 250,000,000,000,000 tokens distributed // 3,086 BNB / 250,000,000,000,000 HABEO Liquidity // 500,000,000,000,000 total tokens in circulation at start // 500,000,000,000,000 Total tokens burnt right at the close of early distribution. // 475,000,000,000,000 burnt over time to get to 975,000,000,000,000 tokens burnt // and 25,000,000,000,000 total in circulation. // If all early distribution tokens are distributed at 25 BNB: // 138 operations of 25 BNB each x 1,806,250,000,000 HABEO each = ~3,460 BNB collected / 250,000,000,000,000 tokens distributed // 3,460 BNB / 250,000,000,000,000 HABEO Liquidity // 500,000,000,000,000 total tokens in circulation at start // 500,000,000,000,000 Total tokens burnt right at the close of early distribution. // 475,000,000,000,000 burnt over time to get to 975,000,000,000,000 tokens burnt // and 25,000,000,000,000 total in circulation. // The difference between all three case scenarios is that in the second and third one, there will be more BNB in the // liquidity pool right after the early distribution ends. // The most likely case will be a mixture of all options which will bring the amount of BNB to somewhere in between. // This is where we renounce ownership. // The function is defined under the Owenable class if you want to see the details. renounceOwnership(); // We emit tokenstotal so we do not need to calculate from reflection. // At construction they are the same so we emit tokensTotal which is cheaper in gas emit Transfer(address(0), _msgSender(), contractData.tokensTotal); } // Constructor ends here. The rest of the code are functions that can be called externally or internally. // External functions are ONLY called externally. // Public functions are called EITHER internally or externally. // Internal functions are only accessible from the contract or any contracts derived from this contract. // Private functions can only be called from within the contract. // For HABEO, there are no unused functions. All of them are used somehow. // The receive() function is called when someone sends BNB to the contract and when the swap and liquify // process receives BNB to add to liquidity. // The withdrawBNBDonationsToDevTeam() can be called by anyone and it will only execute AFTER early distribution // The only thing it does is to withdraw whatever amount of BNB is in the contract (donations) and send it to the dev wallet. // The addRemoveExchange() function can only be called by the developeraccount and is used to add / remove // exchange addresses. This is needed so we can add exchanges that list HABEO on the fly and remove addresses // when exchanges update their contracts. // The rest of the functions are explained near the function code. // This function starts as the receiver of BNB for the early distribution and then // is used for the contract to recieve excess BNB from pcsV2Router when swaping. // Once the early distribution is done, donations to the devteam can be sent here too. receive() external payable { // To save gas, we avoid using require statements every chance we have. // For instance, instead of checking if the earlyDistroMaxBNB limit is already reached, // we let Solidity detect the overflow and cause an exception. // the exception (negative number) will cause a revert. // This will generate a generic "revert" fail message for the user but it saves gas to the user too. // As all exceptions and requires will eat up the gas anyways, it is better to make it cheaper to the user in gas. if (!inEarlyDistro || inSwapAndLiquify) { // We only arrive here if early distribution is done and someone donates to the dev team OR // if the router sends us swap excess. // We emit so the transfer is logged. emit Transfer(_msgSender(), address(this), msg.value); } else if (_msgSender() != address(pcsV2Router)) { // If we are at the due date or earlyDistroMaxBNB is reached, // we honor the last request even if it is after the established date // or if the earlyDistroMaxHABEO has been reached. // This does not affect the balance of tokens, BNB and burns at all so it's easier to // just do it and reward the last person that tried to get tokens at early distribution. // worst case scenario we'll be sending an extra 25 BNB in tokens, best case scenario we'll // be sending extra 0.1 BNB in tokens. // Either way, it should improve pricing at the exchange. // We do need to check if the value sent aligns with one of the allowed amounts. // If we get 0 here, an invalid amount of BNB was sent so we revert. uint256 tokensAmount = earlyDistroPackages[msg.value]; require (tokensAmount > 0 , "Wrong request amount"); // If someone wants to sneak a second request from a wallet, we revert. require (!wallets[_msgSender()].walletsThatAcquiredAtEarlyDistro, "Only 1 per wallet"); // We do want to use a variable as a temporary holder of the value to prevent re-entry attacks. uint256 amountBNB = msg.value; // Add the amount to the liquidity holder. liquidityBNB += amountBNB; // Remove the tokens from the contract. wallets[address(this)].tokensOwned -= tokensAmount; // Remove the reflections from the contract. // We could be using some of the existing functions to calculate rather than doing the math here. // However, it is saving gas to do it this way. wallets[address(this)].reflectionsOwned -= tokensAmount * (contractData.reflectionsTotal/contractData.tokensTotal); // Add the wallet to the list of wallets that have acquired tokens at the early distribution. wallets[_msgSender()].walletsThatAcquiredAtEarlyDistro = true; // Give the tokens to the wallet in reflections form. wallets[_msgSender()].reflectionsOwned += tokensAmount * (contractData.reflectionsTotal/contractData.tokensTotal); // Emit the event so the transfer is logged. emit Transfer(address(this), _msgSender(), tokensAmount); // Check to see if we have reached the total number of HABEOs at the early distribution or the earlyDistroDeadline. if (earlyDistroMaxHABEO > tokensAmount && block.timestamp < earlyDistroDeadline){ // If not, just deduct the new amount. earlyDistroMaxHABEO -= tokensAmount; } else if (earlyDistroMaxHABEO <= tokensAmount){ // If we did, then ensure the value for earlyDistroMaxHABEO is 0 and close the early distribution. earlyDistroMaxHABEO = 0; closeTheEarlyDistro(); inEarlyDistro = false; } } } // Here is where we close the early distribution function closeTheEarlyDistro() internal { // Initial burn number after early distribution. This is the number of tokens to be burnt right after early distribution. // both in tokens and in reflections as the wallet is not excluded from reflections until we reach // the max burn. uint256 tInitialBurn = 500000000 * 10**6 * 10**9; uint256 rInitialBurn = tInitialBurn * (contractData.reflectionsTotal/contractData.tokensTotal); // We substract the burnt tokens from the contract. wallets[address(this)].tokensOwned -= tInitialBurn; // We substract the burn reflections from the contract. wallets[address(this)].reflectionsOwned -= rInitialBurn; // We move the tokens and reflections to the burn wallet. wallets[address(0)].tokensOwned = tInitialBurn; wallets[address(0)].reflectionsOwned = rInitialBurn; // We emit the transfer so it is logged. emit Transfer(address(this), address(0), tInitialBurn); //We need to set the flag on so we can process the liquification inSwapAndLiquify = true; // Add all the tokens in the contract and all the BNBs as a pair. // Instead of calling swap and liquify, we can call addLiquidity directly because, // we already have the BNB so there's no need for swapping. // We provide all the remaining tokens in the contract and all the liquidity collected. addLiquidity(wallets[address(this)].tokensOwned, liquidityBNB, true); } // All these are the functions that show metadata upon request. // they are all external because they are usually called by wallets // and exchanges to show token data. function name() external view returns (string memory) { return contractData.name; } function symbol() external view returns (string memory) { return contractData.symbol; } function decimals() external view returns (uint8) { return contractData.decimals; } function totalSupply() external view override returns (uint256) { return contractData.tokensTotal; } // Simply returns the value in tTokens for the requested account // If the account is excluded, it simply returns the value. // If the account is not excluded, then we need to calculate the token value from the reflections value. function balanceOf(address account) external view override returns (uint256) { if (wallets[account].isExcludedFromTaxAndReflections) return wallets[account].tokensOwned; return tokensFromReflections(wallets[account].reflectionsOwned); } // This function shows what the allowance is for a certain pair of addresses. function allowance(address owner, address spender) external view override returns (uint256) { return wallets[owner].allowances[spender]; } // Transfer and approve are called by wallets/exchanges to initiate a transfer. // The approve function is the one that provides allowance to the exchanges to operate // on the user's behalf. // It can also be called manually by an experienced user to set up someone else to spend // tokens on the original user's behalf. // Of course the only account that can allow an approve call is the user allowing someone // else to spend on their behalf. // This is the point of entry for the transfer requests. function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } // This is the entry point for the approve function. // This enables an address to spend a certain amount of tokens on behalf of another address. // Basically, provides allowances to addresses. // This is used quite a bit at swap time and gives users the chance to allow others to spend on their behalf. // This is a requirement for DeFi exchanges like Pancakeswap. They ask for your approval to do this before you can swap. function approve(address spender, uint256 amount) external override returns (bool) { _approve(_msgSender(), spender, amount,true); return true; } // User may want to decrease the allowance provided to another account. // This is the point of entry for that. // This is not a common function to have. We provide it because we've seen some exchanges // (like PancakeSwap for instance) that sometimes try to get a wide range approval all at once. // If the user decides later that wants to lower this allowance, this is the function to call. // For a user to call this, the user needs to have a little bit more advanced knowledge. function decreaseAllowance(address spender, uint256 amount) external returns (bool) { _approve(_msgSender(), spender, amount,false); return true; } // This is the actual worker for the approve function. // This can only be called from this contract. function _approve(address allower, address spender, uint256 amount, bool incrementDecrement) private { // incrementDecrement determines if this is an increase or a decrease request. // If we are incrementing the allowance, we add to it. // If we are decrementing, we decrement and if we don't have enough, we set to 0. if(incrementDecrement){ if (amount >= contractData.MAX - wallets[allower].allowances[spender]){ wallets[allower].allowances[spender] = contractData.MAX; } else { wallets[allower].allowances[spender] += amount; } } else if (wallets[allower].allowances[spender] >= amount){ wallets[allower].allowances[spender] -= amount; } else { wallets[allower].allowances[spender] = 0; } // We emit the event to log it. emit Approval(allower, spender, amount); } // General transfer function to send from one account to another. // This is what the allowance is for when a user authorizes another user to spend on behalf. // This is a standard BEP-20/ERC-20 function. function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { // First we try to decrease the allowance. // If we do not have enough allowance we revert through the exception. wallets[sender].allowances[_msgSender()] -= amount; // If we have the allowance, we transfer. _transfer(sender, recipient, amount); return true; } // This function returns the number of tokens owned by providing the current number of reflections // it is only used internally a couple of times but one of those is the balanceOf function which is // called continuously by the exchanges and wallets. function tokensFromReflections(uint256 reflectionsAmount) private view returns(uint256) { // First we get the current rate of reflections vs tokens. // Then we divide by the rate. // The getRate function spins up the currentsupply calculation which is complex and spends gas. uint256 currentRate = getRate(); return reflectionsAmount / currentRate; } // This is the function used at transfer time that returns various values that are needed for a correct // distribution of tokens. // The amount to provide is the number of real tokens and the function returns values in both reflection and token. // We need this translation because of reflection. // This is a very gas expensive function. function getValues(uint256 tAmount, uint256 tax) private view returns (uint256, uint256, uint256, uint256, uint256) { // We need to find out the t values. (uint256 tTransferAmount, uint256 tFee) = getTValues(tAmount, tax); // And we need to out the r values. (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = getRValues(tAmount, tFee, getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee); } // This is a spinoff from the getValues function and it returns the token part of the values function getTValues(uint256 tAmount, uint256 tax) private pure returns (uint256, uint256) { // Tax is a percentage so we calculate the t value of the fees. uint256 tFee = tAmount * tax / 10**2; // transferAmount is tokenAmount minus tax minus liq (to save gas we use the same // variable since rate for tax = liq rate) uint256 tTransferAmount = tAmount - tFee - tFee; return (tTransferAmount, tFee); } // This is a spinoff from the getValues function and it returns the reflections part of the values function getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { // convert tokens to reflections uint256 rAmount = tAmount * currentRate; // do the same for the fees uint256 rFee = tFee * currentRate; // now calculate the transfer amount in reflections too. // substract fee two times because of liq AND reflections. uint256 rTransferAmount = rAmount - rFee - rFee; return (rAmount, rTransferAmount, rFee); } // This function calculates and returns the rate of conversion between reflections and tokens. // Notice that it calls getCurrentSupply which is an expensive function. function getRate() private view returns(uint256) { (uint256 reflectionsSupply, uint256 tokensSupply) = getCurrentSupply(); return reflectionsSupply / tokensSupply; } // We calculate supply as follows: // - We start with the total for tokens and reflections // (maximum number of tokens and reflections minus reflections fees that // have been removed over time because of the reflection distribution process) // - We remove any tokens and reflections that are owned by the excluded accounts from that supply. // - We then return those totals which are the current supply for tokens and reflecions function getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = contractData.reflectionsTotal; uint256 tSupply = contractData.tokensTotal; // We do need to check if we are in early distribution because we do not apply reflections at early distribution. // In this case we return totals. // If this was not here, then it would mess balances because the contract still owns all of the // tokens that have yet to be acquired. if (inEarlyDistro){ return (contractData.reflectionsTotal, contractData.tokensTotal); } // This is exclusively for precaution. If for whatever reason the numbers don't add up, // go back to the basics. This is the least invasive thing to do. if (rSupply < contractData.reflectionsTotal / contractData.tokensTotal) return (contractData.reflectionsTotal, contractData.tokensTotal); // This is expensive. // This loop goes through all of the added exchanges and, as they are excluded, // removes the r and t values belonging to them. for (uint256 i = 0; i < newExchanges.length; i++) { rSupply -= wallets[newExchanges[i]].reflectionsOwned; tSupply -= wallets[newExchanges[i]].tokensOwned; } // We know these are already excluded so we make the above loop shorter. tSupply = tSupply - wallets[pcsV2Pair].tokensOwned - wallets[address(this)].tokensOwned; rSupply = rSupply - wallets[pcsV2Pair].reflectionsOwned - wallets[address(this)].reflectionsOwned; // Once we are done burning, we start excluding the burning address form the supply. if (!keepBurning){ tSupply -= wallets[address(0)].tokensOwned; rSupply -= wallets[address(0)].reflectionsOwned; } return (rSupply, tSupply); } // This is the worker transfer function // It is a wrapper for the transfer functions that are specific for each scenario // General calculations happen here. function _transfer(address from, address to, uint256 amount) private { uint256 contractTokenBalance = 0; // During early distribution, only transactions from the contract are allowed. // This is so the contract can distribute the tokens and add to the liquidity pool WHILE // no reflections or taxing happens. if (inEarlyDistro){ if(from != address(this)){ revert("Cannot transfer during early distribution"); } } else { // We only check this if we are not in early distribution anymore. // Is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? contractTokenBalance = wallets[address(this)].tokensOwned; } // Between regular accounts, there's a max transfer size. // However, anyone can swap as much as they want. Swapping large numbers pays higher taxes. // Also the contract and the burn wallet can transfer as much as they want. if((!wallets[from].walletIsExchange && !wallets[to].walletIsExchange) || (!wallets[from].isExcludedFromTaxAndReflections && !wallets[to].isExcludedFromTaxAndReflections)){ require(amount <= contractData.maxTxAmount, "Above Transfer Limit"); } // Make sure the request is not coming from PCS so we prevent a circular event. // Saving some variable declaration by setting the contractBalance to the numTokensSwapToAddToLiquidity // so we can swap a fixed ammount of tokens. if (from != pcsV2Pair && (contractTokenBalance >= contractData.numTokensSwapToAddToLiquidity) && !inSwapAndLiquify) { contractTokenBalance = contractData.numTokensSwapToAddToLiquidity; // Swap and add liquidity swapAndLiquify(contractTokenBalance); } // If we are still burning it's because we did not hit 975,000,000,000,000 burnt yet, // check and see if we did hit that mark. If we did, we stop burning, convert the // reflections into tokens and move the // 0x address to excluded so it does not receive any more reflections. if (keepBurning){ // We need to check the burn wallet balance. // Lifetime max number of tokens to burn. // Amazingly, it is cheaper to run the math here than to have a stored global with the value. // Both for deployment and exec. // Max lifetime burn = 975,000,000,000,000 if (wallets[address(0)].tokensOwned >= (975000000 * 10**6 * 10**9)){ // Stop the burn keepBurning = false; // Convert 0x wallet into an excluded address so it does not receive any more reflections wallets[address(0)].isExcludedFromTaxAndReflections = true; } } // Initiate transfer. Tax will be charged later. tokenTransfer(from,to,amount); } // This is where we start the process to provide liquidity on a regular basis. // We first swap half of the tokens for BNB. // Then, we add liquidity putting together the remaining half of the tokens and the swapped BNB as pair. // There will be a very small leftover that goes into the contract address. // The reason to do it like this is that liquidity needs to be added in a balanced way. // If the new liquidity was not balanced, then if would affect swap value noticeably // (the exchange does not allow this anyways). // So, we see how much BNB we can obtain with half of the tokens. Then, we have the remaining half of the tokens // that evidently are worth pretty much the amount of BNB that we've received for the initial half. // Putting these two together to add liquidity gives us a huge chance of having a pretty accurate calculation. // Nevertheless, as the amounts will not be perfect, the small leftovers are returned to the contract. function swapAndLiquify(uint256 contractTokenBalance) private { // We must raise a flag to recognize that we have started a swap. inSwapAndLiquify = true; // If we are still burning, this is where we take some tokens to burn them if (keepBurning){ // We liquify 90% of the fees // We burn 10% of the fees // We divide contractTokenBalance by 10 so we can burn 10% uint256 burnPile = contractTokenBalance / 10; // If we substract 10% from 100%, we have 90%. // we'll use this 90% to liquify. contractTokenBalance -= burnPile; // What's the reflections amount for the burned tokens? (uint256 rAmount, , , , ) = getValues(burnPile, 0); // Burn the tokens. wallets[address(0)].reflectionsOwned += rAmount; // even though the burn wallet is not excluded from reflections yet, // we still add the tokens to keep it up to date. wallets[address(0)].tokensOwned += burnPile; //Emit a transfer to show the movement. emit Transfer(address(this), address(0), burnPile); } // Now that we have the 90% to work with, we split the contract balance into halves. uint256 half = contractTokenBalance / 2; // Capture the contract's current BNB balance. // This is so that we can capture exactly the amount of BNB that the // swap creates, and not make the liquidity event include any BNB that // had been left over or manually sent to the contract. uint256 initialBalance = address(this).balance; // Swap half of the tokens for BNB. swapTokensForBNB(half); // How much BNB did we just swap into? // We have to do this so we can maintain the balance as close as possible in the LP. uint256 bnbSwapAmmount = address(this).balance - initialBalance; // Get the contract to add liquidity to PCS addLiquidity(half, bnbSwapAmmount,false); emit SwapAndLiquify(half, bnbSwapAmmount, half); } // This is where we get the tokens swapped for BNB. function swapTokensForBNB(uint256 tokenAmount) private { // Create the array to pass as the pair token/weth address[] memory path = new address[](2); path[0] = address(this); path[1] = pcsV2Router.WETH(); // Since the router will be using tokens on behalf of the contract, // we need to get an allowance. _approve(address(this), address(pcsV2Router), tokenAmount,true); // Make the swap happen and set the contract as the receiver of any leftover. pcsV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of BNB path, address(this), block.timestamp + 10 seconds ); } // This is where we add the liquidity function addLiquidity(uint256 tokenAmount, uint256 bnbAmount, bool fromEarlyDistro) private { // Again, we need to make sure the router can spend the tokens on behalf of the contract. // We save some gas by adding allowance directly instead of going through approve. // _approve(address(this), address(pcsV2Router), tokenAmount, true); wallets[address(this)].allowances[address(pcsV2Router)] += tokenAmount; // We need to check whether we arrived here through the swapandliquify function or directly // from the early distribution end event. if(fromEarlyDistro){ // If we got here from the early distribution, we clear the variable containing the liquidity amount // since we have passed it now as tokenAmount with the call. liquidityBNB = 0; } // We add the liquidity and lock the CAKE-LP forever. pcsV2Router.addLiquidityETH{value: bnbAmount}( address(this), tokenAmount, 0, 0, // Sending the CAKE tokens to the burn wallet means // they are not recoverable and the liquidity is locked forever address(0), block.timestamp + 10 seconds ); // Turn the flag off for swapping. inSwapAndLiquify = false; } // This method is responsible for deciding what route to take with regards to fees function tokenTransfer(address sender, address recipient, uint256 amount) private { if (wallets[sender].walletIsExchange) { // This should only take the basic tax ammount since it's someone obtaining HABEO // it should not however take fees if recipient is excluded. transferFromExchange(sender, recipient, amount); } else if (wallets[recipient].walletIsExchange) { // We need to check if the owner or contract are sending to LP, in which case we do not take fees. // If it is not the case, then this is a regular account swapping. take taxes accordingly transferToExchange(sender, recipient, amount); } else if (wallets[sender].isExcludedFromTaxAndReflections || wallets[recipient].isExcludedFromTaxAndReflections) { // This is excluded/excluded transactions and not exchanges are involved, no fees. transferWithExcluded(sender, recipient, amount); } else { // If nothing else, default to standard. // These are two regular accounts transferring tokens from one to the other. // Low fees. transferStandard(sender, recipient, amount); } } // This method is a helper to calculate the tax rate that an operation incurs. // This is only triggered when the TO is an exchange since that's a swapping out operation. // The rate is based on the percentage of account balance being transferred. function calculateTaxAndLiquidityBasedOnTxPercentage(uint256 senderBalance,uint256 amount) private pure returns (uint256){ // Minimum tax. uint256 tax = 1; // Percentage of amount over senderBalance. uint256 pctSwappedOut = amount * 100 / senderBalance; // Remember that this only calculates the rate. // This rate applies to both charges, the reflection fee and the liquidity. // So, percentages taken from the txs are 2,4,6,8,10,20,30,40,50,60 respectively. if (pctSwappedOut <= 1) { tax = 1; } else if (pctSwappedOut <= 2) { tax = 2; } else if (pctSwappedOut <= 3) { tax = 3; } else if (pctSwappedOut <= 4) { tax = 4; } else if (pctSwappedOut <= 5) { tax = 5; } else if (pctSwappedOut <= 10) { tax = 10; } else if (pctSwappedOut <= 20) { tax = 15; } else if (pctSwappedOut <= 40) { tax = 20; } else if (pctSwappedOut <= 75) { tax = 25; } else if (pctSwappedOut <= 100) { tax = 30; } return (tax); } // Standard transactions are the easiest. // Two regular wallets trading tokens. // Very low fee. 2% total. (1% tax rate) function transferStandard(address sender, address recipient, uint256 tAmount) private { uint256 rAmount; uint256 rTransferAmount; uint256 rFee; uint256 tTransferAmount; uint256 tFee; // Standard transfers have a tax rate of 1 so we hardcode it to save gas. (rAmount, rTransferAmount, rFee, tTransferAmount, tFee) = getValues(tAmount, 1); // Remove the reflections from the sender wallets[sender].reflectionsOwned -= rAmount; // Add the reflections (minus taxes) to the recipient. wallets[recipient].reflectionsOwned += rTransferAmount; // Now, take care of the liquidity and fees takeCareOfLiquidityAndFees(rFee, tFee); // Show the transaction to the world. emit Transfer(sender, recipient, tTransferAmount); } // This other route means we are sending tokens to an exchange // This could be either a swap or liquidity provision. // If it's a swap, high tax. if it is LP, no tax. function transferToExchange(address sender, address recipient, uint256 tAmount) private { uint256 rAmount; uint256 rTransferAmount; uint256 rFee; uint256 tTransferAmount; uint256 tFee; // We have to do this (getValues) two times, the first one is to get the ramount so we can // understand what percentage of the wallet is being affected. We do this with a tax of 0 so // no fees are deducted. // We do it outside the "If then" so we can use the resulting values as the first instance of the if or at the else. // We do the second one, after we've calculated the taxes for this transaction. // This time around, taxes are charged. (rAmount, rTransferAmount, rFee, tTransferAmount, tFee) = getValues(tAmount, 0); // Is this a regular wallet? if (!wallets[sender].isExcludedFromTaxAndReflections){ // Regular accounts can't swap more often than once every 8 hours. require (wallets[sender].lastExchangeOperation <= block.timestamp - 8 hours, "Too soon"); // Calculate the tax rate (uint256 taxRate) = calculateTaxAndLiquidityBasedOnTxPercentage(wallets[sender].reflectionsOwned, rAmount); // Now we need to calculate the transfer and fees/liqs with the updated tax values (rAmount, rTransferAmount, rFee, tTransferAmount, tFee) = getValues(tAmount, taxRate); // We remove the reflections from the sender. All of the amount. wallets[sender].reflectionsOwned -= rAmount; // We add the reflections to the exchange. Just the transfer amount. wallets[recipient].reflectionsOwned += rTransferAmount; // We add the tokens to the exchange. Just the transfer amount. wallets[recipient].tokensOwned += tTransferAmount; // We update the timestamp so the wallet cannot operate until the next window. wallets[sender].lastExchangeOperation = block.timestamp; } else { // If this is an excluded wallet, then it's simpler as they are not charged taxes. // Take tokens from sender. wallets[sender].tokensOwned -= tAmount; // Take tokens from sender. wallets[sender].reflectionsOwned -= rAmount; // Add the tokens to the exchange. wallets[recipient].tokensOwned += tTransferAmount; // We add the reflections to the exchange. Just the transfer amount. wallets[recipient].reflectionsOwned += rTransferAmount; } // Now, take care of the liquidity and fees takeCareOfLiquidityAndFees(rFee, tFee); // Show the transaction to the world. emit Transfer(sender, recipient, tTransferAmount); } // If an excluded address is reciving tokens from PCS then, no fees. // This could be being done to manage LP or something to that extent. // If the recipient is a regular account, then they are obtaining tokens so, low fees. function transferFromExchange(address sender, address recipient, uint256 tAmount) private { uint256 rAmount; uint256 rTransferAmount; uint256 rFee; uint256 tTransferAmount; uint256 tFee; // Is this an excluded account? if (wallets[recipient].isExcludedFromTaxAndReflections){ // No tax so 0 passed. (rAmount, rTransferAmount, rFee, tTransferAmount, tFee) = getValues(tAmount, 0); // Remove the tokens from the exchange wallet. wallets[sender].tokensOwned -= tAmount; // Remove the reflections from the exchange wallet. wallets[sender].reflectionsOwned -= rAmount; // Add the tokens to the recipient. wallets[recipient].tokensOwned += tTransferAmount; // Add the reflections to the recipient. wallets[recipient].reflectionsOwned += rTransferAmount; } else { // This is a regular account getting tokens. // Regular accounts can't swap more often than once every 8 hours. require (wallets[recipient].lastExchangeOperation <= block.timestamp - 8 hours, "Too soon"); // Minimal tax of 1%. (rAmount, rTransferAmount, rFee, tTransferAmount, tFee) = getValues(tAmount, 1); // Remove the tokens from the exchange. wallets[sender].tokensOwned -= tAmount; // Remove the tokens from the exchange. wallets[sender].reflectionsOwned -= rAmount; // Add the reflections to the recipient's wallet. wallets[recipient].reflectionsOwned += rTransferAmount; // We update the timestamp so the wallet cannot operate until the next window. wallets[recipient].lastExchangeOperation = block.timestamp; } // Now, take care of the liquidity and fees takeCareOfLiquidityAndFees(rFee, tFee); // Show the transaction to the world. emit Transfer(sender, recipient, tTransferAmount); } // We are dealing with either, or both accounts being excluded but with no exanches involved. function transferWithExcluded(address sender, address recipient, uint256 tAmount) private { uint256 rAmount; uint256 rTransferAmount; uint256 rFee; uint256 tTransferAmount; uint256 tFee; // No taxes when working with excluded accounts (rAmount, rTransferAmount, rFee, tTransferAmount, tFee) = getValues(tAmount, 0); //These apply to all cases // Remove reflections from sender. wallets[sender].reflectionsOwned -= rAmount; // Add reflections to recipient. wallets[recipient].reflectionsOwned += rTransferAmount; // If both are excluded. if (wallets[sender].isExcludedFromTaxAndReflections && wallets[recipient].isExcludedFromTaxAndReflections){ // Remove tokens from sender. wallets[sender].tokensOwned -= tAmount; // Add tokens to recipient. wallets[recipient].tokensOwned += tTransferAmount; } else if(wallets[sender].isExcludedFromTaxAndReflections){ // Only the sender is excluded so, take tokens from sender. wallets[sender].tokensOwned -= tAmount; } else { // Add tokens to recipient. wallets[recipient].tokensOwned += tTransferAmount; } // Now, take care of the liquidity and fees takeCareOfLiquidityAndFees(rFee, tFee); // Show the transaction to the world. emit Transfer(sender, recipient, tTransferAmount); } function takeCareOfLiquidityAndFees(uint256 refFee, uint256 tokFee) private { // Add the liquidity tokens to the tokens owned by the contract. // Liquidity and fees have the same value so we only use a generic fee that we can apply both for // liquidity and tax/reflections. wallets[address(this)].tokensOwned += tokFee; wallets[address(this)].reflectionsOwned += refFee; // Remove the fee from the reflections totals (this is how distribution happens). contractData.reflectionsTotal -= refFee; } // We are opening anyone to donate BNB to the dev team by sending it to the contract. // Together with the donations, there will be a very small amount of leftover BNB from // the swaps that will accumulate over time. // The reason this leftover is in the contract is that after swap and liq, there's always a small // rounding amount because the exchange could never be exact. // This keeps accummulating in the contract address and it is inevitable because of the way liquidity pools work. // The ammount each time is minimal (a few dollar cents at current BNB value) so it does not // affect trading or liq at all. // However, it is a waste to leave this in the contract accumulating over time. // So, we've added a function that when called by anyone, sends the accummulated BNB to the devteam's wallet. // As ownership is renounced, the BNB would get locked and lost forever if this function did not exist. // This function does not work until the early distribution is done so devs can't collect BNB from it. function withdrawBNBDonationsToDevTeam() external{ // If we are in early distribution or swapping, leave. if (!inEarlyDistro && !inSwapAndLiquify){ // Get the balance. uint256 amount = address(this).balance; // Send the BNB to the devs wallet. payable(devteam).transfer(amount); // Let everyone know this happened. emit Transfer(address(this), address(devteam), amount); } } // This function is only callable by dev team. // The use for this is to add or remove an exchange account. // To add, we simply append at the end of the array. // To remove, we need to go through a loop, find the account, remove it, // move the last account into the slot of the removed one and then, shorten the array by 1. // We also set the right flags on the account and convert/remove tokens. function addRemoveExchange(address account, bool addRemove) external { // If the devteam did not call this, leave. if (msg.sender == devteam){ // If this flag is true then, we are adding an exchange. if (addRemove){ // if it has any reflections on it we get the token value for them. wallets[account].tokensOwned = tokensFromReflections(wallets[account].reflectionsOwned); // This wallet is now an exchange. wallets[account].walletIsExchange = true; // Exclude the wallet from taxes and reflections. wallets[account].isExcludedFromTaxAndReflections = true; // Add the account to the newExchanges array for later looping when needed. newExchanges.push(account); } else { // We are removing an exchange. // We need to loop through the array until we find the affected account. for (uint256 i = 0; i < newExchanges.length; i++) { // If we find it, we remove it. if (newExchanges[i] == account) { // We move the last address into the affected account spot. newExchanges[i] = newExchanges[newExchanges.length - 1]; // Remove all tokens. wallets[newExchanges[i]].tokensOwned = 0; // Set the flag off. No longer an exchange. wallets[newExchanges[i]].walletIsExchange = false; // Let it experience taxes and reflections again. wallets[newExchanges[i]].isExcludedFromTaxAndReflections = false; // Remove the last entry from the array. newExchanges.pop(); // Break once found. No need to finish. break; } } } } return; } }
General transfer function to send from one account to another. This is what the allowance is for when a user authorizes another user to spend on behalf. This is a standard BEP-20/ERC-20 function. First we try to decrease the allowance. If we do not have enough allowance we revert through the exception. If we have the allowance, we transfer.
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { wallets[sender].allowances[_msgSender()] -= amount; _transfer(sender, recipient, amount); return true; }
12,583,425
[ 1, 12580, 7412, 445, 358, 1366, 628, 1245, 2236, 358, 4042, 18, 1220, 353, 4121, 326, 1699, 1359, 353, 364, 1347, 279, 729, 2869, 3128, 4042, 729, 358, 17571, 603, 12433, 6186, 18, 1220, 353, 279, 4529, 9722, 52, 17, 3462, 19, 654, 39, 17, 3462, 445, 18, 5783, 732, 775, 358, 20467, 326, 1699, 1359, 18, 971, 732, 741, 486, 1240, 7304, 1699, 1359, 732, 15226, 3059, 326, 1520, 18, 971, 732, 1240, 326, 1699, 1359, 16, 732, 7412, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 7412, 1265, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 3903, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 17662, 2413, 63, 15330, 8009, 5965, 6872, 63, 67, 3576, 12021, 1435, 65, 3947, 3844, 31, 203, 3639, 389, 13866, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 3639, 327, 638, 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, -100, -100, -100, -100, -100, -100, -100, -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/0xC0205e203F423Bcd8B2a4d6f8C8A154b0Aa60F19/sources/ConverterRegistry.sol
* @dev checks whether or not a given value is a converter anchor @param _value value @return true if the given value is an anchor, false if not/
function isAnchor(address _value) public view override returns (bool) { return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).isSmartToken(_value); }
3,607,119
[ 1, 12366, 2856, 578, 486, 279, 864, 460, 353, 279, 6027, 6984, 225, 389, 1132, 460, 327, 638, 309, 326, 864, 460, 353, 392, 6984, 16, 629, 309, 486, 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, 353, 11605, 12, 2867, 389, 1132, 13, 1071, 1476, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 327, 467, 5072, 4243, 751, 12, 2867, 951, 12, 2248, 2204, 2560, 67, 5937, 25042, 67, 4883, 13, 2934, 291, 23824, 1345, 24899, 1132, 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 ]
// File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.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/token/ERC20/IERC20.sol 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); } // File: @openzeppelin/contracts/math/SafeMath.sol 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) { 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; } } // File: @openzeppelin/contracts/utils/Address.sol 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"); } /** * @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: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This 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 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.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. */ 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 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/SandwichToken.sol pragma solidity 0.6.12; // SandwichToken with Governance. contract SandwichToken is ERC20("SandwichToken", "SWH"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /// @notice burn `_amount` token from `_account`. Must only be called by the owner (MasterChef). function burn(address _account, uint256 _amount) public onlyOwner { _burn(_account, _amount); _moveDelegates(_delegates[_account],address(0), _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 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 The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "SANDWICH::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "SANDWICH::delegateBySig: invalid nonce"); require(now <= expiry, "SANDWICH::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @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 (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @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, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "SANDWICH::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; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SANDWICHs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "SANDWICH::_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 DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
@notice burn `_amount` token from `_account`. Must only be called by the owner (MasterChef).
function burn(address _account, uint256 _amount) public onlyOwner { _burn(_account, _amount); _moveDelegates(_delegates[_account],address(0), _amount); }
2,055,508
[ 1, 70, 321, 1375, 67, 8949, 68, 1147, 628, 1375, 67, 4631, 8338, 6753, 1338, 506, 2566, 635, 326, 3410, 261, 7786, 39, 580, 74, 2934, 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, 565, 445, 18305, 12, 2867, 389, 4631, 16, 2254, 5034, 389, 8949, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 70, 321, 24899, 4631, 16, 389, 8949, 1769, 203, 3639, 389, 8501, 15608, 815, 24899, 3771, 1332, 815, 63, 67, 4631, 6487, 2867, 12, 20, 3631, 389, 8949, 1769, 203, 565, 289, 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 ]
./full_match/137/0x2ae00e1bB3492F1D535fa0b4C568740Fd6A733f6/sources/contracts/MaticPirates.sol
* As another option for supporting trading without requiring meta transactions, override isApprovedForAll to whitelist OpenSea proxy accounts on Matic/
function isApprovedForAll( address _owner, address _operator ) public override view returns (bool isOperator) { if (_operator == address(0x58807baD0B376efc12F5AD86aAc70E78ed67deaE)) { return true; } return ERC721.isApprovedForAll(_owner, _operator); }
3,753,671
[ 1, 1463, 4042, 1456, 364, 22930, 1284, 7459, 2887, 29468, 2191, 8938, 16, 3849, 353, 31639, 1290, 1595, 358, 10734, 3502, 1761, 69, 2889, 9484, 603, 490, 2126, 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 ]
[ 1, 1, 1, 1, 1, 1, 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, 353, 31639, 1290, 1595, 12, 203, 3639, 1758, 389, 8443, 16, 203, 3639, 1758, 389, 9497, 203, 565, 262, 1071, 3849, 1476, 1135, 261, 6430, 353, 5592, 13, 288, 203, 3639, 309, 261, 67, 9497, 422, 1758, 12, 20, 92, 8204, 3672, 27, 12124, 40, 20, 38, 6418, 26, 73, 7142, 2138, 42, 25, 1880, 5292, 69, 9988, 7301, 41, 8285, 329, 9599, 323, 69, 41, 3719, 288, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 540, 203, 3639, 327, 4232, 39, 27, 5340, 18, 291, 31639, 1290, 1595, 24899, 8443, 16, 389, 9497, 1769, 203, 565, 289, 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 ]
./full_match/43113/0xCF79ba6aC171e56DB2d931EE353e57E5be7ad585/sources/contracts/Alto_Token.sol
Number of decimals of the smallest unit
uint8 public _decimals;
7,112,403
[ 1, 1854, 434, 15105, 434, 326, 13541, 2836, 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, 2254, 28, 1071, 389, 31734, 31, 282, 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.5.0; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { 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); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @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; } } /** * @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; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query 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]; } /** * @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 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) { _transfer(msg.sender, 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) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @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 * Emits an Approval event. * @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) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); 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 * Emits an Approval event. * @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) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ 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); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ 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); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ 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); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } contract BlackList is Ownable, ERC20 { function getBlackListStatus(address _maker) external view returns (bool) { return blackLists[_maker]; } function getOwner() external view returns (address) { return owner; } mapping (address => bool) public blackLists; function addBlackList (address _evilUser) public onlyOwner { blackLists[_evilUser] = true; } function removeBlackList (address _clearedUser) public onlyOwner { blackLists[_clearedUser] = false; } function destroyBlackFunds (address _blackListedUser) public onlyOwner { require(blackLists[_blackListedUser]); uint dirtyFunds = balanceOf(_blackListedUser); _burn(_blackListedUser, dirtyFunds); } event DestroyedBlackFunds(address _blackListedUser, uint _balance); event AddedBlackList(address _user); event RemovedBlackList(address _user); } /** * @title BREATH * @author BREATH * * @dev Standard ERC20 token with burn, mint & blacklist. */ contract BREATH is BlackList { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Constructor. * @param name name of the token * @param symbol symbol of the token, 3-4 chars is recommended * @param decimals number of decimal places of one token unit, 18 is widely used * @param totalSupply total supply of tokens in lowest units (depending on decimals) * @param tokenOwnerAddress address that gets 100% of token supply */ constructor(string memory name, string memory symbol, uint8 decimals, uint256 totalSupply, address payable feeReceiver, address tokenOwnerAddress) public payable { _name = name; _symbol = symbol; _decimals = decimals; // set tokenOwnerAddress as owner of all tokens _mint(tokenOwnerAddress, totalSupply); // pay the service fee for contract deployment feeReceiver.transfer(msg.value); } /** * @dev Burns a specific amount of tokens. * @param value The amount of lowest token units to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } // optional functions from ERC20 stardard /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } function transfer(address _to, uint256 _value) public returns (bool) { require(!blackLists[msg.sender]); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(!blackLists[_from]); return super.transferFrom(_from, _to, _value); } /** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public onlyOwner returns (bool) { _mint(account, amount); return true; } }
* @title BREATH @author BREATH @dev Standard ERC20 token with burn, mint & blacklist./
contract BREATH is BlackList { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals, uint256 totalSupply, address payable feeReceiver, address tokenOwnerAddress) public payable { _name = name; _symbol = symbol; _decimals = decimals; _mint(tokenOwnerAddress, totalSupply); feeReceiver.transfer(msg.value); } function burn(uint256 value) public { _burn(msg.sender, value); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function transfer(address _to, uint256 _value) public returns (bool) { require(!blackLists[msg.sender]); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(!blackLists[_from]); return super.transferFrom(_from, _to, _value); } function mint(address account, uint256 amount) public onlyOwner returns (bool) { _mint(account, amount); return true; } }
503,405
[ 1, 38, 862, 3275, 225, 605, 862, 3275, 225, 8263, 4232, 39, 3462, 1147, 598, 18305, 16, 312, 474, 473, 11709, 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 ]
[ 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, 0 ]
[ 1, 16351, 605, 862, 3275, 353, 22467, 682, 288, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 203, 565, 3885, 12, 1080, 3778, 508, 16, 533, 3778, 3273, 16, 2254, 28, 15105, 16, 2254, 5034, 2078, 3088, 1283, 16, 1758, 8843, 429, 14036, 12952, 16, 1758, 1147, 5541, 1887, 13, 1071, 8843, 429, 288, 203, 1377, 389, 529, 273, 508, 31, 203, 1377, 389, 7175, 273, 3273, 31, 203, 1377, 389, 31734, 273, 15105, 31, 203, 203, 1377, 389, 81, 474, 12, 2316, 5541, 1887, 16, 2078, 3088, 1283, 1769, 203, 203, 1377, 14036, 12952, 18, 13866, 12, 3576, 18, 1132, 1769, 203, 565, 289, 203, 203, 565, 445, 18305, 12, 11890, 5034, 460, 13, 1071, 288, 203, 1377, 389, 70, 321, 12, 3576, 18, 15330, 16, 460, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 508, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 1377, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 1377, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 1135, 261, 11890, 28, 13, 288, 203, 1377, 327, 389, 31734, 31, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2583, 12, 5, 11223, 7432, 63, 3576, 18, 15330, 19226, 203, 3639, 2 ]
./full_match/80001/0xae510345f19A2725b110D2A795eBfe526C0EE6DB/sources/contracts/MetaTxForwarder.sol
setCaller(_caller);
) EIP712("MinimalForwarder", "0.0.1") { transferOwnership(_owner); }
5,561,986
[ 1, 542, 11095, 24899, 16140, 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, 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, 262, 512, 2579, 27, 2138, 2932, 2930, 2840, 30839, 3113, 315, 20, 18, 20, 18, 21, 7923, 288, 203, 3639, 7412, 5460, 12565, 24899, 8443, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./SafeMath.sol"; import "./IERC20.sol"; import "./MagicLampERC721.sol"; interface SuperMagic { function compose(address owner) external returns (bool); function bet(address owner) external returns (bool); } /** * @title MagicLamps NFT contract * @dev Extends MagicLampERC721 Non-Fungible Token Standard basic implementation */ contract MagicLamps is MagicLampERC721 { using SafeMath for uint256; using Address for address; // Public variables address public superMagicContract; // This is SHA256 hash of the provenance record of all MagicLamp artworks // It is derived by hashing every individual NFT's picture, and then concatenating all those hash, deriving yet another SHA256 from that. string public MAGICLAMPS_PROVENANCE = ""; uint256 public constant SALE_START_TIMESTAMP = 1631372400; uint256 public constant REVEAL_TIMESTAMP = SALE_START_TIMESTAMP + (7 days); uint256 public constant MAX_MAGICLAMP_SUPPLY = 10000; uint256 public MAGICLAMP_MINT_COUNT_LIMIT = 30; uint256 public constant REFERRAL_REWARD_PERCENT = 1000; // 10% uint256 public constant LIQUIDITY_FUND_PERCENT = 1000; // 10% bool public saleIsActive = false; uint256 public startingIndexBlock; uint256 public startingIndex; uint256 public mintPrice = 30000000000000000; // 0.03 ETH uint256 public aldnReward = 10000000000000000000; // (10% of ALDN totalSupply) / 10000 // Mapping from token ID to puzzle mapping (uint256 => uint256) public puzzles; // Referral management uint256 public totalReferralRewardAmount; uint256 public distributedReferralRewardAmount; mapping(address => uint256) public referralRewards; mapping(address => mapping(address => bool)) public referralStatus; address public liquidityFundAddress = 0x9C73aAdcFb1ee7314d2Ac96150073F88b47E0A32; address public devAddress = 0xB689bA113effd47d38CfF88A682465945bd80829; /* * 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 == 0x93254542 * => 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; // Events event DistributeReferralRewards(uint256 indexed magicLampIndex, uint256 amount); event EarnReferralReward(address indexed account, uint256 amount); event WithdrawFund(uint256 liquidityFund, uint256 treasuryFund); /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_, address aladdin, address genie) MagicLampERC721(name_, symbol_) { aladdinToken = aladdin; genieToken = genie; // register the supported interfaces to conform to MagiclampsERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } function mintMagicLamp(uint256 count, address referrer) public payable { require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started"); require(saleIsActive, "Sale must be active to mint"); require(totalSupply() < MAX_MAGICLAMP_SUPPLY, "Sale has already ended"); require(count > 0, "count cannot be 0"); require(count <= MAGICLAMP_MINT_COUNT_LIMIT, "Exceeds mint count limit"); require(totalSupply().add(count) <= MAX_MAGICLAMP_SUPPLY, "Exceeds max supply"); if(msg.sender != owner()) { require(mintPrice.mul(count) <= msg.value, "Ether value sent is not correct"); } IERC20(aladdinToken).transfer(_msgSender(), aldnReward.mul(count)); for (uint256 i = 0; i < count; i++) { uint256 mintIndex = totalSupply(); if (block.timestamp < REVEAL_TIMESTAMP) { _mintedBeforeReveal[mintIndex] = true; } puzzles[mintIndex] = getRandomNumber(type(uint256).min, type(uint256).max.sub(1)); _safeMint(_msgSender(), mintIndex); } if (referrer != address(0) && referrer != _msgSender()) { _rewardReferral(referrer, _msgSender(), msg.value); } /** * Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense */ if (startingIndexBlock == 0 && (totalSupply() == MAX_MAGICLAMP_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } function setSuperMagicContractAddress(address contractAddress) public onlyOwner { superMagicContract = contractAddress; } /** * Set price to mint a MagicLamps. */ function setMintPrice(uint256 _price) external onlyOwner { mintPrice = _price; } /** * Set maximum count to mint per once. */ function setMintCountLimit(uint256 count) external onlyOwner { MAGICLAMP_MINT_COUNT_LIMIT = count; } function setDevAddress(address _devAddress) external onlyOwner { devAddress = _devAddress; } /** * Set ALDN reward amount to mint a MagicLamp. */ function setALDNReward(uint256 _aldnReward) external onlyOwner { aldnReward = _aldnReward; } /** * Mint MagicLamps by owner */ function reserveMagicLamps(address to, uint256 count) external onlyOwner { require(to != address(0), "Invalid address to reserve."); uint256 supply = totalSupply(); uint256 i; for (i = 0; i < count; i++) { _safeMint(to, supply + i); } if (startingIndexBlock == 0) { startingIndexBlock = block.number; } } function bet(uint256 useTokenId1) public { require(superMagicContract != address(0), "SuperMagic contract address need be set"); address from = msg.sender; require(ownerOf(useTokenId1) == from, "ERC721: use of token1 that is not own"); // _burn(useTokenId1); safeTransferFrom(from, superMagicContract, useTokenId1); SuperMagic superMagic = SuperMagic(superMagicContract); bool result = superMagic.bet(from); require(result, "SuperMagic compose failed"); } function compose(uint256 useTokenId1, uint256 useTokenId2, uint256 useTokenId3) public { require(superMagicContract != address(0), "SuperMagic contract address need be set"); address from = msg.sender; require(ownerOf(useTokenId1) == from, "ERC721: use of token1 that is not own"); require(ownerOf(useTokenId2) == from, "ERC721: use of token2 that is not own"); require(ownerOf(useTokenId3) == from, "ERC721: use of token3 that is not own"); // _burn(useTokenId1); // _burn(useTokenId2); // _burn(useTokenId3); safeTransferFrom(from, superMagicContract, useTokenId1); safeTransferFrom(from, superMagicContract, useTokenId2); safeTransferFrom(from, superMagicContract, useTokenId3); SuperMagic superMagic = SuperMagic(superMagicContract); bool result = superMagic.compose(from); require(result, "SuperMagic compose failed"); } /* * Set provenance once it's calculated */ function setProvenanceHash(string memory _provenanceHash) external onlyOwner { MAGICLAMPS_PROVENANCE = _provenanceHash; } /* * Pause sale if active, make active if paused */ function setSaleState() external onlyOwner { saleIsActive = !saleIsActive; } /** * @dev Finalize starting index */ function finalizeStartingIndex() public virtual { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_MAGICLAMP_SUPPLY; // 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_MAGICLAMP_SUPPLY; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } /** * @dev Withdraws liquidity and treasury fund. */ function withdrawFund() public onlyOwner { uint256 fund = address(this).balance.sub(totalReferralRewardAmount).add(distributedReferralRewardAmount); uint256 liquidityFund = _percent(fund, LIQUIDITY_FUND_PERCENT); payable(liquidityFundAddress).transfer(liquidityFund); uint256 treasuryFund = fund.sub(liquidityFund); uint256 devFund = treasuryFund.mul(30).div(100); payable(devAddress).transfer(devFund); payable(msg.sender).transfer(treasuryFund.sub(devFund)); emit WithdrawFund(liquidityFund, treasuryFund); } /** * @dev Withdraws ALDN to treasury if ALDN after sale ended */ function withdrawFreeToken(address token) public onlyOwner { if (token == aladdinToken) { require(totalSupply() >= MAX_MAGICLAMP_SUPPLY, "Sale has not ended"); } IERC20(token).transfer(msg.sender, IERC20(token).balanceOf(address(this))); } function _rewardReferral(address referrer, address referee, uint256 referralAmount) internal { uint256 referrerBalance = MagicLampERC721.balanceOf(referrer); bool status = referralStatus[referrer][referee]; uint256 rewardAmount = _percent(referralAmount, REFERRAL_REWARD_PERCENT); if (referrerBalance != 0 && rewardAmount != 0 && !status) { referralRewards[referrer] = referralRewards[referrer].add(rewardAmount); totalReferralRewardAmount = totalReferralRewardAmount.add(rewardAmount); emit EarnReferralReward(referrer, rewardAmount); referralRewards[referee] = referralRewards[referee].add(rewardAmount); totalReferralRewardAmount = totalReferralRewardAmount.add(rewardAmount); emit EarnReferralReward(referee, rewardAmount); referralStatus[referrer][referee] = true; } } function distributeReferralRewards(uint256 startMagicLampId, uint256 endMagicLampId) external onlyOwner { require(block.timestamp > SALE_START_TIMESTAMP, "Sale has not started"); require(startMagicLampId < totalSupply(), "Index is out of range"); if (endMagicLampId >= totalSupply()) { endMagicLampId = totalSupply().sub(1); } for (uint256 i = startMagicLampId; i <= endMagicLampId; i++) { address owner = ownerOf(i); uint256 amount = referralRewards[owner]; if (amount > 0) { magicLampWallet.depositETH{ value: amount }(address(this), i, amount); distributedReferralRewardAmount = distributedReferralRewardAmount.add(amount); delete referralRewards[owner]; emit DistributeReferralRewards(i, amount); } } } /** * Set the starting index block for the collection, essentially unblocking * setting starting index */ function emergencySetStartingIndexBlock() external onlyOwner { require(startingIndex == 0, "Starting index is already set"); startingIndexBlock = block.number; } function emergencyWithdraw() external onlyOwner { payable(msg.sender).transfer(address(this).balance); } /** * Get the array of token for owner. */ function tokensOfOwner(address _owner) external view returns(uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); for (uint256 index; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // 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 no longer needed starting with Solidity 0.8. 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. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * 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; } } } // SPDX-License-Identifier: MIT 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 `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 custom add */ function burn(uint256 burnQuantity) 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: MIT pragma solidity ^0.8.0; import "./SafeMath.sol"; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./IERC721Metadata.sol"; import "./Address.sol"; import "./Context.sol"; import "./ERC165.sol"; import "./Strings.sol"; import "./Ownable.sol"; import "./EnumerableMap.sol"; import "./EnumerableSet.sol"; import "./IMagicLampERC721.sol"; import "./Stringstrings.sol"; import "./IERC20.sol"; import "./SafeERC20.sol"; interface IMagicLampWallet { function depositETH(address host, uint256 id, uint256 amount) external payable; function withdrawAll(address host, uint256 id) external; } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract MagicLampERC721 is ERC165, IERC721, IERC721Metadata, IMagicLampERC721, Ownable { using SafeMath for uint256; using Address for address; using Strings for uint256; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Stringstrings for string; using SafeERC20 for IERC20; // Token name string private _name; // Token symbol string private _symbol; // Token URI string private _tokenUri; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap internal _tokenOwners; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) internal _holderTokens; // Mapping from token ID to approved address mapping (uint256 => address) internal _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal _operatorApprovals; uint256 public constant NAME_CHANGE_PRICE = 1337 * (10**18); // Mapping from token ID to name mapping (uint256 => string) internal _tokenName; // Mapping if certain name string has already been reserved mapping (string => bool) internal _nameReserved; // Mapping from token ID to whether the MagicLamp was minted before reveal mapping (uint256 => bool) internal _mintedBeforeReveal; address public aladdinToken; address public genieToken; IMagicLampWallet public magicLampWallet; // Intializing the random nonce uint256 private _randNonce = 0; // Events event NameChange(uint256 indexed magicLampIndex, string newName); /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "MagicLampERC721: 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, "MagicLampERC721: 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 baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return _tokenUri; } // Set Token URI function setBaseURI(string memory url) public onlyOwner { _tokenUri = url; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = MagicLampERC721.ownerOf(tokenId); require(to != owner, "MagicLampERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "MagicLampERC721: 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), "MagicLampERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "MagicLampERC721: 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), "MagicLampERC721: 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), "MagicLampERC721: 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 MagicLampERC721 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), "MagicLampERC721: 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) public 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), "MagicLampERC721: operator query for nonexistent token"); address owner = MagicLampERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `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), "MagicLampERC721: 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), "MagicLampERC721: mint to the zero address"); require(!exists(tokenId), "MagicLampERC721: 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 = MagicLampERC721.ownerOf(tokenId); // Prevent burner's MagicLampWallet assets to be transferred together magicLampWallet.withdrawAll(address(this), tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), 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(MagicLampERC721.ownerOf(tokenId) == from, "MagicLampERC721: transfer of token that is not own"); require(to != address(0), "MagicLampERC721: 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 Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(MagicLampERC721.ownerOf(tokenId), to, tokenId); } /** * @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()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("MagicLampERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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` 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 tokenId) internal virtual { } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override virtual returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override virtual 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 override virtual returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev Returns name of the MagicLamp at index. */ function tokenNameByIndex(uint256 index) public view virtual returns (string memory) { return _tokenName[index]; } /** * @dev Returns if the name has been reserved. */ function isNameReserved(string memory nameString) public view virtual returns (bool) { return _nameReserved[toLower(nameString)]; } /** * @dev Returns if the MagicLamp has been minted before reveal phase */ function isMintedBeforeReveal(uint256 index) public view override virtual returns (bool) { return _mintedBeforeReveal[index]; } function initMagicLampWalletAddress(address newMagicLampWallet) public virtual onlyOwner { magicLampWallet = IMagicLampWallet(newMagicLampWallet); } /** * @dev Changes the name of MagicLamp of given tokenId */ function changeName(uint256 tokenId, string memory newName) public virtual { require(_msgSender() == ownerOf(tokenId), "Caller is not the owner"); require(validateName(newName) == true, "Not a valid new name"); require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])), "New name is same as the current one"); require(sha256(bytes(toLower(newName))) == sha256(bytes(toLower(_tokenName[tokenId]))) || isNameReserved(newName) == false, "Name already reserved"); IERC20(genieToken).safeTransferFrom(_msgSender(), address(this), NAME_CHANGE_PRICE); // If already named, dereserve old name if (bytes(_tokenName[tokenId]).length > 0) { _toggleReserveName(_tokenName[tokenId], false); } _toggleReserveName(newName, true); _tokenName[tokenId] = newName; IERC20(genieToken).burn(NAME_CHANGE_PRICE); emit NameChange(tokenId, newName); } /** * @dev Reserves the name if isReserve is set to true, de-reserves if set to false */ function _toggleReserveName(string memory str, bool isReserve) internal virtual { _nameReserved[toLower(str)] = isReserve; } /** * @dev Checks if the name string is valid (Alphanumeric and spaces without leading or trailing space) */ function validateName(string memory str) public pure virtual returns (bool){ bytes memory b = bytes(str); if(b.length < 1) return false; if(b.length > 25) return false; // Cannot be longer than 25 characters if(b[0] == 0x20) return false; // Leading space if (b[b.length - 1] == 0x20) return false; // Trailing space bytes1 lastChar = b[0]; for(uint i; i<b.length; i++){ bytes1 char = b[i]; if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces if( !(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x20) //space ) return false; lastChar = char; } return true; } /** * @dev Converts the string to lowercase */ function toLower(string memory str) public pure virtual returns (string memory) { bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // Uppercase character if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } /** * @dev Counts percentage of amount */ function _percent(uint256 amount, uint256 fraction) internal pure virtual returns(uint256) { return amount.mul(fraction).div(10000); } function getRandomNumber(uint256 a, uint256 b) internal virtual returns (uint256) { uint256 min = a; uint256 max = (b.add(1)).sub(min); _randNonce ++; return (uint256(uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, _randNonce)))%max)).add(min); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./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.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.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.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.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) { 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.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. */ 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 () { // 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.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "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] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Context.sol"; // 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; address private _authorizedNewOwner; event OwnershipTransferAuthorization(address indexed authorizedAddress); 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 Returns the address of the current authorized new owner. */ function authorizedNewOwner() public view virtual returns (address) { return _authorizedNewOwner; } /** * @notice Authorizes the transfer of ownership from _owner to the provided address. * NOTE: No transfer will occur unless authorizedAddress calls assumeOwnership( ). * This authorization may be removed by another call to this function authorizing * the null address. * * @param authorizedAddress The address authorized to become the new owner. */ function authorizeOwnershipTransfer(address authorizedAddress) external onlyOwner { _authorizedNewOwner = authorizedAddress; emit OwnershipTransferAuthorization(_authorizedNewOwner); } /** * @notice Transfers ownership of this contract to the _authorizedNewOwner. */ function assumeOwnership() external { require(_msgSender() == _authorizedNewOwner, "Ownable: only the authorized new owner can accept ownership"); emit OwnershipTransferred(_owner, _authorizedNewOwner); _owner = _authorizedNewOwner; _authorizedNewOwner = address(0); } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. * * @param confirmAddress The address wants to give up ownership. */ function renounceOwnership(address confirmAddress) public virtual onlyOwner { require(confirmAddress == _owner, "Ownable: confirm address is wrong"); emit OwnershipTransferred(_owner, address(0)); _authorizedNewOwner = address(0); _owner = address(0); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./EnumerableSet.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 { using EnumerableSet for EnumerableSet.Bytes32Set; // 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 Map { // Storage of keys EnumerableSet.Bytes32Set _keys; mapping (bytes32 => bytes32) _values; } /** * @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) { map._values[key] = value; return map._keys.add(key); } /** * @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) { delete map._values[key]; return map._keys.remove(key); } /** * @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._keys.contains(key); } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._keys.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) { bytes32 key = map._keys.at(index); return (key, map._values[key]); } /** * @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) { bytes32 value = map._values[key]; if (value == bytes32(0)) { return (_contains(map, key), bytes32(0)); } else { return (true, value); } } /** * @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) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key"); return value; } /** * @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) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), errorMessage); return value; } // 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.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; if (lastIndex != toDeleteIndex) { 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] = valueIndex; // Replace lastvalue's index to valueIndex } // 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) { 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.8.0; import "./IERC721Enumerable.sol"; interface IMagicLampERC721 is IERC721Enumerable { function isMintedBeforeReveal(uint256 index) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Stringstrings { function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory) { 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 (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { 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; while (_i != 0) { k = k -1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } function fromAddress(address addr) internal pure returns(string memory) { bytes20 addrBytes = bytes20(addr); bytes16 hexAlphabet = "0123456789abcdef"; bytes memory result = new bytes(42); result[0] = '0'; result[1] = 'x'; for (uint i = 0; i < 20; i++) { result[i * 2 + 2] = hexAlphabet[uint8(addrBytes[i] >> 4)]; result[i * 2 + 3] = hexAlphabet[uint8(addrBytes[i] & 0x0f)]; } return string(result); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./Address.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' // 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 { 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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^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); } // SPDX-License-Identifier: MIT pragma solidity ^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); }
* @dev See {IERC721-setApprovalForAll}./
function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "MagicLampERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); }
6,846,959
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 17, 542, 23461, 1290, 1595, 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 ]
[ 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, 565, 445, 444, 23461, 1290, 1595, 12, 2867, 3726, 16, 1426, 20412, 13, 1071, 5024, 3849, 288, 203, 3639, 2583, 12, 9497, 480, 389, 3576, 12021, 9334, 315, 19289, 48, 931, 654, 39, 27, 5340, 30, 6617, 537, 358, 4894, 8863, 203, 203, 3639, 389, 9497, 12053, 4524, 63, 67, 3576, 12021, 1435, 6362, 9497, 65, 273, 20412, 31, 203, 3639, 3626, 1716, 685, 1125, 1290, 1595, 24899, 3576, 12021, 9334, 3726, 16, 20412, 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 ]
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.8.10; import {ILensHub} from '../interfaces/ILensHub.sol'; import {Events} from '../libraries/Events.sol'; import {Helpers} from '../libraries/Helpers.sol'; import {Constants} from '../libraries/Constants.sol'; import {DataTypes} from '../libraries/DataTypes.sol'; import {Errors} from '../libraries/Errors.sol'; import {PublishingLogic} from '../libraries/PublishingLogic.sol'; import {ProfileTokenURILogic} from '../libraries/ProfileTokenURILogic.sol'; import {InteractionLogic} from '../libraries/InteractionLogic.sol'; import {IERC721Enumerable} from '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol'; import {LensNFTBase} from './base/LensNFTBase.sol'; import {LensMultiState} from './base/LensMultiState.sol'; import {LensHubStorage} from './storage/LensHubStorage.sol'; import {VersionedInitializable} from '../upgradeability/VersionedInitializable.sol'; /** * @title LensHub * @author Lens Protocol * * @notice This is the main entrypoint of the Lens Protocol. It contains governance functionality as well as * publishing and profile interaction functionality. * * NOTE: The Lens Protocol is unique in that frontend operators need to track a potentially overwhelming * number of NFT contracts and interactions at once. For that reason, we've made two quirky design decisions: * 1. Both Follow & Collect NFTs invoke an LensHub callback on transfer with the sole purpose of emitting an event. * 2. Almost every event in the protocol emits the current block timestamp, reducing the need to fetch it manually. */ contract LensHub is ILensHub, LensNFTBase, VersionedInitializable, LensMultiState, LensHubStorage { uint256 internal constant REVISION = 1; address internal immutable FOLLOW_NFT_IMPL; address internal immutable COLLECT_NFT_IMPL; /** * @dev This modifier reverts if the caller is not the configured governance address. */ modifier onlyGov() { _validateCallerIsGovernance(); _; } /** * @dev This modifier reverts if the caller is not a whitelisted profile creator address. */ modifier onlyWhitelistedProfileCreator() { _validateCallerIsWhitelistedProfileCreator(); _; } /** * @dev The constructor sets the immutable follow & collect NFT implementations. * * @param followNFTImpl The follow NFT implementation address. * @param collectNFTImpl The collect NFT implementation address. */ constructor(address followNFTImpl, address collectNFTImpl) { FOLLOW_NFT_IMPL = followNFTImpl; COLLECT_NFT_IMPL = collectNFTImpl; } /// @inheritdoc ILensHub function initialize( string calldata name, string calldata symbol, address newGovernance ) external override initializer { super._initialize(name, symbol); _setState(DataTypes.ProtocolState.Paused); _setGovernance(newGovernance); } /// *********************** /// *****GOV FUNCTIONS***** /// *********************** /// @inheritdoc ILensHub function setGovernance(address newGovernance) external override onlyGov { _setGovernance(newGovernance); } /// @inheritdoc ILensHub function setEmergencyAdmin(address newEmergencyAdmin) external override onlyGov { address prevEmergencyAdmin = _emergencyAdmin; _emergencyAdmin = newEmergencyAdmin; emit Events.EmergencyAdminSet( msg.sender, prevEmergencyAdmin, newEmergencyAdmin, block.timestamp ); } /// @inheritdoc ILensHub function setState(DataTypes.ProtocolState newState) external override { if (msg.sender != _governance && msg.sender != _emergencyAdmin) revert Errors.NotGovernanceOrEmergencyAdmin(); _setState(newState); } ///@inheritdoc ILensHub function whitelistProfileCreator(address profileCreator, bool whitelist) external override onlyGov { _profileCreatorWhitelisted[profileCreator] = whitelist; emit Events.ProfileCreatorWhitelisted(profileCreator, whitelist, block.timestamp); } /// @inheritdoc ILensHub function whitelistFollowModule(address followModule, bool whitelist) external override onlyGov { _followModuleWhitelisted[followModule] = whitelist; emit Events.FollowModuleWhitelisted(followModule, whitelist, block.timestamp); } /// @inheritdoc ILensHub function whitelistReferenceModule(address referenceModule, bool whitelist) external override onlyGov { _referenceModuleWhitelisted[referenceModule] = whitelist; emit Events.ReferenceModuleWhitelisted(referenceModule, whitelist, block.timestamp); } /// @inheritdoc ILensHub function whitelistCollectModule(address collectModule, bool whitelist) external override onlyGov { _collectModuleWhitelisted[collectModule] = whitelist; emit Events.CollectModuleWhitelisted(collectModule, whitelist, block.timestamp); } /// ********************************* /// *****PROFILE OWNER FUNCTIONS***** /// ********************************* /// @inheritdoc ILensHub function createProfile(DataTypes.CreateProfileData calldata vars) external override whenNotPaused onlyWhitelistedProfileCreator { uint256 profileId = ++_profileCounter; _mint(vars.to, profileId); PublishingLogic.createProfile( vars, profileId, _profileIdByHandleHash, _profileById, _followModuleWhitelisted ); } /// @inheritdoc ILensHub function setDefaultProfile(uint256 profileId) external override whenNotPaused { _setDefaultProfile(msg.sender, profileId); } /// @inheritdoc ILensHub function setDefaultProfileWithSig(DataTypes.SetDefaultProfileWithSigData calldata vars) external override whenNotPaused { _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( SET_DEFAULT_PROFILE_WITH_SIG_TYPEHASH, vars.wallet, vars.profileId, sigNonces[vars.wallet]++, vars.sig.deadline ) ) ), vars.wallet, vars.sig ); _setDefaultProfile(vars.wallet, vars.profileId); } /// @inheritdoc ILensHub function setFollowModule( uint256 profileId, address followModule, bytes calldata followModuleData ) external override whenNotPaused { _validateCallerIsProfileOwner(profileId); PublishingLogic.setFollowModule( profileId, followModule, followModuleData, _profileById[profileId], _followModuleWhitelisted ); } /// @inheritdoc ILensHub function setFollowModuleWithSig(DataTypes.SetFollowModuleWithSigData calldata vars) external override whenNotPaused { address owner = ownerOf(vars.profileId); _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( SET_FOLLOW_MODULE_WITH_SIG_TYPEHASH, vars.profileId, vars.followModule, keccak256(vars.followModuleData), sigNonces[owner]++, vars.sig.deadline ) ) ), owner, vars.sig ); PublishingLogic.setFollowModule( vars.profileId, vars.followModule, vars.followModuleData, _profileById[vars.profileId], _followModuleWhitelisted ); } /// @inheritdoc ILensHub function setDispatcher(uint256 profileId, address dispatcher) external override whenNotPaused { _validateCallerIsProfileOwner(profileId); _setDispatcher(profileId, dispatcher); } /// @inheritdoc ILensHub function setDispatcherWithSig(DataTypes.SetDispatcherWithSigData calldata vars) external override whenNotPaused { address owner = ownerOf(vars.profileId); _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( SET_DISPATCHER_WITH_SIG_TYPEHASH, vars.profileId, vars.dispatcher, sigNonces[owner]++, vars.sig.deadline ) ) ), owner, vars.sig ); _setDispatcher(vars.profileId, vars.dispatcher); } /// @inheritdoc ILensHub function setProfileImageURI(uint256 profileId, string calldata imageURI) external override whenNotPaused { _validateCallerIsProfileOwnerOrDispatcher(profileId); _setProfileImageURI(profileId, imageURI); } /// @inheritdoc ILensHub function setProfileImageURIWithSig(DataTypes.SetProfileImageURIWithSigData calldata vars) external override whenNotPaused { address owner = ownerOf(vars.profileId); _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( SET_PROFILE_IMAGE_URI_WITH_SIG_TYPEHASH, vars.profileId, keccak256(bytes(vars.imageURI)), sigNonces[owner]++, vars.sig.deadline ) ) ), owner, vars.sig ); _setProfileImageURI(vars.profileId, vars.imageURI); } /// @inheritdoc ILensHub function setFollowNFTURI(uint256 profileId, string calldata followNFTURI) external override whenNotPaused { _validateCallerIsProfileOwnerOrDispatcher(profileId); _setFollowNFTURI(profileId, followNFTURI); } /// @inheritdoc ILensHub function setFollowNFTURIWithSig(DataTypes.SetFollowNFTURIWithSigData calldata vars) external override whenNotPaused { address owner = ownerOf(vars.profileId); _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( SET_FOLLOW_NFT_URI_WITH_SIG_TYPEHASH, vars.profileId, keccak256(bytes(vars.followNFTURI)), sigNonces[owner]++, vars.sig.deadline ) ) ), owner, vars.sig ); _setFollowNFTURI(vars.profileId, vars.followNFTURI); } /// @inheritdoc ILensHub function post(DataTypes.PostData calldata vars) external override whenPublishingEnabled { _validateCallerIsProfileOwnerOrDispatcher(vars.profileId); _createPost( vars.profileId, vars.contentURI, vars.collectModule, vars.collectModuleData, vars.referenceModule, vars.referenceModuleData ); } /// @inheritdoc ILensHub function postWithSig(DataTypes.PostWithSigData calldata vars) external override whenPublishingEnabled { address owner = ownerOf(vars.profileId); _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( POST_WITH_SIG_TYPEHASH, vars.profileId, keccak256(bytes(vars.contentURI)), vars.collectModule, keccak256(vars.collectModuleData), vars.referenceModule, keccak256(vars.referenceModuleData), sigNonces[owner]++, vars.sig.deadline ) ) ), owner, vars.sig ); _createPost( vars.profileId, vars.contentURI, vars.collectModule, vars.collectModuleData, vars.referenceModule, vars.referenceModuleData ); } /// @inheritdoc ILensHub function comment(DataTypes.CommentData calldata vars) external override whenPublishingEnabled { _validateCallerIsProfileOwnerOrDispatcher(vars.profileId); _createComment(vars); } /// @inheritdoc ILensHub function commentWithSig(DataTypes.CommentWithSigData calldata vars) external override whenPublishingEnabled { address owner = ownerOf(vars.profileId); _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( COMMENT_WITH_SIG_TYPEHASH, vars.profileId, keccak256(bytes(vars.contentURI)), vars.profileIdPointed, vars.pubIdPointed, vars.collectModule, keccak256(vars.collectModuleData), vars.referenceModule, keccak256(vars.referenceModuleData), sigNonces[owner]++, vars.sig.deadline ) ) ), owner, vars.sig ); _createComment( DataTypes.CommentData( vars.profileId, vars.contentURI, vars.profileIdPointed, vars.pubIdPointed, vars.collectModule, vars.collectModuleData, vars.referenceModule, vars.referenceModuleData ) ); } /// @inheritdoc ILensHub function mirror(DataTypes.MirrorData calldata vars) external override whenPublishingEnabled { _validateCallerIsProfileOwnerOrDispatcher(vars.profileId); _createMirror( vars.profileId, vars.profileIdPointed, vars.pubIdPointed, vars.referenceModule, vars.referenceModuleData ); } /// @inheritdoc ILensHub function mirrorWithSig(DataTypes.MirrorWithSigData calldata vars) external override whenPublishingEnabled { address owner = ownerOf(vars.profileId); _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( MIRROR_WITH_SIG_TYPEHASH, vars.profileId, vars.profileIdPointed, vars.pubIdPointed, vars.referenceModule, keccak256(vars.referenceModuleData), sigNonces[owner]++, vars.sig.deadline ) ) ), owner, vars.sig ); _createMirror( vars.profileId, vars.profileIdPointed, vars.pubIdPointed, vars.referenceModule, vars.referenceModuleData ); } /** * @notice Burns a profile, this maintains the profile data struct, but deletes the * handle hash to profile ID mapping value. * * NOTE: This overrides the LensNFTBase contract's `burn()` function and calls it to fully burn * the NFT. */ function burn(uint256 tokenId) public override whenNotPaused { super.burn(tokenId); _clearHandleHash(tokenId); } /** * @notice Burns a profile with a signature, this maintains the profile data struct, but deletes the * handle hash to profile ID mapping value. * * NOTE: This overrides the LensNFTBase contract's `burnWithSig()` function and calls it to fully burn * the NFT. */ function burnWithSig(uint256 tokenId, DataTypes.EIP712Signature calldata sig) public override whenNotPaused { super.burnWithSig(tokenId, sig); _clearHandleHash(tokenId); } /// *************************************** /// *****PROFILE INTERACTION FUNCTIONS***** /// *************************************** /// @inheritdoc ILensHub function follow(uint256[] calldata profileIds, bytes[] calldata datas) external override whenNotPaused { InteractionLogic.follow( msg.sender, profileIds, datas, FOLLOW_NFT_IMPL, _profileById, _profileIdByHandleHash ); } /// @inheritdoc ILensHub function followWithSig(DataTypes.FollowWithSigData calldata vars) external override whenNotPaused { bytes32[] memory dataHashes = new bytes32[](vars.datas.length); for (uint256 i = 0; i < vars.datas.length; ++i) { dataHashes[i] = keccak256(vars.datas[i]); } _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( FOLLOW_WITH_SIG_TYPEHASH, keccak256(abi.encodePacked(vars.profileIds)), keccak256(abi.encodePacked(dataHashes)), sigNonces[vars.follower]++, vars.sig.deadline ) ) ), vars.follower, vars.sig ); InteractionLogic.follow( vars.follower, vars.profileIds, vars.datas, FOLLOW_NFT_IMPL, _profileById, _profileIdByHandleHash ); } /// @inheritdoc ILensHub function collect( uint256 profileId, uint256 pubId, bytes calldata data ) external override whenNotPaused { InteractionLogic.collect( msg.sender, profileId, pubId, data, COLLECT_NFT_IMPL, _pubByIdByProfile, _profileById ); } /// @inheritdoc ILensHub function collectWithSig(DataTypes.CollectWithSigData calldata vars) external override whenNotPaused { _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( COLLECT_WITH_SIG_TYPEHASH, vars.profileId, vars.pubId, keccak256(vars.data), sigNonces[vars.collector]++, vars.sig.deadline ) ) ), vars.collector, vars.sig ); InteractionLogic.collect( vars.collector, vars.profileId, vars.pubId, vars.data, COLLECT_NFT_IMPL, _pubByIdByProfile, _profileById ); } /// @inheritdoc ILensHub function emitFollowNFTTransferEvent( uint256 profileId, uint256 followNFTId, address from, address to ) external override { address expectedFollowNFT = _profileById[profileId].followNFT; if (msg.sender != expectedFollowNFT) revert Errors.CallerNotFollowNFT(); emit Events.FollowNFTTransferred(profileId, followNFTId, from, to, block.timestamp); } /// @inheritdoc ILensHub function emitCollectNFTTransferEvent( uint256 profileId, uint256 pubId, uint256 collectNFTId, address from, address to ) external override { address expectedCollectNFT = _pubByIdByProfile[profileId][pubId].collectNFT; if (msg.sender != expectedCollectNFT) revert Errors.CallerNotCollectNFT(); emit Events.CollectNFTTransferred( profileId, pubId, collectNFTId, from, to, block.timestamp ); } /// ********************************* /// *****EXTERNAL VIEW FUNCTIONS***** /// ********************************* /// @inheritdoc ILensHub function isProfileCreatorWhitelisted(address profileCreator) external view override returns (bool) { return _profileCreatorWhitelisted[profileCreator]; } /// @inheritdoc ILensHub function defaultProfile(address wallet) external view override returns (uint256) { return _defaultProfileByAddress[wallet]; } /// @inheritdoc ILensHub function isFollowModuleWhitelisted(address followModule) external view override returns (bool) { return _followModuleWhitelisted[followModule]; } /// @inheritdoc ILensHub function isReferenceModuleWhitelisted(address referenceModule) external view override returns (bool) { return _referenceModuleWhitelisted[referenceModule]; } /// @inheritdoc ILensHub function isCollectModuleWhitelisted(address collectModule) external view override returns (bool) { return _collectModuleWhitelisted[collectModule]; } /// @inheritdoc ILensHub function getGovernance() external view override returns (address) { return _governance; } /// @inheritdoc ILensHub function getDispatcher(uint256 profileId) external view override returns (address) { return _dispatcherByProfile[profileId]; } /// @inheritdoc ILensHub function getPubCount(uint256 profileId) external view override returns (uint256) { return _profileById[profileId].pubCount; } /// @inheritdoc ILensHub function getFollowNFT(uint256 profileId) external view override returns (address) { return _profileById[profileId].followNFT; } /// @inheritdoc ILensHub function getFollowNFTURI(uint256 profileId) external view override returns (string memory) { return _profileById[profileId].followNFTURI; } /// @inheritdoc ILensHub function getCollectNFT(uint256 profileId, uint256 pubId) external view override returns (address) { return _pubByIdByProfile[profileId][pubId].collectNFT; } /// @inheritdoc ILensHub function getFollowModule(uint256 profileId) external view override returns (address) { return _profileById[profileId].followModule; } /// @inheritdoc ILensHub function getCollectModule(uint256 profileId, uint256 pubId) external view override returns (address) { return _pubByIdByProfile[profileId][pubId].collectModule; } /// @inheritdoc ILensHub function getReferenceModule(uint256 profileId, uint256 pubId) external view override returns (address) { return _pubByIdByProfile[profileId][pubId].referenceModule; } /// @inheritdoc ILensHub function getHandle(uint256 profileId) external view override returns (string memory) { return _profileById[profileId].handle; } /// @inheritdoc ILensHub function getPubPointer(uint256 profileId, uint256 pubId) external view override returns (uint256, uint256) { uint256 profileIdPointed = _pubByIdByProfile[profileId][pubId].profileIdPointed; uint256 pubIdPointed = _pubByIdByProfile[profileId][pubId].pubIdPointed; return (profileIdPointed, pubIdPointed); } /// @inheritdoc ILensHub function getContentURI(uint256 profileId, uint256 pubId) external view override returns (string memory) { (uint256 rootProfileId, uint256 rootPubId, ) = Helpers.getPointedIfMirror( profileId, pubId, _pubByIdByProfile ); return _pubByIdByProfile[rootProfileId][rootPubId].contentURI; } /// @inheritdoc ILensHub function getProfileIdByHandle(string calldata handle) external view override returns (uint256) { bytes32 handleHash = keccak256(bytes(handle)); return _profileIdByHandleHash[handleHash]; } /// @inheritdoc ILensHub function getProfile(uint256 profileId) external view override returns (DataTypes.ProfileStruct memory) { return _profileById[profileId]; } /// @inheritdoc ILensHub function getPub(uint256 profileId, uint256 pubId) external view override returns (DataTypes.PublicationStruct memory) { return _pubByIdByProfile[profileId][pubId]; } /// @inheritdoc ILensHub function getPubType(uint256 profileId, uint256 pubId) external view override returns (DataTypes.PubType) { if (pubId == 0 || _profileById[profileId].pubCount < pubId) { return DataTypes.PubType.Nonexistent; } else if (_pubByIdByProfile[profileId][pubId].collectModule == address(0)) { return DataTypes.PubType.Mirror; } else { if (_pubByIdByProfile[profileId][pubId].profileIdPointed == 0) { return DataTypes.PubType.Post; } else { return DataTypes.PubType.Comment; } } } /** * @dev Overrides the ERC721 tokenURI function to return the associated URI with a given profile. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { address followNFT = _profileById[tokenId].followNFT; return ProfileTokenURILogic.getProfileTokenURI( tokenId, followNFT == address(0) ? 0 : IERC721Enumerable(followNFT).totalSupply(), ownerOf(tokenId), _profileById[tokenId].handle, _profileById[tokenId].imageURI ); } /// **************************** /// *****INTERNAL FUNCTIONS***** /// **************************** function _setGovernance(address newGovernance) internal { address prevGovernance = _governance; _governance = newGovernance; emit Events.GovernanceSet(msg.sender, prevGovernance, newGovernance, block.timestamp); } function _createPost( uint256 profileId, string memory contentURI, address collectModule, bytes memory collectModuleData, address referenceModule, bytes memory referenceModuleData ) internal { PublishingLogic.createPost( profileId, contentURI, collectModule, collectModuleData, referenceModule, referenceModuleData, ++_profileById[profileId].pubCount, _pubByIdByProfile, _collectModuleWhitelisted, _referenceModuleWhitelisted ); } function _setDefaultProfile(address wallet, uint256 profileId) internal { if (profileId > 0) { if (wallet != ownerOf(profileId)) revert Errors.NotProfileOwner(); } _defaultProfileByAddress[wallet] = profileId; emit Events.DefaultProfileSet(wallet, profileId, block.timestamp); } function _createComment(DataTypes.CommentData memory vars) internal { PublishingLogic.createComment( vars, _profileById[vars.profileId].pubCount + 1, _profileById, _pubByIdByProfile, _collectModuleWhitelisted, _referenceModuleWhitelisted ); _profileById[vars.profileId].pubCount++; } function _createMirror( uint256 profileId, uint256 profileIdPointed, uint256 pubIdPointed, address referenceModule, bytes calldata referenceModuleData ) internal { PublishingLogic.createMirror( profileId, profileIdPointed, pubIdPointed, referenceModule, referenceModuleData, ++_profileById[profileId].pubCount, _pubByIdByProfile, _referenceModuleWhitelisted ); } function _setDispatcher(uint256 profileId, address dispatcher) internal { _dispatcherByProfile[profileId] = dispatcher; emit Events.DispatcherSet(profileId, dispatcher, block.timestamp); } function _setProfileImageURI(uint256 profileId, string memory imageURI) internal { if (bytes(imageURI).length > Constants.MAX_PROFILE_IMAGE_URI_LENGTH) revert Errors.ProfileImageURILengthInvalid(); _profileById[profileId].imageURI = imageURI; emit Events.ProfileImageURISet(profileId, imageURI, block.timestamp); } function _setFollowNFTURI(uint256 profileId, string memory followNFTURI) internal { _profileById[profileId].followNFTURI = followNFTURI; emit Events.FollowNFTURISet(profileId, followNFTURI, block.timestamp); } function _clearHandleHash(uint256 profileId) internal { bytes32 handleHash = keccak256(bytes(_profileById[profileId].handle)); _profileIdByHandleHash[handleHash] = 0; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override whenNotPaused { if (_dispatcherByProfile[tokenId] != address(0)) { _setDispatcher(tokenId, address(0)); } if (_defaultProfileByAddress[from] == tokenId) { _defaultProfileByAddress[from] = 0; } super._beforeTokenTransfer(from, to, tokenId); } function _validateCallerIsProfileOwnerOrDispatcher(uint256 profileId) internal view { if (msg.sender != ownerOf(profileId) && msg.sender != _dispatcherByProfile[profileId]) revert Errors.NotProfileOwnerOrDispatcher(); } function _validateCallerIsProfileOwner(uint256 profileId) internal view { if (msg.sender != ownerOf(profileId)) revert Errors.NotProfileOwner(); } function _validateCallerIsGovernance() internal view { if (msg.sender != _governance) revert Errors.NotGovernance(); } function _validateCallerIsWhitelistedProfileCreator() internal view { if (!_profileCreatorWhitelisted[msg.sender]) revert Errors.ProfileCreatorNotWhitelisted(); } function getRevision() internal pure virtual override returns (uint256) { return REVISION; } }
@inheritdoc ILensHub
function setState(DataTypes.ProtocolState newState) external override { if (msg.sender != _governance && msg.sender != _emergencyAdmin) revert Errors.NotGovernanceOrEmergencyAdmin(); _setState(newState); }
12,861,937
[ 1, 36, 10093, 467, 48, 773, 8182, 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, 12947, 12, 751, 2016, 18, 5752, 1119, 15907, 13, 3903, 3849, 288, 203, 3639, 309, 261, 3576, 18, 15330, 480, 389, 75, 1643, 82, 1359, 597, 1234, 18, 15330, 480, 389, 351, 24530, 4446, 13, 203, 5411, 15226, 9372, 18, 1248, 43, 1643, 82, 1359, 1162, 1514, 24530, 4446, 5621, 203, 3639, 389, 542, 1119, 12, 2704, 1119, 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 ]
./full_match/5/0xeD4656b74079Ae4dA917b9098E308281872C9768/sources/browser/oops.sol
Function to get value of the string variable
contract methodOverloading { function getValue( string memory _strin) public pure returns(string memory){ return _strin; } function getValue( uint _num) public pure returns(uint){ return _num; } }
11,586,430
[ 1, 2083, 358, 336, 460, 434, 326, 533, 2190, 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, 707, 4851, 15174, 288, 7010, 4202, 203, 565, 445, 2366, 12, 7010, 1377, 533, 3778, 389, 701, 267, 13, 1071, 16618, 1135, 12, 1080, 3778, 15329, 7010, 3639, 327, 389, 701, 267, 31, 7010, 565, 289, 7010, 21281, 565, 445, 2366, 12, 7010, 1377, 2254, 389, 2107, 13, 1071, 16618, 1135, 12, 11890, 15329, 7010, 3639, 327, 389, 2107, 31, 7010, 565, 289, 225, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.4.21 <0.6.0; contract RefrigeratedTransportation { //Set of States enum StateType { Created, InTransit, Completed, OutOfCompliance} enum SensorType { None, Humidity, Temperature } //List of properties StateType public State; int public MinHumidity; int public MaxHumidity; int public MinTemperature; int public MaxTemperature; int public LastSensorUpdateTimestamp; SensorType public ComplianceSensorType; string public ComplianceDetail; bool public ComplianceStatus; int public ComplianceSensorReading; constructor(int minHumidity, int maxHumidity, int minTemperature, int maxTemperature) public { ComplianceStatus = true; ComplianceSensorReading = -1; MinHumidity = minHumidity; MaxHumidity = maxHumidity; MinTemperature = minTemperature; MaxTemperature = maxTemperature; State = StateType.Created; ComplianceDetail = "N/A"; } function IngestTelemetry(int humidity, int temperature, int timestamp) public { LastSensorUpdateTimestamp = timestamp; if (humidity > MaxHumidity || humidity < MinHumidity) { ComplianceSensorType = SensorType.Humidity; ComplianceSensorReading = humidity; ComplianceDetail = "Humidity value out of range."; ComplianceStatus = false; } else if (temperature > MaxTemperature || temperature < MinTemperature) { ComplianceSensorType = SensorType.Temperature; ComplianceSensorReading = temperature; ComplianceDetail = "Temperature value out of range."; ComplianceStatus = false; } if (ComplianceStatus == false) { State = StateType.OutOfCompliance; } } }
Set of StatesList of properties
{ StateType public State; int public MinHumidity; int public MaxHumidity; int public MinTemperature; int public MaxTemperature; int public LastSensorUpdateTimestamp; SensorType public ComplianceSensorType; string public ComplianceDetail; bool public ComplianceStatus; int public ComplianceSensorReading; constructor(int minHumidity, int maxHumidity, int minTemperature, int maxTemperature) public enum StateType { Created, InTransit, Completed, OutOfCompliance} enum SensorType { None, Humidity, Temperature } { ComplianceStatus = true; ComplianceSensorReading = -1; MinHumidity = minHumidity; MaxHumidity = maxHumidity; MinTemperature = minTemperature; MaxTemperature = maxTemperature; State = StateType.Created; ComplianceDetail = "N/A"; } function IngestTelemetry(int humidity, int temperature, int timestamp) public { LastSensorUpdateTimestamp = timestamp; if (humidity > MaxHumidity || humidity < MinHumidity) { ComplianceSensorType = SensorType.Humidity; ComplianceSensorReading = humidity; ComplianceDetail = "Humidity value out of range."; ComplianceStatus = false; } else if (temperature > MaxTemperature || temperature < MinTemperature) { ComplianceSensorType = SensorType.Temperature; ComplianceSensorReading = temperature; ComplianceDetail = "Temperature value out of range."; ComplianceStatus = false; } if (ComplianceStatus == false) { State = StateType.OutOfCompliance; } } function IngestTelemetry(int humidity, int temperature, int timestamp) public { LastSensorUpdateTimestamp = timestamp; if (humidity > MaxHumidity || humidity < MinHumidity) { ComplianceSensorType = SensorType.Humidity; ComplianceSensorReading = humidity; ComplianceDetail = "Humidity value out of range."; ComplianceStatus = false; } else if (temperature > MaxTemperature || temperature < MinTemperature) { ComplianceSensorType = SensorType.Temperature; ComplianceSensorReading = temperature; ComplianceDetail = "Temperature value out of range."; ComplianceStatus = false; } if (ComplianceStatus == false) { State = StateType.OutOfCompliance; } } function IngestTelemetry(int humidity, int temperature, int timestamp) public { LastSensorUpdateTimestamp = timestamp; if (humidity > MaxHumidity || humidity < MinHumidity) { ComplianceSensorType = SensorType.Humidity; ComplianceSensorReading = humidity; ComplianceDetail = "Humidity value out of range."; ComplianceStatus = false; } else if (temperature > MaxTemperature || temperature < MinTemperature) { ComplianceSensorType = SensorType.Temperature; ComplianceSensorReading = temperature; ComplianceDetail = "Temperature value out of range."; ComplianceStatus = false; } if (ComplianceStatus == false) { State = StateType.OutOfCompliance; } } function IngestTelemetry(int humidity, int temperature, int timestamp) public { LastSensorUpdateTimestamp = timestamp; if (humidity > MaxHumidity || humidity < MinHumidity) { ComplianceSensorType = SensorType.Humidity; ComplianceSensorReading = humidity; ComplianceDetail = "Humidity value out of range."; ComplianceStatus = false; } else if (temperature > MaxTemperature || temperature < MinTemperature) { ComplianceSensorType = SensorType.Temperature; ComplianceSensorReading = temperature; ComplianceDetail = "Temperature value out of range."; ComplianceStatus = false; } if (ComplianceStatus == false) { State = StateType.OutOfCompliance; } } }
5,432,471
[ 1, 694, 434, 29577, 682, 434, 1790, 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, 95, 203, 203, 565, 3287, 559, 1071, 225, 3287, 31, 203, 565, 509, 1071, 225, 5444, 44, 379, 24237, 31, 203, 565, 509, 1071, 225, 4238, 44, 379, 24237, 31, 203, 565, 509, 1071, 225, 5444, 1837, 9289, 31, 203, 565, 509, 1071, 225, 4238, 1837, 9289, 31, 203, 565, 509, 1071, 225, 6825, 22294, 1891, 4921, 31, 203, 203, 565, 28903, 559, 1071, 225, 1286, 10671, 22294, 559, 31, 203, 565, 533, 1071, 225, 1286, 10671, 6109, 31, 203, 565, 1426, 1071, 225, 1286, 10671, 1482, 31, 203, 565, 509, 1071, 225, 1286, 10671, 22294, 15714, 31, 203, 203, 565, 3885, 12, 474, 1131, 44, 379, 24237, 16, 509, 943, 44, 379, 24237, 16, 509, 1131, 1837, 9289, 16, 509, 943, 1837, 9289, 13, 1071, 203, 565, 2792, 3287, 559, 288, 12953, 16, 657, 26164, 16, 28722, 16, 18407, 16687, 97, 203, 565, 2792, 28903, 559, 288, 599, 16, 670, 379, 24237, 16, 3955, 9289, 289, 203, 565, 288, 203, 3639, 1286, 10671, 1482, 273, 638, 31, 203, 3639, 1286, 10671, 22294, 15714, 273, 300, 21, 31, 203, 3639, 5444, 44, 379, 24237, 273, 1131, 44, 379, 24237, 31, 203, 3639, 4238, 44, 379, 24237, 273, 943, 44, 379, 24237, 31, 203, 3639, 5444, 1837, 9289, 273, 1131, 1837, 9289, 31, 203, 3639, 4238, 1837, 9289, 273, 943, 1837, 9289, 31, 203, 3639, 3287, 273, 3287, 559, 18, 6119, 31, 203, 3639, 1286, 10671, 6109, 273, 315, 50, 19, 37, 14432, 203, 565, 289, 203, 203, 565, 445, 657, 17592, 56, 20483, 12, 2 ]
./partial_match/42/0xb32b29120aa5a022EB5FF646c277A07c38c71587/sources/TornTest.sol
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract TornTest is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = "TORN"; name = "TornTest"; decimals = 2; _totalSupply = 150000000; balances[0x4d03Cd7EA8ee83a4f8f739515cfb0432920eaf63] = _totalSupply; emit Transfer(address(0), 0x4d03Cd7EA8ee83a4f8f739515cfb0432920eaf63, _totalSupply); } function totalSupply() public override view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public override returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public override 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 override returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public override view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
8,919,283
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 1551, 25444, 1147, 29375, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 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, 16351, 399, 14245, 4709, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 16, 14060, 10477, 288, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 56, 916, 50, 14432, 203, 3639, 508, 273, 315, 56, 14245, 4709, 14432, 203, 3639, 15105, 273, 576, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 4711, 17877, 31, 203, 3639, 324, 26488, 63, 20, 92, 24, 72, 4630, 19728, 27, 41, 37, 28, 1340, 10261, 69, 24, 74, 28, 74, 27, 5520, 25, 3600, 8522, 70, 3028, 1578, 29, 3462, 73, 1727, 4449, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 374, 92, 24, 72, 4630, 19728, 27, 41, 37, 28, 1340, 10261, 69, 24, 74, 28, 74, 27, 5520, 25, 3600, 8522, 70, 3028, 1578, 29, 3462, 73, 1727, 4449, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 3849, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 300, 324, 26488, 63, 2867, 12, 20, 13, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 3849, 1476, 2 ]
pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // @openzeppelin/[email protected] interface IMigratorChef { function migrate(IERC20 token) external returns (IERC20); } // Generator is the Miner of AF. He can make AF and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once AF is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract Generator is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of SUSHIs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accAFPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accAFPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. AFs to distribute per block. uint256 lastRewardBlock; // Last block number that AFs distribution occurs. uint256 accAFPerShare; // Accumulated AFs per share, times 1e12. See below. } // The AF TOKEN! IERC20 public tokenAF; // total mint amount. uint256 public mintReward; uint public constant SUSPEND_MINING_BALANCE = 100000e8; // Dev address. address public devaddr; // Block number when bonus AF period ends. uint256 public bonusEndBlock; // AF tokens created per block. uint256 public tokenAFPerBlock; // Bonus muliplier for early AF makers. uint256 public constant BONUS_MULTIPLIER = 5; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when AF mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event Mint(address indexed to, uint256 amount); constructor( IERC20 _tokenAF, address _devaddr, uint256 _tokenAFPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { tokenAF = _tokenAF; devaddr = _devaddr; tokenAFPerBlock = _tokenAFPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accAFPerShare: 0 })); } // Update the given pool's AF allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Migrate AF token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrateAF() public { require(address(migrator) != address(0), "migrate: no migrator token"); uint256 bal = tokenAF.balanceOf(address(this)); tokenAF.safeApprove(address(migrator), bal); IERC20 newToken = migrator.migrate(tokenAF); require(bal == newToken.balanceOf(address(this)), "migrate: bad"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (tokenAF.balanceOf(address(this)) < SUSPEND_MINING_BALANCE) { return 0; } if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending AFs on frontend. function pendingAF(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accAFPerShare = pool.accAFPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 tokenAFReward = multiplier.mul(tokenAFPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accAFPerShare = accAFPerShare.add(tokenAFReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accAFPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 tokenAFReward = multiplier.mul(tokenAFPerBlock).mul(pool.allocPoint).div(totalAllocPoint); mint(devaddr, tokenAFReward.div(10)); mintReward.add(tokenAFReward); pool.accAFPerShare = pool.accAFPerShare.add(tokenAFReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to Generator for AF rewards. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accAFPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeAFTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accAFPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from Generator. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accAFPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeAFTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accAFPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe AF transfer function, just in case if rounding error causes pool to not have enough AFs. function safeAFTransfer(address _to, uint256 _amount) internal { uint256 AFBal = tokenAF.balanceOf(address(this)); if (_amount > AFBal) { tokenAF.transfer(_to, AFBal); } else { tokenAF.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } function mint(address to, uint256 rewardAmount) private { if (rewardAmount == 0) { emit Mint(to, 0); return; } require(tokenAF.transfer(to, rewardAmount), 'Generator: transfer out of unlocked pool failed'); emit Mint(to, rewardAmount); } }
Safe AF transfer function, just in case if rounding error causes pool to not have enough AFs.
function safeAFTransfer(address _to, uint256 _amount) internal { uint256 AFBal = tokenAF.balanceOf(address(this)); if (_amount > AFBal) { tokenAF.transfer(_to, AFBal); tokenAF.transfer(_to, _amount); } }
5,438,342
[ 1, 9890, 10888, 7412, 445, 16, 2537, 316, 648, 309, 13885, 555, 14119, 2845, 358, 486, 1240, 7304, 10888, 87, 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, 565, 445, 4183, 6799, 5912, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 2713, 288, 203, 3639, 2254, 5034, 10888, 38, 287, 273, 1147, 6799, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 67, 8949, 405, 10888, 38, 287, 13, 288, 203, 5411, 1147, 6799, 18, 13866, 24899, 869, 16, 10888, 38, 287, 1769, 203, 5411, 1147, 6799, 18, 13866, 24899, 869, 16, 389, 8949, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xf2c8F539077c892A8126AaAf5012FB9d154776b4/sources/contracts/PrmntOrigin.sol
Strings.toString(getDuration(tokenId)), 's ease-in-out infinite r1;transform-origin:320px 320px;}@keyframes r1{0%{transform:rotate(0) scale(1)}50%{transform:rotate(180deg) scale(1.4)}}</style>', '<style>g.c{fill:none;animation:', Strings.toString(getDuration(tokenId)), 's ease-in-out infinite r1;transform-origin:320px 320px;}@keyframes r1{0%{transform:rotate(0) scale(1)}50%{transform:rotate(180deg) scale(1.4)}}</style>',
function createArtwork(uint256 tokenId, uint256 hue) public view returns (string memory){ string memory parts = string.concat( " style='background: ", string.concat( 'hsl(', Strings.toString(hue), suffixes[0]), ";'>", generatePaths(7, tokenId, hue), '</svg>'); return parts; '<style>g.c{fill:none;}</style>', }
1,865,446
[ 1, 7957, 18, 10492, 12, 588, 5326, 12, 2316, 548, 13, 3631, 296, 87, 28769, 17, 267, 17, 659, 14853, 436, 21, 31, 6547, 17, 10012, 30, 31273, 4430, 890, 3462, 4430, 31, 97, 36, 856, 10278, 436, 21, 95, 20, 9, 95, 6547, 30, 20342, 12, 20, 13, 3159, 12, 21, 16869, 3361, 9, 95, 6547, 30, 20342, 12, 18278, 9923, 13, 3159, 12, 21, 18, 24, 13, 9090, 1757, 4060, 1870, 16, 2368, 4060, 34, 75, 18, 71, 95, 5935, 30, 6102, 31, 30822, 30, 2187, 8139, 18, 10492, 12, 588, 5326, 12, 2316, 548, 13, 3631, 296, 87, 28769, 17, 267, 17, 659, 14853, 436, 21, 31, 6547, 17, 10012, 30, 31273, 4430, 890, 3462, 4430, 31, 97, 36, 856, 10278, 436, 21, 95, 20, 9, 95, 6547, 30, 20342, 12, 20, 13, 3159, 12, 21, 16869, 3361, 9, 95, 6547, 30, 20342, 12, 18278, 9923, 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, 752, 4411, 1252, 12, 11890, 5034, 1147, 548, 16, 2254, 5034, 16846, 13, 1071, 1476, 1135, 261, 1080, 3778, 15329, 203, 3639, 533, 3778, 2140, 273, 533, 18, 16426, 12, 203, 3639, 315, 2154, 2218, 9342, 30, 3104, 203, 3639, 533, 18, 16426, 12, 203, 5411, 296, 76, 2069, 12, 2187, 7010, 5411, 8139, 18, 10492, 12, 76, 344, 3631, 18333, 63, 20, 65, 3631, 203, 3639, 315, 4359, 2984, 16, 203, 540, 203, 3639, 2103, 4466, 12, 27, 16, 1147, 548, 16, 16846, 3631, 203, 540, 203, 3639, 4357, 11451, 1870, 1769, 203, 3639, 327, 2140, 31, 203, 3639, 2368, 4060, 34, 75, 18, 71, 95, 5935, 30, 6102, 31, 12863, 4060, 1870, 16, 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 ]
//Address: 0xcd820a2f792f429bf95e6d0de909d06110b44123 //Contract name: ReplaySafeSplit //Balance: 0 Ether //Verification Date: 9/4/2016 //Transacion Count: 1 // CODE STARTS HERE contract RequiringFunds { modifier NeedEth () { if (msg.value <= 0 ) throw; _ } } contract AmIOnTheFork { function forked() constant returns(bool); } contract ReplaySafeSplit is RequiringFunds { // address private constant oracleAddress = 0x8128B12cABc6043d94BD3C4d9B9455077Eb18807; // testnet address private constant oracleAddress = 0x2bd2326c993dfaef84f696526064ff22eba5b362; // mainnet // Fork oracle to use AmIOnTheFork amIOnTheFork = AmIOnTheFork(oracleAddress); // Splits the funds into 2 addresses function split(address targetFork, address targetNoFork) NeedEth returns(bool) { // The 2 checks are to ensure that users provide BOTH addresses // and prevent funds to be sent to 0x0 on one fork or the other. if (targetFork == 0) throw; if (targetNoFork == 0) throw; if (amIOnTheFork.forked() // if we are on the fork && targetFork.send(msg.value)) { // send the ETH to the targetFork address return true; } else if (!amIOnTheFork.forked() // if we are NOT on the fork && targetNoFork.send(msg.value)) { // send the ETH to the targetNoFork address return true; } throw; // don't accept value transfer, otherwise it would be trapped. } // Reject value transfers. function() { throw; } }
address private constant oracleAddress = 0x8128B12cABc6043d94BD3C4d9B9455077Eb18807; testnet Fork oracle to use Splits the funds into 2 addresses
contract ReplaySafeSplit is RequiringFunds { AmIOnTheFork amIOnTheFork = AmIOnTheFork(oracleAddress); function split(address targetFork, address targetNoFork) NeedEth returns(bool) { if (targetFork == 0) throw; if (targetNoFork == 0) throw; return true; return true; } }
2,473,653
[ 1, 2867, 3238, 5381, 20865, 1887, 273, 374, 92, 28, 10392, 38, 2138, 71, 2090, 71, 26, 3028, 23, 72, 11290, 18096, 23, 39, 24, 72, 29, 38, 11290, 2539, 20, 4700, 41, 70, 2643, 3672, 27, 31, 377, 1842, 2758, 27599, 20865, 358, 999, 5385, 87, 326, 284, 19156, 1368, 576, 6138, 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, 16351, 868, 1601, 9890, 5521, 353, 868, 372, 11256, 42, 19156, 288, 203, 203, 282, 3986, 45, 1398, 1986, 22662, 2125, 45, 1398, 1986, 22662, 273, 3986, 45, 1398, 1986, 22662, 12, 280, 16066, 1887, 1769, 203, 203, 282, 445, 1416, 12, 2867, 1018, 22662, 16, 1758, 1018, 2279, 22662, 13, 12324, 41, 451, 1135, 12, 6430, 13, 288, 203, 4202, 309, 261, 3299, 22662, 422, 374, 13, 604, 31, 203, 4202, 309, 261, 3299, 2279, 22662, 422, 374, 13, 604, 31, 203, 203, 6647, 327, 638, 31, 203, 6647, 327, 638, 31, 203, 4202, 289, 203, 203, 282, 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 ]
// File: @bancor/contracts-solidity/solidity/contracts/utility/interfaces/IOwned.sol // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; /* Owned contract interface */ interface IOwned { // this function isn't since the compiler emits automatically generated getter functions as external function owner() external view returns (address); function transferOwnership(address _newOwner) external; function acceptOwnership() external; } // File: @bancor/contracts-solidity/solidity/contracts/utility/Owned.sol pragma solidity 0.6.12; /** * @dev Provides support and utilities for contract ownership */ contract Owned is IOwned { address public override owner; address public newOwner; /** * @dev triggered when the owner is updated * * @param _prevOwner previous owner * @param _newOwner new owner */ event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** * @dev initializes a new Owned instance */ constructor() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { _ownerOnly(); _; } // error message binary size optimization function _ownerOnly() internal view { require(msg.sender == owner, "ERR_ACCESS_DENIED"); } /** * @dev allows transferring the contract ownership * the new owner still needs to accept the transfer * can only be called by the contract owner * * @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public override ownerOnly { require(_newOwner != owner, "ERR_SAME_OWNER"); newOwner = _newOwner; } /** * @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() override public { require(msg.sender == newOwner, "ERR_ACCESS_DENIED"); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } // File: @openzeppelin/contracts/math/Math.sol 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); } } // File: @openzeppelin/contracts/math/SafeMath.sol 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) { 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; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol 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); } // File: @openzeppelin/contracts/utils/Address.sol 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) { // 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); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.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 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"); } } } // File: contracts/interfaces/IExecutor.sol pragma solidity 0.6.12; interface IExecutor { function execute( uint256 _id, uint256 _for, uint256 _against, uint256 _quorum ) external; } // File: contracts/BancorGovernance.sol /* ____ __ __ __ _ / __/__ __ ___ / /_ / / ___ / /_ (_)__ __ _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ / /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\ /___/ * Synthetix: YFIRewards.sol * * Docs: https://docs.synthetix.io/ * * * MIT License * =========== * * Copyright (c) 2020 Synthetix * * 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 */ pragma solidity 0.6.12; /** * @title The Bancor Governance Contract * * Big thanks to synthetix / yearn.finance for the initial version! */ contract BancorGovernance is Owned { using SafeMath for uint256; using SafeERC20 for IERC20; uint32 internal constant PPM_RESOLUTION = 1000000; struct Proposal { uint256 id; mapping(address => uint256) votesFor; mapping(address => uint256) votesAgainst; uint256 totalVotesFor; uint256 totalVotesAgainst; uint256 start; // start timestmp; uint256 end; // start + voteDuration uint256 totalAvailableVotes; uint256 quorum; uint256 quorumRequired; bool open; bool executed; address proposer; address executor; string hash; } /** * @notice triggered when a new proposal is created * * @param _id proposal id * @param _start voting start timestamp * @param _duration voting duration * @param _proposer proposal creator * @param _executor contract that will exeecute the proposal once it passes */ event NewProposal( uint256 indexed _id, uint256 _start, uint256 _duration, address _proposer, address _executor ); /** * @notice triggered when voting on a proposal has ended * * @param _id proposal id * @param _for number of votes for the proposal * @param _against number of votes against the proposal * @param _quorumReached true if quorum was reached, false otherwise */ event ProposalFinished( uint256 indexed _id, uint256 _for, uint256 _against, bool _quorumReached ); /** * @notice triggered when a proposal was successfully executed * * @param _id proposal id * @param _executor contract that will execute the proposal once it passes */ event ProposalExecuted(uint256 indexed _id, address indexed _executor); /** * @notice triggered when a stake has been added to the contract * * @param _user staker address * @param _amount staked amount */ event Staked(address indexed _user, uint256 _amount); /** * @notice triggered when a stake has been removed from the contract * * @param _user staker address * @param _amount unstaked amount */ event Unstaked(address indexed _user, uint256 _amount); /** * @notice triggered when a user votes on a proposal * * @param _id proposal id * @param _voter voter addrerss * @param _vote true if the vote is for the proposal, false otherwise * @param _weight number of votes */ event Vote(uint256 indexed _id, address indexed _voter, bool _vote, uint256 _weight); /** * @notice triggered when the quorum is updated * * @param _quorum new quorum */ event QuorumUpdated(uint256 _quorum); /** * @notice triggered when the minimum stake required to create a new proposal is updated * * @param _minimum new minimum */ event NewProposalMinimumUpdated(uint256 _minimum); /** * @notice triggered when the vote duration is updated * * @param _voteDuration new vote duration */ event VoteDurationUpdated(uint256 _voteDuration); /** * @notice triggered when the vote lock duration is updated * * @param _duration new vote lock duration */ event VoteLockDurationUpdated(uint256 _duration); // PROPOSALS // voting duration in seconds uint256 public voteDuration = 3 days; // vote lock in seconds uint256 public voteLockDuration = 3 days; // the fraction of vote lock used to lock voter to avoid rapid unstaking uint256 public constant voteLockFraction = 10; // minimum stake required to propose uint256 public newProposalMinimum = 1e18; // quorum needed for a proposal to pass, default = 20% uint256 public quorum = 200000; // sum of current total votes uint256 public totalVotes; // number of proposals uint256 public proposalCount; // proposals by id mapping(uint256 => Proposal) public proposals; // VOTES // governance token used for votes IERC20 public immutable govToken; // lock duration for each voter stake by voter address mapping(address => uint256) public voteLocks; // number of votes for each user mapping(address => uint256) private votes; /** * @notice used to initialize a new BancorGovernance contract * * @param _govToken token used to represents votes */ constructor(IERC20 _govToken) public { require(address(_govToken) != address(0), "ERR_NO_TOKEN"); govToken = _govToken; } /** * @notice allows execution by staker only */ modifier onlyStaker() { require(votes[msg.sender] > 0, "ERR_NOT_STAKER"); _; } /** * @notice allows execution only when the proposal exists * * @param _id proposal id */ modifier proposalExists(uint256 _id) { Proposal memory proposal = proposals[_id]; require(proposal.start > 0 && proposal.start < block.timestamp, "ERR_INVALID_ID"); _; } /** * @notice allows execution only when the proposal is still open * * @param _id proposal id */ modifier proposalOpen(uint256 _id) { Proposal memory proposal = proposals[_id]; require(proposal.open, "ERR_NOT_OPEN"); _; } /** * @notice allows execution only when the proposal with given id is open * * @param _id proposal id */ modifier proposalNotEnded(uint256 _id) { Proposal memory proposal = proposals[_id]; require(proposal.end >= block.timestamp, "ERR_ENDED"); _; } /** * @notice allows execution only when the proposal with given id has ended * * @param _id proposal id */ modifier proposalEnded(uint256 _id) { Proposal memory proposal = proposals[_id]; require(proposal.end <= block.timestamp, "ERR_NOT_ENDED"); _; } /** * @notice verifies that a value is greater than zero * * @param _value value to check for zero */ modifier greaterThanZero(uint256 _value) { require(_value > 0, "ERR_ZERO_VALUE"); _; } /** * @notice Updates the vote lock on the sender * * @param _proposalEnd proposal end time */ function updateVoteLock(uint256 _proposalEnd) private onlyStaker { voteLocks[msg.sender] = Math.max( voteLocks[msg.sender], Math.max(_proposalEnd, voteLockDuration.add(block.timestamp)) ); } /** * @notice does the common vote finalization * * @param _id the id of the proposal to vote * @param _for is this vote for or against the proposal */ function vote(uint256 _id, bool _for) private onlyStaker proposalExists(_id) proposalOpen(_id) proposalNotEnded(_id) { Proposal storage proposal = proposals[_id]; if (_for) { uint256 votesAgainst = proposal.votesAgainst[msg.sender]; // do we have against votes for this sender? if (votesAgainst > 0) { // yes, remove the against votes first proposal.totalVotesAgainst = proposal.totalVotesAgainst.sub(votesAgainst); proposal.votesAgainst[msg.sender] = 0; } } else { // get against votes for this sender uint256 votesFor = proposal.votesFor[msg.sender]; // do we have for votes for this sender? if (votesFor > 0) { proposal.totalVotesFor = proposal.totalVotesFor.sub(votesFor); proposal.votesFor[msg.sender] = 0; } } // calculate voting power in case voting against twice uint256 voteAmount = votesOf(msg.sender).sub( _for ? proposal.votesFor[msg.sender] : proposal.votesAgainst[msg.sender] ); if (_for) { // increase total for votes of the proposal proposal.totalVotesFor = proposal.totalVotesFor.add(voteAmount); // set for votes to the votes of the sender proposal.votesFor[msg.sender] = votesOf(msg.sender); } else { // increase total against votes of the proposal proposal.totalVotesAgainst = proposal.totalVotesAgainst.add(voteAmount); // set against votes to the votes of the sender proposal.votesAgainst[msg.sender] = votesOf(msg.sender); } // update total votes available on the proposal proposal.totalAvailableVotes = totalVotes; // recalculate quorum based on overall votes proposal.quorum = calculateQuorumRatio(proposal); // update vote lock updateVoteLock(proposal.end); // emit vote event emit Vote(proposal.id, msg.sender, _for, voteAmount); } /** * @notice returns the quorum ratio of a proposal * * @param _proposal proposal * @return quorum ratio */ function calculateQuorumRatio(Proposal memory _proposal) internal view returns (uint256) { // calculate overall votes uint256 totalProposalVotes = _proposal.totalVotesFor.add(_proposal.totalVotesAgainst); return totalProposalVotes.mul(PPM_RESOLUTION).div(totalVotes); } /** * @notice removes the caller's entire stake */ function exit() external { unstake(votesOf(msg.sender)); } /** * @notice returns the voting stats of a proposal * * @param _id proposal id * @return votes for ratio * @return votes against ratio * @return quorum ratio */ function proposalStats(uint256 _id) public view returns ( uint256, uint256, uint256 ) { Proposal memory proposal = proposals[_id]; uint256 forRatio = proposal.totalVotesFor; uint256 againstRatio = proposal.totalVotesAgainst; // calculate overall total votes uint256 totalProposalVotes = forRatio.add(againstRatio); // calculate for votes ratio forRatio = forRatio.mul(PPM_RESOLUTION).div(totalProposalVotes); // calculate against votes ratio againstRatio = againstRatio.mul(PPM_RESOLUTION).div(totalProposalVotes); // calculate quorum ratio uint256 quorumRatio = totalProposalVotes.mul(PPM_RESOLUTION).div( proposal.totalAvailableVotes ); return (forRatio, againstRatio, quorumRatio); } /** * @notice returns the voting power of a given address * * @param _voter voter address * @return votes of given address */ function votesOf(address _voter) public view returns (uint256) { return votes[_voter]; } /** * @notice returns the voting power of a given address against a given proposal * * @param _voter voter address * @param _id proposal id * @return votes of given address against given proposal */ function votesAgainstOf(address _voter, uint256 _id) public view returns (uint256) { return proposals[_id].votesAgainst[_voter]; } /** * @notice returns the voting power of a given address for a given proposal * * @param _voter voter address * @param _id proposal id * @return votes of given address for given proposal */ function votesForOf(address _voter, uint256 _id) public view returns (uint256) { return proposals[_id].votesFor[_voter]; } /** * @notice updates the quorum needed for proposals to pass * * @param _quorum required quorum */ function setQuorum(uint256 _quorum) public ownerOnly greaterThanZero(_quorum) { // check quorum for not being above 100 require(_quorum <= PPM_RESOLUTION, "ERR_QUORUM_TOO_HIGH"); quorum = _quorum; emit QuorumUpdated(_quorum); } /** * @notice updates the minimum stake required to create a new proposal * * @param _minimum minimum stake */ function setNewProposalMinimum(uint256 _minimum) public ownerOnly greaterThanZero(_minimum) { require(_minimum <= govToken.totalSupply(), "ERR_EXCEEDS_TOTAL_SUPPLY"); newProposalMinimum = _minimum; emit NewProposalMinimumUpdated(_minimum); } /** * @notice updates the proposals voting duration * * @param _voteDuration vote duration */ function setVoteDuration(uint256 _voteDuration) public ownerOnly greaterThanZero(_voteDuration) { voteDuration = _voteDuration; emit VoteDurationUpdated(_voteDuration); } /** * @notice updates the post vote lock duration * * @param _duration new vote lock duration */ function setVoteLockDuration(uint256 _duration) public ownerOnly greaterThanZero(_duration) { voteLockDuration = _duration; emit VoteLockDurationUpdated(_duration); } /** * @notice creates a new proposal * * @param _executor the address of the contract that will execute the proposal after it passes * @param _hash ipfs hash of the proposal description */ function propose(address _executor, string memory _hash) public { require(votesOf(msg.sender) > newProposalMinimum, "ERR_INSUFFICIENT_STAKE"); uint256 id = proposalCount; // increment proposal count so next proposal gets the next higher id proposalCount = proposalCount.add(1); // create new proposal Proposal memory proposal = Proposal({ id: id, proposer: msg.sender, totalVotesFor: 0, totalVotesAgainst: 0, start: block.timestamp, end: voteDuration.add(block.timestamp), executor: _executor, hash: _hash, totalAvailableVotes: totalVotes, quorum: 0, quorumRequired: quorum, open: true, executed: false }); proposals[id] = proposal; // lock proposer updateVoteLock(proposal.end); // emit proposal event emit NewProposal(id, proposal.start, voteDuration, proposal.proposer, proposal.executor); } /** * @notice executes a proposal * * @param _id id of the proposal to execute */ function execute(uint256 _id) public proposalExists(_id) proposalEnded(_id) { // check for executed status require(!proposals[_id].executed, "ERR_ALREADY_EXECUTED"); // get voting info of proposal (uint256 forRatio, uint256 againstRatio, uint256 quorumRatio) = proposalStats(_id); // check proposal state require(quorumRatio >= proposals[_id].quorumRequired, "ERR_NO_QUORUM"); // if the proposal is still open if (proposals[_id].open) { // tally votes tallyVotes(_id); } // set executed proposals[_id].executed = true; // do execution on the contract to be executed // note that this is a safe call as it was part of the proposal that was voted on IExecutor(proposals[_id].executor).execute(_id, forRatio, againstRatio, quorumRatio); // emit proposal executed event emit ProposalExecuted(_id, proposals[_id].executor); } /** * @notice tallies votes of proposal with given id * * @param _id id of the proposal to tally votes for */ function tallyVotes(uint256 _id) public proposalExists(_id) proposalOpen(_id) proposalEnded(_id) { // get voting info of proposal (uint256 forRatio, uint256 againstRatio, ) = proposalStats(_id); // do we have a quorum? bool quorumReached = proposals[_id].quorum >= proposals[_id].quorumRequired; // close proposal proposals[_id].open = false; // emit proposal finished event emit ProposalFinished(_id, forRatio, againstRatio, quorumReached); } /** * @notice stakes vote tokens * * @param _amount amount of vote tokens to stake */ function stake(uint256 _amount) public greaterThanZero(_amount) { // increase vote power votes[msg.sender] = votesOf(msg.sender).add(_amount); // increase total votes totalVotes = totalVotes.add(_amount); // transfer tokens to this contract govToken.safeTransferFrom(msg.sender, address(this), _amount); // lock staker to avoid flashloans messing around with total votes voteLocks[msg.sender] = Math.max( voteLocks[msg.sender], Math.max(voteLockDuration.div(voteLockFraction), 10 minutes).add(block.timestamp) ); // emit staked event emit Staked(msg.sender, _amount); } /** * @notice unstakes vote tokens * * @param _amount amount of vote tokens to unstake */ function unstake(uint256 _amount) public greaterThanZero(_amount) { require(voteLocks[msg.sender] < block.timestamp, "ERR_LOCKED"); // reduce votes for user votes[msg.sender] = votesOf(msg.sender).sub(_amount); // reduce total votes totalVotes = totalVotes.sub(_amount); // transfer tokens back govToken.safeTransfer(msg.sender, _amount); // emit unstaked event emit Unstaked(msg.sender, _amount); } /** * @notice votes for a proposal * * @param _id id of the proposal to vote for */ function voteFor(uint256 _id) public { vote(_id, true); } /** * @notice votes against a proposal * * @param _id id of the proposal to vote against */ function voteAgainst(uint256 _id) public { vote(_id, false); } }
* @title The Bancor Governance Contract Big thanks to synthetix / yearn.finance for the initial version!/
contract BancorGovernance is Owned { using SafeMath for uint256; using SafeERC20 for IERC20; uint32 internal constant PPM_RESOLUTION = 1000000; ____ __ __ __ _ pragma solidity 0.6.12; struct Proposal { uint256 id; mapping(address => uint256) votesFor; mapping(address => uint256) votesAgainst; uint256 totalVotesFor; uint256 totalVotesAgainst; uint256 totalAvailableVotes; uint256 quorum; uint256 quorumRequired; bool open; bool executed; address proposer; address executor; string hash; } uint256 indexed _id, uint256 _start, uint256 _duration, address _proposer, address _executor ); uint256 indexed _id, uint256 _for, uint256 _against, bool _quorumReached ); event NewProposal( event ProposalFinished( event ProposalExecuted(uint256 indexed _id, address indexed _executor); event Staked(address indexed _user, uint256 _amount); event Unstaked(address indexed _user, uint256 _amount); event Vote(uint256 indexed _id, address indexed _voter, bool _vote, uint256 _weight); event QuorumUpdated(uint256 _quorum); event NewProposalMinimumUpdated(uint256 _minimum); event VoteDurationUpdated(uint256 _voteDuration); event VoteLockDurationUpdated(uint256 _duration); uint256 public voteDuration = 3 days; uint256 public voteLockDuration = 3 days; uint256 public constant voteLockFraction = 10; uint256 public newProposalMinimum = 1e18; uint256 public quorum = 200000; uint256 public totalVotes; uint256 public proposalCount; mapping(uint256 => Proposal) public proposals; IERC20 public immutable govToken; mapping(address => uint256) public voteLocks; mapping(address => uint256) private votes; constructor(IERC20 _govToken) public { require(address(_govToken) != address(0), "ERR_NO_TOKEN"); govToken = _govToken; } modifier onlyStaker() { require(votes[msg.sender] > 0, "ERR_NOT_STAKER"); _; } modifier proposalExists(uint256 _id) { Proposal memory proposal = proposals[_id]; require(proposal.start > 0 && proposal.start < block.timestamp, "ERR_INVALID_ID"); _; } modifier proposalOpen(uint256 _id) { Proposal memory proposal = proposals[_id]; require(proposal.open, "ERR_NOT_OPEN"); _; } modifier proposalNotEnded(uint256 _id) { Proposal memory proposal = proposals[_id]; require(proposal.end >= block.timestamp, "ERR_ENDED"); _; } modifier proposalEnded(uint256 _id) { Proposal memory proposal = proposals[_id]; require(proposal.end <= block.timestamp, "ERR_NOT_ENDED"); _; } modifier greaterThanZero(uint256 _value) { require(_value > 0, "ERR_ZERO_VALUE"); _; } function updateVoteLock(uint256 _proposalEnd) private onlyStaker { voteLocks[msg.sender] = Math.max( voteLocks[msg.sender], Math.max(_proposalEnd, voteLockDuration.add(block.timestamp)) ); } function vote(uint256 _id, bool _for) private onlyStaker proposalExists(_id) proposalOpen(_id) proposalNotEnded(_id) { Proposal storage proposal = proposals[_id]; if (_for) { uint256 votesAgainst = proposal.votesAgainst[msg.sender]; if (votesAgainst > 0) { proposal.totalVotesAgainst = proposal.totalVotesAgainst.sub(votesAgainst); proposal.votesAgainst[msg.sender] = 0; } if (votesFor > 0) { proposal.totalVotesFor = proposal.totalVotesFor.sub(votesFor); proposal.votesFor[msg.sender] = 0; } } _for ? proposal.votesFor[msg.sender] : proposal.votesAgainst[msg.sender] ); if (_for) { proposal.totalVotesFor = proposal.totalVotesFor.add(voteAmount); proposal.votesFor[msg.sender] = votesOf(msg.sender); proposal.totalVotesAgainst = proposal.totalVotesAgainst.add(voteAmount); proposal.votesAgainst[msg.sender] = votesOf(msg.sender); } } function vote(uint256 _id, bool _for) private onlyStaker proposalExists(_id) proposalOpen(_id) proposalNotEnded(_id) { Proposal storage proposal = proposals[_id]; if (_for) { uint256 votesAgainst = proposal.votesAgainst[msg.sender]; if (votesAgainst > 0) { proposal.totalVotesAgainst = proposal.totalVotesAgainst.sub(votesAgainst); proposal.votesAgainst[msg.sender] = 0; } if (votesFor > 0) { proposal.totalVotesFor = proposal.totalVotesFor.sub(votesFor); proposal.votesFor[msg.sender] = 0; } } _for ? proposal.votesFor[msg.sender] : proposal.votesAgainst[msg.sender] ); if (_for) { proposal.totalVotesFor = proposal.totalVotesFor.add(voteAmount); proposal.votesFor[msg.sender] = votesOf(msg.sender); proposal.totalVotesAgainst = proposal.totalVotesAgainst.add(voteAmount); proposal.votesAgainst[msg.sender] = votesOf(msg.sender); } } function vote(uint256 _id, bool _for) private onlyStaker proposalExists(_id) proposalOpen(_id) proposalNotEnded(_id) { Proposal storage proposal = proposals[_id]; if (_for) { uint256 votesAgainst = proposal.votesAgainst[msg.sender]; if (votesAgainst > 0) { proposal.totalVotesAgainst = proposal.totalVotesAgainst.sub(votesAgainst); proposal.votesAgainst[msg.sender] = 0; } if (votesFor > 0) { proposal.totalVotesFor = proposal.totalVotesFor.sub(votesFor); proposal.votesFor[msg.sender] = 0; } } _for ? proposal.votesFor[msg.sender] : proposal.votesAgainst[msg.sender] ); if (_for) { proposal.totalVotesFor = proposal.totalVotesFor.add(voteAmount); proposal.votesFor[msg.sender] = votesOf(msg.sender); proposal.totalVotesAgainst = proposal.totalVotesAgainst.add(voteAmount); proposal.votesAgainst[msg.sender] = votesOf(msg.sender); } } } else { uint256 votesFor = proposal.votesFor[msg.sender]; function vote(uint256 _id, bool _for) private onlyStaker proposalExists(_id) proposalOpen(_id) proposalNotEnded(_id) { Proposal storage proposal = proposals[_id]; if (_for) { uint256 votesAgainst = proposal.votesAgainst[msg.sender]; if (votesAgainst > 0) { proposal.totalVotesAgainst = proposal.totalVotesAgainst.sub(votesAgainst); proposal.votesAgainst[msg.sender] = 0; } if (votesFor > 0) { proposal.totalVotesFor = proposal.totalVotesFor.sub(votesFor); proposal.votesFor[msg.sender] = 0; } } _for ? proposal.votesFor[msg.sender] : proposal.votesAgainst[msg.sender] ); if (_for) { proposal.totalVotesFor = proposal.totalVotesFor.add(voteAmount); proposal.votesFor[msg.sender] = votesOf(msg.sender); proposal.totalVotesAgainst = proposal.totalVotesAgainst.add(voteAmount); proposal.votesAgainst[msg.sender] = votesOf(msg.sender); } } uint256 voteAmount = votesOf(msg.sender).sub( function vote(uint256 _id, bool _for) private onlyStaker proposalExists(_id) proposalOpen(_id) proposalNotEnded(_id) { Proposal storage proposal = proposals[_id]; if (_for) { uint256 votesAgainst = proposal.votesAgainst[msg.sender]; if (votesAgainst > 0) { proposal.totalVotesAgainst = proposal.totalVotesAgainst.sub(votesAgainst); proposal.votesAgainst[msg.sender] = 0; } if (votesFor > 0) { proposal.totalVotesFor = proposal.totalVotesFor.sub(votesFor); proposal.votesFor[msg.sender] = 0; } } _for ? proposal.votesFor[msg.sender] : proposal.votesAgainst[msg.sender] ); if (_for) { proposal.totalVotesFor = proposal.totalVotesFor.add(voteAmount); proposal.votesFor[msg.sender] = votesOf(msg.sender); proposal.totalVotesAgainst = proposal.totalVotesAgainst.add(voteAmount); proposal.votesAgainst[msg.sender] = votesOf(msg.sender); } } } else { proposal.totalAvailableVotes = totalVotes; proposal.quorum = calculateQuorumRatio(proposal); updateVoteLock(proposal.end); emit Vote(proposal.id, msg.sender, _for, voteAmount); function calculateQuorumRatio(Proposal memory _proposal) internal view returns (uint256) { uint256 totalProposalVotes = _proposal.totalVotesFor.add(_proposal.totalVotesAgainst); return totalProposalVotes.mul(PPM_RESOLUTION).div(totalVotes); } function exit() external { unstake(votesOf(msg.sender)); } function proposalStats(uint256 _id) public view returns ( uint256, uint256, uint256 ) { Proposal memory proposal = proposals[_id]; uint256 forRatio = proposal.totalVotesFor; uint256 againstRatio = proposal.totalVotesAgainst; uint256 totalProposalVotes = forRatio.add(againstRatio); forRatio = forRatio.mul(PPM_RESOLUTION).div(totalProposalVotes); againstRatio = againstRatio.mul(PPM_RESOLUTION).div(totalProposalVotes); uint256 quorumRatio = totalProposalVotes.mul(PPM_RESOLUTION).div( proposal.totalAvailableVotes ); return (forRatio, againstRatio, quorumRatio); } function votesOf(address _voter) public view returns (uint256) { return votes[_voter]; } function votesAgainstOf(address _voter, uint256 _id) public view returns (uint256) { return proposals[_id].votesAgainst[_voter]; } function votesForOf(address _voter, uint256 _id) public view returns (uint256) { return proposals[_id].votesFor[_voter]; } function setQuorum(uint256 _quorum) public ownerOnly greaterThanZero(_quorum) { require(_quorum <= PPM_RESOLUTION, "ERR_QUORUM_TOO_HIGH"); quorum = _quorum; emit QuorumUpdated(_quorum); } function setNewProposalMinimum(uint256 _minimum) public ownerOnly greaterThanZero(_minimum) { require(_minimum <= govToken.totalSupply(), "ERR_EXCEEDS_TOTAL_SUPPLY"); newProposalMinimum = _minimum; emit NewProposalMinimumUpdated(_minimum); } function setVoteDuration(uint256 _voteDuration) public ownerOnly greaterThanZero(_voteDuration) { voteDuration = _voteDuration; emit VoteDurationUpdated(_voteDuration); } function setVoteLockDuration(uint256 _duration) public ownerOnly greaterThanZero(_duration) { voteLockDuration = _duration; emit VoteLockDurationUpdated(_duration); } function propose(address _executor, string memory _hash) public { require(votesOf(msg.sender) > newProposalMinimum, "ERR_INSUFFICIENT_STAKE"); uint256 id = proposalCount; proposalCount = proposalCount.add(1); Proposal memory proposal = Proposal({ id: id, proposer: msg.sender, totalVotesFor: 0, totalVotesAgainst: 0, start: block.timestamp, end: voteDuration.add(block.timestamp), executor: _executor, hash: _hash, totalAvailableVotes: totalVotes, quorum: 0, quorumRequired: quorum, open: true, executed: false }); proposals[id] = proposal; } function propose(address _executor, string memory _hash) public { require(votesOf(msg.sender) > newProposalMinimum, "ERR_INSUFFICIENT_STAKE"); uint256 id = proposalCount; proposalCount = proposalCount.add(1); Proposal memory proposal = Proposal({ id: id, proposer: msg.sender, totalVotesFor: 0, totalVotesAgainst: 0, start: block.timestamp, end: voteDuration.add(block.timestamp), executor: _executor, hash: _hash, totalAvailableVotes: totalVotes, quorum: 0, quorumRequired: quorum, open: true, executed: false }); proposals[id] = proposal; } updateVoteLock(proposal.end); emit NewProposal(id, proposal.start, voteDuration, proposal.proposer, proposal.executor); function execute(uint256 _id) public proposalExists(_id) proposalEnded(_id) { require(!proposals[_id].executed, "ERR_ALREADY_EXECUTED"); (uint256 forRatio, uint256 againstRatio, uint256 quorumRatio) = proposalStats(_id); require(quorumRatio >= proposals[_id].quorumRequired, "ERR_NO_QUORUM"); if (proposals[_id].open) { tallyVotes(_id); } } function execute(uint256 _id) public proposalExists(_id) proposalEnded(_id) { require(!proposals[_id].executed, "ERR_ALREADY_EXECUTED"); (uint256 forRatio, uint256 againstRatio, uint256 quorumRatio) = proposalStats(_id); require(quorumRatio >= proposals[_id].quorumRequired, "ERR_NO_QUORUM"); if (proposals[_id].open) { tallyVotes(_id); } } proposals[_id].executed = true; IExecutor(proposals[_id].executor).execute(_id, forRatio, againstRatio, quorumRatio); emit ProposalExecuted(_id, proposals[_id].executor); function tallyVotes(uint256 _id) public proposalExists(_id) proposalOpen(_id) proposalEnded(_id) { (uint256 forRatio, uint256 againstRatio, ) = proposalStats(_id); bool quorumReached = proposals[_id].quorum >= proposals[_id].quorumRequired; proposals[_id].open = false; emit ProposalFinished(_id, forRatio, againstRatio, quorumReached); } function stake(uint256 _amount) public greaterThanZero(_amount) { votes[msg.sender] = votesOf(msg.sender).add(_amount); totalVotes = totalVotes.add(_amount); govToken.safeTransferFrom(msg.sender, address(this), _amount); voteLocks[msg.sender] = Math.max( voteLocks[msg.sender], Math.max(voteLockDuration.div(voteLockFraction), 10 minutes).add(block.timestamp) ); emit Staked(msg.sender, _amount); } function unstake(uint256 _amount) public greaterThanZero(_amount) { require(voteLocks[msg.sender] < block.timestamp, "ERR_LOCKED"); votes[msg.sender] = votesOf(msg.sender).sub(_amount); totalVotes = totalVotes.sub(_amount); govToken.safeTransfer(msg.sender, _amount); emit Unstaked(msg.sender, _amount); } function voteFor(uint256 _id) public { vote(_id, true); } function voteAgainst(uint256 _id) public { vote(_id, false); } }
13,465,036
[ 1, 1986, 605, 304, 3850, 611, 1643, 82, 1359, 13456, 4454, 286, 19965, 358, 6194, 451, 278, 697, 342, 677, 73, 1303, 18, 926, 1359, 364, 326, 2172, 1177, 5, 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, 16351, 605, 304, 3850, 43, 1643, 82, 1359, 353, 14223, 11748, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 2254, 1578, 2713, 5381, 453, 12728, 67, 17978, 13269, 273, 15088, 31, 203, 203, 203, 282, 19608, 67, 5411, 1001, 282, 1001, 3639, 1001, 282, 389, 203, 683, 9454, 18035, 560, 374, 18, 26, 18, 2138, 31, 203, 565, 1958, 19945, 288, 203, 3639, 2254, 5034, 612, 31, 203, 3639, 2874, 12, 2867, 516, 2254, 5034, 13, 19588, 1290, 31, 203, 3639, 2874, 12, 2867, 516, 2254, 5034, 13, 19588, 23530, 334, 31, 203, 3639, 2254, 5034, 2078, 29637, 1290, 31, 203, 3639, 2254, 5034, 2078, 29637, 23530, 334, 31, 203, 3639, 2254, 5034, 2078, 5268, 29637, 31, 203, 3639, 2254, 5034, 31854, 31, 203, 3639, 2254, 5034, 31854, 3705, 31, 203, 3639, 1426, 1696, 31, 203, 3639, 1426, 7120, 31, 203, 3639, 1758, 450, 5607, 31, 203, 3639, 1758, 6601, 31, 203, 3639, 533, 1651, 31, 203, 565, 289, 203, 203, 3639, 2254, 5034, 8808, 389, 350, 16, 203, 3639, 2254, 5034, 389, 1937, 16, 203, 3639, 2254, 5034, 389, 8760, 16, 203, 3639, 1758, 389, 685, 5607, 16, 203, 3639, 1758, 389, 21097, 203, 565, 11272, 203, 203, 3639, 2254, 5034, 8808, 389, 350, 16, 203, 3639, 2254, 5034, 389, 1884, 16, 203, 3639, 2254, 5034, 389, 23095, 334, 16, 203, 3639, 1426, 389, 372, 16105, 23646, 203, 565, 11272, 203, 203, 203, 203, 203, 2 ]
./partial_match/42/0xbe983c68C821bC431dDD98bD35E4dFdd42914A02/sources/Defi99Core.sol
@notice The portion of defi99Rate that each market currently receives
mapping(address => uint) public defi99Speeds;
3,421,302
[ 1, 1986, 14769, 434, 1652, 77, 2733, 4727, 716, 1517, 13667, 4551, 17024, 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, 2874, 12, 2867, 516, 2254, 13, 1071, 1652, 77, 2733, 16562, 87, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.9; // Goals of Staking V2 // 1. Stake RandomWalkNFT, Spiral, Crystals, SPIRALBITS and IMPISH // 2. Allow Crystals to grow - both size and target symmetry // 3. Allow Spirals to claim win if Spiral game ends // 4. Allow listing on marketplace while staked // A note on how TokenIDs work. // TokenIDs stored inside the contract have to be >1M // 1M+ -> RandomWalkNFT // 2M+ -> Spiral // 3M+ -> Staked Crystal that is growing // 4M+ -> Fully grown crystal that is earning SPIRALBITS import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./ImpishCrystal.sol"; import "./ImpishSpiral.sol"; import "./SpiralBits.sol"; // import "hardhat/console.sol"; abstract contract IRPS { function commit( bytes32 commitment, address player, uint32[] calldata crystalIDs ) external virtual; } contract StakingV2 is IERC721ReceiverUpgradeable, ReentrancyGuardUpgradeable, OwnableUpgradeable { // Since this is an upgradable implementation, the storage layout is important. // Please be careful changing variable positions when upgrading. // Global reward for all SPIRALBITS staked per second, across ALL staked SpiralBits uint256 public SPIRALBITS_STAKING_EMISSION_PER_SEC; // Global reward for all IMPISH staked per second, across ALL staked IMPISH uint256 public IMPISH_STAKING_EMISSION_PER_SEC; // How many SpiralBits per second are awarded to a staked spiral // 0.167 SPIRALBITS per second. (10 SPIRALBITS per 60 seconds) uint256 public SPIRALBITS_PER_SECOND_PER_SPIRAL; // How many SpiralBits per second are awarded to a staked RandomWalkNFTs // 0.0167 SPIRALBITS per second. (1 SPIRALBITS per 60 seconds) uint256 public SPIRALBITS_PER_SECOND_PER_RW; // How many SpiralBits per second are awarded to a staked, fully grown // spiral. 0.0835 SPIRALBITS per second (5 SPIRALBITS per 60 seconds) uint256 public SPIRALBITS_PER_SECOND_PER_CRYSTAL; // We're staking this NFT in this contract IERC721 public randomWalkNFT; ImpishSpiral public impishspiral; ImpishCrystal public crystals; // The token that is being issued for staking SpiralBits public spiralbits; // The Impish Token IERC20 public impish; struct RewardEpoch { uint32 epochDurationSec; // Total seconds that this epoch lasted uint96 totalSpiralBitsStaked; // Total SPIRALBITS staked across all accounts in whole uints for this Epoch uint96 totalImpishStaked; // Total IMPISH tokens staked across all accounts in whole units for this Epoch } RewardEpoch[] public epochs; // List of epochs uint32 public lastEpochTime; // Last epoch ended at this time struct StakedNFTAndTokens { uint16 numRWStaked; uint16 numSpiralsStaked; uint16 numGrowingCrystalsStaked; uint16 numFullCrystalsStaked; uint32 lastClaimEpoch; // Last Epoch number the rewards were accumulated into claimedSpiralBits. Cannot be 0. uint96 spiralBitsStaked; // Total number of SPIRALBITS staked uint96 impishStaked; // Total number of IMPISH tokens staked uint96 claimedSpiralBits; // Already claimed (but not withdrawn) spiralBits before lastClaimTime mapping(uint256 => uint256) ownedTokens; // index => tokenId } struct TokenIdInfo { uint256 ownedTokensIndex; address owner; } // Mapping of Contract TokenID => Address that staked it. mapping(uint256 => TokenIdInfo) public stakedTokenOwners; // Address that staked the token => Token Accounting mapping(address => StakedNFTAndTokens) public stakedNFTsAndTokens; mapping(uint32 => uint8) public crystalTargetSyms; // V2 fields // They have to be at the end, because we don't want to overwrite the storage address public rps; // Upgradable contracts use initialize instead of constructors function initialize(address _crystals) public initializer { // Call super initializers __Ownable_init(); __ReentrancyGuard_init(); SPIRALBITS_STAKING_EMISSION_PER_SEC = 4 ether; IMPISH_STAKING_EMISSION_PER_SEC = 1 ether; SPIRALBITS_PER_SECOND_PER_SPIRAL = 0.167 ether * 1.1; // 10% bonus SPIRALBITS_PER_SECOND_PER_RW = 0.0167 ether * 1.8; // 80% bonus SPIRALBITS_PER_SECOND_PER_CRYSTAL = 0.0835 ether; crystals = ImpishCrystal(_crystals); impishspiral = ImpishSpiral(crystals.spirals()); randomWalkNFT = IERC721(impishspiral._rwNFT()); spiralbits = SpiralBits(crystals.SpiralBits()); impish = IERC20(impishspiral._impishDAO()); // To make accounting easier, we put a dummy epoch here epochs.push(RewardEpoch({epochDurationSec: 0, totalSpiralBitsStaked: 0, totalImpishStaked: 0})); // Authorize spiralbits to be spent from this contact by the Crystals contracts, used to grow crystals spiralbits.approve(_crystals, 2_000_000_000 ether); lastEpochTime = uint32(block.timestamp); } function stakeSpiralBits(uint256 amount) external { stakeSpiralBitsForOwner(amount, msg.sender); } function stakeSpiralBitsForOwner(uint256 amount, address owner) public nonReentrant { require(amount > 0, "Need SPIRALBITS"); // Update the owner's rewards. The newly added epoch doesn't matter, because it's duration is 0. // This has to be done before _updateRewards(owner); // Transfer the SpiralBits in. If amount is bad or user doesn't have enough tokens, this will fail. spiralbits.transferFrom(msg.sender, address(this), amount); // Spiralbits accounting stakedNFTsAndTokens[owner].spiralBitsStaked += uint96(amount); } function unstakeSpiralBits(bool claimReward) external nonReentrant { uint256 amount = stakedNFTsAndTokens[msg.sender].spiralBitsStaked; require(amount > 0, "NoSPIRALBITSToUnstake"); // Update the owner's rewards first. This also updates the current epoch, since nothing has changed yet. _updateRewards(msg.sender); // Impish accounting stakedNFTsAndTokens[msg.sender].spiralBitsStaked = 0; // Transfer Spiralbits out. spiralbits.transfer(msg.sender, amount); if (claimReward) { _claimRewards(msg.sender); } } function stakeImpish(uint256 amount) external { stakeImpishForOwner(amount, msg.sender); } function stakeImpishForOwner(uint256 amount, address owner) public nonReentrant { require(amount > 0, "Need IMPISH"); // Update the owner's rewards first. This also updates the current epoch, since nothing has changed yet. _updateRewards(owner); // Transfer the SpiralBits in. If amount is bad or user doesn't have enoug htokens, this will fail. impish.transferFrom(msg.sender, address(this), amount); // Impish accounting stakedNFTsAndTokens[owner].impishStaked += uint96(amount); } function unstakeImpish(bool claimReward) external nonReentrant { uint256 amount = stakedNFTsAndTokens[msg.sender].impishStaked; require(amount > 0, "No IMPISH to Unstake"); // Update the owner's rewards first. This also updates the current epoch, since nothing has changed yet. _updateRewards(msg.sender); // Impish accounting stakedNFTsAndTokens[msg.sender].impishStaked = 0; // Transfer impish out. impish.transfer(msg.sender, amount); if (claimReward) { _claimRewards(msg.sender); } } function stakeNFTsForOwner(uint32[] calldata contractTokenIds, address owner) external nonReentrant { // Update the owner's rewards first. This also updates the current epoch, since nothing has changed yet. _updateRewards(owner); for (uint256 i = 0; i < contractTokenIds.length; i++) { require(contractTokenIds[i] > 1_000_000, "UseContractTokenIDs"); uint32 nftType = contractTokenIds[i] / 1_000_000; uint32 tokenId = contractTokenIds[i] % 1_000_000; if (nftType == 1) { _stakeNFT(randomWalkNFT, owner, uint256(tokenId), 1_000_000); // Add this RWNFT to the staked struct stakedNFTsAndTokens[owner].numRWStaked += 1; } else if (nftType == 2) { _stakeNFT(impishspiral, owner, uint256(tokenId), 2_000_000); // Add this spiral to the staked struct stakedNFTsAndTokens[owner].numSpiralsStaked += 1; } else if (nftType == 3) { // Crystals that are growing _stakeNFT(crystals, owner, uint256(tokenId), 3_000_000); // Add this crystal (Growing) to the staked struct stakedNFTsAndTokens[owner].numGrowingCrystalsStaked += 1; } else if (nftType == 4) { // Crystals that are fully grown (uint8 currentCrystalSize, , , , ) = crystals.crystals(tokenId); require(currentCrystalSize == 100, "CrystalNotFullyGrown"); _stakeNFT(crystals, owner, uint256(tokenId), 4_000_000); // Add this crystal (fully grown) to the staked struct stakedNFTsAndTokens[owner].numFullCrystalsStaked += 1; } else { revert("InvalidNFTType"); } } } function unstakeNFTs(uint32[] calldata contractTokenIds, bool claim) external nonReentrant { // Update the owner's rewards first. This also updates the current epoch. _updateRewards(msg.sender); for (uint256 i = 0; i < contractTokenIds.length; i++) { require(contractTokenIds[i] > 1_000_000, "UseContractTokenIDs"); uint32 nftType = contractTokenIds[i] / 1_000_000; uint32 tokenId = contractTokenIds[i] % 1_000_000; if (nftType == 1) { _unstakeNFT(randomWalkNFT, uint256(tokenId), 1_000_000); // Add this RWNFT to the staked struct stakedNFTsAndTokens[msg.sender].numRWStaked -= 1; } else if (nftType == 2) { _unstakeNFT(impishspiral, uint256(tokenId), 2_000_000); // Add this spiral to the staked struct stakedNFTsAndTokens[msg.sender].numSpiralsStaked -= 1; } else if (nftType == 3) { // Crystals that are growing _unstakeNFT(crystals, uint256(tokenId), 3_000_000); // Add this crystal (Growing) to the staked struct stakedNFTsAndTokens[msg.sender].numGrowingCrystalsStaked -= 1; delete crystalTargetSyms[tokenId + 3_000_000]; } else if (nftType == 4) { // Crystals that are growing _unstakeNFT(crystals, uint256(tokenId), 4_000_000); // Add this crystal (fully grown) to the staked struct stakedNFTsAndTokens[msg.sender].numFullCrystalsStaked -= 1; } else { revert("InvalidNFTType"); } } if (claim) { _claimRewards(msg.sender); } } function pendingRewards(address owner) public view returns (uint256) { uint256 lastClaimedEpoch = stakedNFTsAndTokens[owner].lastClaimEpoch; // Start with already claimed epochs uint256 accumulated = stakedNFTsAndTokens[owner].claimedSpiralBits; // Add up all pending epochs if (lastClaimedEpoch > 0) { accumulated += _getRewardsAccumulated(owner, lastClaimedEpoch); } // Add potentially upcoming epoch RewardEpoch memory newEpoch = _getNextEpoch(); if (newEpoch.epochDurationSec > 0) { // Accumulate what will probably be the next epoch if (newEpoch.totalSpiralBitsStaked > 0) { accumulated += (SPIRALBITS_STAKING_EMISSION_PER_SEC * newEpoch.epochDurationSec * uint256(stakedNFTsAndTokens[owner].spiralBitsStaked)) / uint256(newEpoch.totalSpiralBitsStaked); } if (newEpoch.totalImpishStaked > 0) { accumulated += (IMPISH_STAKING_EMISSION_PER_SEC * newEpoch.epochDurationSec * uint256(stakedNFTsAndTokens[owner].impishStaked)) / uint256(newEpoch.totalImpishStaked); } // Rewards for Staked Spirals accumulated += newEpoch.epochDurationSec * SPIRALBITS_PER_SECOND_PER_SPIRAL * stakedNFTsAndTokens[owner].numSpiralsStaked; // Rewards for staked RandomWalks accumulated += newEpoch.epochDurationSec * SPIRALBITS_PER_SECOND_PER_RW * stakedNFTsAndTokens[owner].numRWStaked; // Rewards for staked fully grown crystals accumulated += newEpoch.epochDurationSec * SPIRALBITS_PER_SECOND_PER_CRYSTAL * stakedNFTsAndTokens[owner].numFullCrystalsStaked; } // Note: Growing crystals do not accumulate rewards return accumulated; } // --------------------- // Internal Functions // --------------------- // Claim the pending rewards function _claimRewards(address owner) internal { _updateRewards(owner); uint256 rewardsPending = stakedNFTsAndTokens[owner].claimedSpiralBits; // If there are any rewards, if (rewardsPending > 0) { // Mark rewards as claimed stakedNFTsAndTokens[owner].claimedSpiralBits = 0; // Mint new spiralbits directly to the claimer spiralbits.mintSpiralBits(owner, rewardsPending); } } // Stake an NFT function _stakeNFT( IERC721 nft, address owner, uint256 tokenId, uint256 tokenIdMultiplier ) internal { require(nft.ownerOf(tokenId) == msg.sender, "DontOwnNFT"); uint256 contractTokenId = tokenIdMultiplier + tokenId; // Add the spiral to staked owner list to keep track of staked tokens _addTokenToOwnerEnumeration(owner, contractTokenId); stakedTokenOwners[contractTokenId].owner = owner; // Transfer the actual NFT to this staking contract. nft.safeTransferFrom(msg.sender, address(this), tokenId); } // Unstake an NFT and return it back to the sender function _unstakeNFT( IERC721 nft, uint256 tokenId, uint256 tokenIdMultiplier ) internal { uint256 contractTokenId = tokenIdMultiplier + tokenId; require(stakedTokenOwners[contractTokenId].owner == msg.sender, "DontOwnNFT"); _removeTokenFromOwnerEnumeration(msg.sender, contractTokenId); // Transfer the NFT out nft.safeTransferFrom(address(this), msg.sender, tokenId); } function _getRewardsAccumulated(address owner, uint256 lastClaimedEpoch) internal view returns (uint256) { uint256 rewardsAccumulated = 0; uint256 totalDuration = 0; for (uint256 i = lastClaimedEpoch + 1; i < epochs.length; i++) { // Accumulate the durations, so we can add the NFT rewards too totalDuration += epochs[i].epochDurationSec; // Accumulate spiralbits reward if (epochs[i].totalSpiralBitsStaked > 0) { rewardsAccumulated += (SPIRALBITS_STAKING_EMISSION_PER_SEC * uint256(epochs[i].epochDurationSec) * uint256(stakedNFTsAndTokens[owner].spiralBitsStaked)) / uint256(epochs[i].totalSpiralBitsStaked); } // accumulate impish rewards if (epochs[i].totalImpishStaked > 0) { rewardsAccumulated += (IMPISH_STAKING_EMISSION_PER_SEC * uint256(epochs[i].epochDurationSec) * uint256(stakedNFTsAndTokens[owner].impishStaked)) / uint256(epochs[i].totalImpishStaked); } } // Rewards for Staked Spirals rewardsAccumulated += totalDuration * SPIRALBITS_PER_SECOND_PER_SPIRAL * stakedNFTsAndTokens[owner].numSpiralsStaked; // Rewards for staked RandomWalks rewardsAccumulated += totalDuration * SPIRALBITS_PER_SECOND_PER_RW * stakedNFTsAndTokens[owner].numRWStaked; // Rewards for staked fully grown crystals rewardsAccumulated += totalDuration * SPIRALBITS_PER_SECOND_PER_CRYSTAL * stakedNFTsAndTokens[owner].numFullCrystalsStaked; // Note: Growing crystals do not accumulate rewards return rewardsAccumulated; } // Do the internal accounting update for the address function _updateRewards(address owner) internal { // First, see if we need to add an epoch. // We may not always need to, especially if the time elapsed is 0 (i.e., multiple tx in same block) if (block.timestamp > lastEpochTime) { _addEpoch(); } // Mark as claimed till the newly created epoch. uint256 lastClaimedEpoch = stakedNFTsAndTokens[owner].lastClaimEpoch; stakedNFTsAndTokens[owner].lastClaimEpoch = uint32(epochs.length - 1); // If this owner is new, just return if (lastClaimedEpoch == 0) { return; } uint256 rewardsAccumulated = _getRewardsAccumulated(owner, lastClaimedEpoch); // Accumulate everything stakedNFTsAndTokens[owner].claimedSpiralBits += uint96(rewardsAccumulated); } // ------------------- // Rewards Epochs // ------------------- // Rewards for ERC20 tokens are different from Rewards for NFTs. // Staked NFTs earn a fixed reward per time, but staked ERC20 earn a reward // proportional to how many other ERC20 of the same type are staked. // That is, there is a global emission per ERC20, that is split evenly among all // staked ERC20. // Therefore, we need to track how many of the total ERC20s were staked for each epoch // Note that if the amount of ERC20 staked by a user changes (via deposit or withdraw), then // the user's balance needs to be updated function _getNextEpoch() internal view returns (RewardEpoch memory) { RewardEpoch memory newEpoch = RewardEpoch({ epochDurationSec: uint32(block.timestamp) - lastEpochTime, totalSpiralBitsStaked: uint96(spiralbits.balanceOf(address(this))), totalImpishStaked: uint96(impish.balanceOf(address(this))) }); return newEpoch; } // Add a new epoch with the balances in the contract function _addEpoch() internal { // Sanity check. Can't add epoch without having the epochs up-to-date require(uint32(block.timestamp) > lastEpochTime, "TooNew"); RewardEpoch memory newEpoch = _getNextEpoch(); // Add to array lastEpochTime = uint32(block.timestamp); epochs.push(newEpoch); } // ------------------- // Keep track of staked NFTs // ------------------- function _totalTokenCountStaked(address _owner) internal view returns (uint256) { return stakedNFTsAndTokens[_owner].numRWStaked + stakedNFTsAndTokens[_owner].numSpiralsStaked + stakedNFTsAndTokens[_owner].numGrowingCrystalsStaked + stakedNFTsAndTokens[_owner].numFullCrystalsStaked; } // Returns a list of token Ids owned by _owner. function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = _totalTokenCountStaked(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } uint256[] memory result = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { result[i] = tokenOfOwnerByIndex(_owner, i); } return result; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256) { require(index < _totalTokenCountStaked(owner), "OwnerIndex out of bounds"); return stakedNFTsAndTokens[owner].ownedTokens[index]; } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param owner address representing the owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address owner, uint256 tokenId) private { uint256 length = _totalTokenCountStaked(owner); stakedNFTsAndTokens[owner].ownedTokens[length] = tokenId; stakedTokenOwners[tokenId].ownedTokensIndex = length; } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _totalTokenCountStaked(from) - 1; uint256 tokenIndex = stakedTokenOwners[tokenId].ownedTokensIndex; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = stakedNFTsAndTokens[from].ownedTokens[lastTokenIndex]; stakedNFTsAndTokens[from].ownedTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token stakedTokenOwners[lastTokenId].ownedTokensIndex = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete stakedTokenOwners[tokenId]; delete stakedNFTsAndTokens[from].ownedTokens[lastTokenIndex]; } // ----------------- // Harvesting and Growing Crystals // ----------------- function setCrystalTargetSym(uint32 crystalTokenId, uint8 targetSym) external nonReentrant { uint32 contractCrystalTokenId = crystalTokenId + 3_000_000; require(stakedTokenOwners[contractCrystalTokenId].owner == msg.sender, "NotYourCrystal"); crystalTargetSyms[contractCrystalTokenId] = targetSym; } // Grow all the given crystals to max size for the target symmetry function _growCrystals(uint32[] memory contractCrystalTokenIds) internal { // How many spiralbits are available to grow uint96 availableSpiralBits = stakedNFTsAndTokens[msg.sender].claimedSpiralBits; stakedNFTsAndTokens[msg.sender].claimedSpiralBits = 0; spiralbits.mintSpiralBits(address(this), availableSpiralBits); for (uint256 i = 0; i < contractCrystalTokenIds.length; i++) { uint32 contractCrystalTokenId = contractCrystalTokenIds[i]; uint32 crystalTokenId = contractCrystalTokenId - 3_000_000; require(stakedTokenOwners[contractCrystalTokenId].owner == msg.sender, "NotYourCrystal"); // Grow the crystal to max that it can (uint8 currentCrystalSize, , uint8 currentSym, , ) = crystals.crystals(crystalTokenId); if (currentCrystalSize < 100) { uint96 spiralBitsNeeded = uint96( crystals.SPIRALBITS_PER_SYM_PER_SIZE() * uint256(100 - currentCrystalSize) * uint256(currentSym) ); if (availableSpiralBits > spiralBitsNeeded) { crystals.grow(crystalTokenId, 100 - currentCrystalSize); availableSpiralBits -= spiralBitsNeeded; } } // Next grow syms if (crystalTargetSyms[contractCrystalTokenId] > 0 && crystalTargetSyms[contractCrystalTokenId] > currentSym) { uint8 growSyms = crystalTargetSyms[contractCrystalTokenId] - currentSym; uint96 spiralBitsNeeded = uint96(crystals.SPIRALBITS_PER_SYM() * uint256(growSyms)); if (availableSpiralBits > spiralBitsNeeded) { crystals.addSym(crystalTokenId, growSyms); availableSpiralBits -= spiralBitsNeeded; } } // And then grow the Crystal again to max size if possible (currentCrystalSize, , currentSym, , ) = crystals.crystals(crystalTokenId); if (currentCrystalSize < 100) { uint96 spiralBitsNeeded = uint96( crystals.SPIRALBITS_PER_SYM_PER_SIZE() * uint256(100 - currentCrystalSize) * uint256(currentSym) ); if (availableSpiralBits > spiralBitsNeeded) { crystals.grow(crystalTokenId, 100 - currentCrystalSize); availableSpiralBits -= spiralBitsNeeded; } } delete crystalTargetSyms[contractCrystalTokenId]; } // Burn any unused spiralbits and credit the user back, so we can harvest more crystals // instead of returning a large amount of SPIRALBITS back to the user here. spiralbits.burn(availableSpiralBits); stakedNFTsAndTokens[msg.sender].claimedSpiralBits = availableSpiralBits; } function harvestCrystals(uint32[] calldata contractCrystalTokenIds, bool claim) external nonReentrant { _updateRewards(msg.sender); // First, grow all the crystals _growCrystals(contractCrystalTokenIds); // And then transfer the crystals over from growing to staked for (uint256 i = 0; i < contractCrystalTokenIds.length; i++) { uint32 contractCrystalTokenId = contractCrystalTokenIds[i]; uint32 crystalTokenId = contractCrystalTokenId - 3_000_000; (uint8 currentCrystalSize, , , , ) = crystals.crystals(crystalTokenId); // Move this crystal over to be staked only if it is fully grown if (currentCrystalSize == 100) { // Unstake growing crystal _removeTokenFromOwnerEnumeration(msg.sender, contractCrystalTokenId); stakedNFTsAndTokens[msg.sender].numGrowingCrystalsStaked -= 1; // Stake fully grown crystal uint256 contractFullyGrownTokenId = 4_000_000 + crystalTokenId; _addTokenToOwnerEnumeration(msg.sender, contractFullyGrownTokenId); stakedTokenOwners[contractFullyGrownTokenId].owner = msg.sender; stakedNFTsAndTokens[msg.sender].numFullCrystalsStaked += 1; } } if (claim) { _claimRewards(msg.sender); } } // ----------------- // RPS Functions // ----------------- // Note that this function is not nonReentrant because the RPS.commit will // reenter via stakeNFTs, and that's OK. function rpsCommit(bytes32 commitment, uint32[] calldata crystalIDs) external { require(rps != address(0), "RPSNotSet"); // Update the owner's rewards first. This also updates the current epoch. _updateRewards(msg.sender); // Unstake the crystals for (uint256 i = 0; i < crystalIDs.length; i++) { uint256 contractTokenId = 4_000_000 + uint256(crystalIDs[i]); require(stakedTokenOwners[contractTokenId].owner == msg.sender, "DontOwnNFT"); _removeTokenFromOwnerEnumeration(msg.sender, contractTokenId); stakedNFTsAndTokens[msg.sender].numFullCrystalsStaked -= 1; } // Commit it for the player IRPS(rps).commit(commitment, msg.sender, crystalIDs); } function setRPS(address _rps) external onlyOwner { rps = _rps; // Authorize the rps to move out Crystals for the RPS game crystals.setApprovalForAll(rps, true); } // ------------------ // Other functions // ------------------ function claimSpiralWin(uint256 spiralTokenId) external nonReentrant { ImpishSpiral(address(impishspiral)).claimWin(spiralTokenId); // Send the ether to the Spiral's owner address spiralOwner = stakedTokenOwners[spiralTokenId + 2_000_000].owner; (bool success, ) = spiralOwner.call{value: address(this).balance}(""); require(success, "Transfer failed."); } receive() external payable { // Default payable to accept ether payments for winning spirals } // ------------------- // Overrides that allow accepting NFTs and ERC20s // ------------------- // Function that marks this contract can accept incoming NFT transfers function onERC721Received( address, address, uint256, bytes calldata ) public pure returns (bytes4) { // Return this value to accept the NFT return IERC721ReceiverUpgradeable.onERC721Received.selector; } }
----------------- RPS Functions ----------------- Note that this function is not nonReentrant because the RPS.commit will reenter via stakeNFTs, and that's OK. Update the owner's rewards first. This also updates the current epoch. Unstake the crystals
function rpsCommit(bytes32 commitment, uint32[] calldata crystalIDs) external { require(rps != address(0), "RPSNotSet"); _updateRewards(msg.sender); for (uint256 i = 0; i < crystalIDs.length; i++) { uint256 contractTokenId = 4_000_000 + uint256(crystalIDs[i]); require(stakedTokenOwners[contractTokenId].owner == msg.sender, "DontOwnNFT"); _removeTokenFromOwnerEnumeration(msg.sender, contractTokenId); stakedNFTsAndTokens[msg.sender].numFullCrystalsStaked -= 1; } }
12,845,862
[ 1, 1271, 17, 534, 5857, 15486, 12146, 3609, 716, 333, 445, 353, 486, 1661, 426, 8230, 970, 2724, 326, 534, 5857, 18, 7371, 903, 283, 2328, 3970, 384, 911, 50, 4464, 87, 16, 471, 716, 1807, 7791, 18, 2315, 326, 3410, 1807, 283, 6397, 1122, 18, 1220, 2546, 4533, 326, 783, 7632, 18, 1351, 334, 911, 326, 4422, 1094, 1031, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 436, 1121, 5580, 12, 3890, 1578, 23274, 16, 2254, 1578, 8526, 745, 892, 4422, 31365, 5103, 13, 3903, 288, 203, 565, 2583, 12, 86, 1121, 480, 1758, 12, 20, 3631, 315, 54, 5857, 1248, 694, 8863, 203, 203, 565, 389, 2725, 17631, 14727, 12, 3576, 18, 15330, 1769, 203, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 4422, 31365, 5103, 18, 2469, 31, 277, 27245, 288, 203, 1377, 2254, 5034, 6835, 1345, 548, 273, 1059, 67, 3784, 67, 3784, 397, 2254, 5034, 12, 3353, 31365, 5103, 63, 77, 19226, 203, 1377, 2583, 12, 334, 9477, 1345, 5460, 414, 63, 16351, 1345, 548, 8009, 8443, 422, 1234, 18, 15330, 16, 315, 40, 1580, 5460, 50, 4464, 8863, 203, 203, 1377, 389, 4479, 1345, 1265, 5541, 21847, 12, 3576, 18, 15330, 16, 6835, 1345, 548, 1769, 203, 1377, 384, 9477, 50, 4464, 87, 1876, 5157, 63, 3576, 18, 15330, 8009, 2107, 5080, 12893, 1094, 1031, 510, 9477, 3947, 404, 31, 203, 565, 289, 203, 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 ]
./full_match/80001/0xDfb72CCa96DA3d35a9806d1012b97Bc5CC2Fc75A/sources/contracts/abstract/DIDOpt.sol
* @dev we create 'isPublicKeyUsed' function to check public key is already use or not, for easily tracking public key is already minted nft or not @param publicKey is public key want to be check/
function isPublicKeyUsed( bytes memory publicKey ) public view virtual returns (bool) { return publicKeyInfo[publicKey].used; }
849,536
[ 1, 1814, 752, 296, 291, 9632, 6668, 11, 445, 358, 866, 1071, 498, 353, 1818, 999, 578, 486, 16, 364, 17997, 11093, 1071, 498, 353, 1818, 312, 474, 329, 290, 1222, 578, 486, 225, 12085, 353, 1071, 498, 2545, 358, 506, 866, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 353, 9632, 6668, 12, 203, 3639, 1731, 3778, 12085, 203, 565, 262, 1071, 1476, 5024, 1135, 261, 6430, 13, 288, 203, 3639, 327, 12085, 966, 63, 482, 653, 8009, 3668, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-04-06 */ /** ███████╗███████╗██████╗░░█████╗░  ██████╗░░█████╗░░█████╗░ ╚════██║██╔════╝██╔══██╗██╔══██╗  ██╔══██╗██╔══██╗██╔══██╗ ░░███╔═╝█████╗░░██████╔╝██║░░██║  ██║░░██║███████║██║░░██║ ██╔══╝░░██╔══╝░░██╔══██╗██║░░██║  ██║░░██║██╔══██║██║░░██║ ███████╗███████╗██║░░██║╚█████╔╝  ██████╔╝██║░░██║╚█████╔╝ ╚══════╝╚══════╝╚═╝░░╚═╝░╚════╝░  ╚═════╝░╚═╝░░╚═╝░╚════╝░ https://twitter.com/ZeroDaoToken /** /** * @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; } } ////// lib/openzeppelin-contracts/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) /* pragma solidity ^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() { _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); } } ////// lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.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 `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); } ////// lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol) /* pragma solidity ^0.8.0; */ /* import "../IERC20.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); } ////// lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol) /* pragma solidity ^0.8.0; */ /* import "./IERC20.sol"; */ /* import "./extensions/IERC20Metadata.sol"; */ /* import "../../utils/Context.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: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - 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) { _approve(_msgSender(), spender, _allowances[_msgSender()][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) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), 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: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); 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); _afterTokenTransfer(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: * * - `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 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 {} } ////// lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol) /* pragma solidity ^0.8.0; */ // 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; } } } ////// src/IUniswapV2Factory.sol /* pragma solidity 0.8.10; */ /* pragma experimental ABIEncoderV2; */ interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } ////// src/IUniswapV2Pair.sol /* pragma solidity 0.8.10; */ /* pragma experimental ABIEncoderV2; */ interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 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 (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 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 (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); 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 (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } ////// src/IUniswapV2Router02.sol /* pragma solidity 0.8.10; */ /* pragma experimental ABIEncoderV2; */ interface IUniswapV2Router02 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } /* pragma solidity >=0.8.10; */ /* import {IUniswapV2Router02} from "./IUniswapV2Router02.sol"; */ /* import {IUniswapV2Factory} from "./IUniswapV2Factory.sol"; */ /* import {IUniswapV2Pair} from "./IUniswapV2Pair.sol"; */ /* import {IERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; */ /* import {ERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol"; */ /* import {Ownable} from "lib/openzeppelin-contracts/contracts/access/Ownable.sol"; */ /* import {SafeMath} from "lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol"; */ contract ZeroDao is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; 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 _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; // 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 UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); 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(); event ManualNukeLP(); constructor() ERC20("Zero Dao", "ZDAO") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 0; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 3; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 3; uint256 totalSupply = 1_000_000_000 * 1e18; maxTransactionAmount = 30_000_000 * 1e18; // 3% from total supply maxTransactionAmountTxn maxWallet = 60_000_000 * 1e18; // 6% from total supply maxWallet swapTokensAtAmount = (totalSupply * 5) / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0x12FA4D7aF8b469235C4701e5780cb877137EFFF9); // set as marketing wallet devWallet = address(0x12FA4D7aF8b469235C4701e5780cb877137EFFF9); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable {} // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } // 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() * 1) / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.1%" ); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[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 _devFee ) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + 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 != uniswapV2Pair, "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]; } event BoughtEarly(address indexed sniper); 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 (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } //when sell else if ( automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } else if (!_isExcludedMaxTransactionAmount[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(); } 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) { // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.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(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.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 + 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.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success, ) = address(devWallet).call{value: ethForDev}(""); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } 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 0% and 10%" ); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { 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(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
exclude from paying fees or having max transaction amount
constructor() ERC20("Zero Dao", "ZDAO") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 0; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 3; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 3; uint256 totalSupply = 1_000_000_000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
4,814,816
[ 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, 7170, 463, 6033, 3113, 315, 62, 18485, 7923, 288, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 203, 5411, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 203, 3639, 11272, 203, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 24899, 318, 291, 91, 438, 58, 22, 8259, 3631, 638, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 10756, 203, 5411, 263, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 203, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 8870, 14667, 2 ]
pragma solidity 0.5.16; import "./Ownable.sol"; contract ToDoList is Ownable { event NewToDo( address indexed owner, string title, uint256 deposit, uint8 id ); event MarkedAsDone(uint8 id); struct ToDo { string title; uint256 deposit; bool isDone; } ToDo[] private todos; mapping(uint8 => address) private todoOwners; mapping(address => uint8) private ownerTodosCount; // to create a new todo item sender has to send some ether that will be released when todo is done function create(string memory _title) public payable { require(msg.value > 0, "Some ether is required"); todos.push(ToDo(_title, msg.value, false)); uint8 id = uint8(todos.length - 1); todoOwners[id] = msg.sender; ownerTodosCount[msg.sender]++; emit NewToDo(msg.sender, _title, msg.value, id); } // return sender todo ids function getIds() public view returns (uint8[] memory) { uint8[] memory result = new uint8[](ownerTodosCount[msg.sender]); uint8 counter = 0; for (uint8 i = 0; i < todos.length; i++) { if (todoOwners[i] == msg.sender) { result[counter] = i; counter++; } } return result; } function getById(uint8 _id) public view returns (uint8 id, string memory title, uint256 deposit, bool isDone) { require(msg.sender == todoOwners[_id], "Sender is not the owner"); ToDo storage todo = todos[_id]; return (_id, todo.title, todo.deposit, todo.isDone); } function markAsDone(uint8 _id) public { ToDo storage todo = todos[_id]; require(msg.sender == todoOwners[_id], "Sender is not the owner"); require(todo.isDone == false, "Already marked as done"); todo.isDone = true; // msg.sender.call.value(todo.deposit); msg.sender.transfer(todo.deposit); emit MarkedAsDone(_id); } }
to create a new todo item sender has to send some ether that will be released when todo is done
function create(string memory _title) public payable { require(msg.value > 0, "Some ether is required"); todos.push(ToDo(_title, msg.value, false)); uint8 id = uint8(todos.length - 1); todoOwners[id] = msg.sender; ownerTodosCount[msg.sender]++; emit NewToDo(msg.sender, _title, msg.value, id); }
12,954,767
[ 1, 869, 752, 279, 394, 10621, 761, 5793, 711, 358, 1366, 2690, 225, 2437, 716, 903, 506, 15976, 1347, 10621, 353, 2731, 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 ]
[ 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, 0, 0 ]
[ 1, 565, 445, 752, 12, 1080, 3778, 389, 2649, 13, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 405, 374, 16, 315, 17358, 225, 2437, 353, 1931, 8863, 203, 3639, 31754, 18, 6206, 12, 774, 3244, 24899, 2649, 16, 1234, 18, 1132, 16, 629, 10019, 203, 3639, 2254, 28, 612, 273, 2254, 28, 12, 88, 369, 538, 18, 2469, 300, 404, 1769, 203, 3639, 10621, 5460, 414, 63, 350, 65, 273, 1234, 18, 15330, 31, 203, 3639, 3410, 56, 369, 538, 1380, 63, 3576, 18, 15330, 3737, 15, 31, 203, 3639, 3626, 1166, 774, 3244, 12, 3576, 18, 15330, 16, 389, 2649, 16, 1234, 18, 1132, 16, 612, 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 ]
pragma solidity ^0.5.0; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "../Interfaces/IKhanaLogic.sol"; contract CommunityEvents is Ownable { IKhanaLogic public khanaLogic; address public newerEventsContract; /** * @dev Throws if called by a non-admin account. */ modifier onlyAdmins() { require(khanaLogic.isAdmin(msg.sender), "Only admins can perform this action"); _; } constructor(address _khanaLogicAddress) public { khanaLogic = IKhanaLogic(_khanaLogicAddress); } /** * @dev Set valid khanaLogic address. * @param _khanaLogic The address of the new communityRegister. */ function setKhanaLogic(address _khanaLogic) external onlyAdmins returns (bool) { khanaLogic = IKhanaLogic(_khanaLogic); return true; } /** * @dev Set a new address for a more recent events contract. * @notice If `newerEventsContract` is set, then this current contract has been * superseeded by the contract at `newerEventsContract`. * @param _newEventsContract The address of the newer events contract. */ function setNewerEventsContract(address _newEventsContract) external onlyAdmins returns (bool) { newerEventsContract = _newEventsContract; return true; } // // Emitting Event Functions // /** * @dev Emit an event that includes a boolean as the main value. * @notice Example: when a contract is active or not. * @param _eventName The bytes32 encoded (hex) representation of the event's name in audit files. * @param _isTrue The boolean value in question. * @param _id The unique ID that can be matched with the record in the distributed audit file, to match * any other information related to this event (e.g. a reason the action was taken). * @param _cid The Content ID of the distributed audit file. */ function emitEvent(bytes32 _eventName, bool _isTrue, uint _id, string calldata _cid) external onlyAdmins { emit LogEvent(_eventName, _isTrue, _id, _cid, msg.sender); emit LogLatestAudit(_cid); } /** * @dev Emit an event that includes an address as the main value. * @notice Example: when a new contract address is added. * @param _eventName The bytes32 encoded (hex) representation of the event's name in audit files. * @param _account The address of the account in question. * @param _id The unique ID that can be matched with the record in the distributed audit file, to match * any other information related to this event (e.g. a reason the action was taken). * @param _cid The Content ID of the distributed audit file. */ function emitEvent(bytes32 _eventName, address _account, uint _id, string calldata _cid) external onlyAdmins { emit LogEvent(_eventName, _account, _id, _cid, msg.sender); emit LogLatestAudit(_cid); } /** * @dev Emit an event that includes an array of addresses as the main values. * @notice Example: when a bulk admin add has been performed. * @param _eventName The bytes32 encoded (hex) representation of the event's name in audit files. * @param _accounts The addresses of the account in question. * @param _id The unique ID that can be matched with the record in the distributed audit file, to match * any other information related to this event (e.g. a reason the action was taken). * @param _cid The Content ID of the distributed audit file. */ function emitEvent(bytes32 _eventName, address[] calldata _accounts, uint _id, string calldata _cid) external onlyAdmins { emit LogEvent(_eventName, _accounts, _id, _cid, msg.sender); emit LogLatestAudit(_cid); } /** * @dev Emit an event that includes a number as the main value. * @notice Example: when an amount of tokens has been created. * @param _eventName The bytes32 encoded (hex) representation of the event's name in audit files. * @param _amount The amount in question. * @param _id The unique ID that can be matched with the record in the distributed audit file, to match * any other information related to this event (e.g. a reason the action was taken). * @param _cid The Content ID of the distributed audit file. */ function emitEvent(bytes32 _eventName, uint _amount, uint _id, string calldata _cid) external onlyAdmins { emit LogEvent(_eventName, _amount, _id, _cid, msg.sender); emit LogLatestAudit(_cid); } /** * @dev Emit an event that includes an address and a number as the main values. * @notice Example: when an award of tokens is given. * @param _eventName The bytes32 encoded (hex) representation of the event's name in audit files. * @param _account The account in question. * @param _amount The amount in question. * @param _id The unique ID that can be matched with the record in the distributed audit file, to match * any other information related to this event (e.g. a reason the action was taken). * @param _cid The Content ID of the distributed audit file. */ function emitEvent(bytes32 _eventName, address _account, uint _amount, uint _id, string calldata _cid) external onlyAdmins { emit LogEvent(_eventName, _account, _amount, _id, _cid, msg.sender); emit LogLatestAudit(_cid); } /** * @dev Emit an event that includes an array of addresses and an array of numbers as the main values. * @notice Example: when a bulk award of tokens is given. * @param _eventName The bytes32 encoded (hex) representation of the event's name in audit files. * @param _accounts The accounts in question. * @param _amounts The amounts in question. * @param _id The unique ID that can be matched with the record in the distributed audit file, to match * any other information related to this event (e.g. a reason the action was taken). * @param _cid The Content ID of the distributed audit file. */ function emitEvent(bytes32 _eventName, address[] calldata _accounts, uint[] calldata _amounts, uint _id, string calldata _cid) external onlyAdmins { emit LogEvent(_eventName, _accounts, _amounts, _id, _cid, msg.sender); emit LogLatestAudit(_cid); } // // Events // /** * @notice We want a single emitted event to record the most recent CID hash */ event LogLatestAudit( string cid ); /** * @notice For logging `bool` events */ event LogEvent( bytes32 indexed eventName, bool isTrue, uint id, string cid, address sender ); /** * @notice For logging `address` events */ event LogEvent( bytes32 indexed eventName, address account, uint id, string cid, address sender ); /** * @notice For logging `address[]` events */ event LogEvent( bytes32 indexed eventName, address[] accounts, uint id, string cid, address sender ); /** * @notice For logging `uint` events */ event LogEvent( bytes32 indexed eventName, uint amount, uint id, string cid, address sender ); /** * @notice For logging `address` and `uint` events */ event LogEvent( bytes32 indexed eventName, address account, uint amount, uint id, string cid, address sender ); /** * @notice For logging an array of `address` and `uint` values in events */ event LogEvent( bytes32 indexed eventName, address[] accounts, uint[] amounts, uint id, string cid, address sender ); }
* @dev Emit an event that includes an address and a number as the main values. @notice Example: when an award of tokens is given. @param _eventName The bytes32 encoded (hex) representation of the event's name in audit files. @param _account The account in question. @param _amount The amount in question. @param _id The unique ID that can be matched with the record in the distributed audit file, to match any other information related to this event (e.g. a reason the action was taken). @param _cid The Content ID of the distributed audit file./
function emitEvent(bytes32 _eventName, address _account, uint _amount, uint _id, string calldata _cid) external onlyAdmins { emit LogEvent(_eventName, _account, _amount, _id, _cid, msg.sender); emit LogLatestAudit(_cid); }
6,477,887
[ 1, 17982, 392, 871, 716, 6104, 392, 1758, 471, 279, 1300, 487, 326, 2774, 924, 18, 225, 5090, 30, 1347, 392, 279, 2913, 434, 2430, 353, 864, 18, 225, 389, 2575, 461, 1021, 1731, 1578, 3749, 261, 7118, 13, 4335, 434, 326, 871, 1807, 508, 316, 8215, 1390, 18, 225, 389, 4631, 1021, 2236, 316, 5073, 18, 225, 389, 8949, 1021, 3844, 316, 5073, 18, 225, 389, 350, 1021, 3089, 1599, 716, 848, 506, 4847, 598, 326, 1409, 316, 326, 16859, 8215, 585, 16, 358, 845, 1281, 1308, 1779, 3746, 358, 333, 871, 261, 73, 18, 75, 18, 279, 3971, 326, 1301, 1703, 9830, 2934, 225, 389, 13478, 1021, 3697, 1599, 434, 326, 16859, 8215, 585, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 3626, 1133, 12, 3890, 1578, 389, 2575, 461, 16, 1758, 389, 4631, 16, 2254, 389, 8949, 16, 2254, 389, 350, 16, 533, 745, 892, 389, 13478, 13, 3903, 1338, 4446, 87, 288, 203, 3639, 3626, 1827, 1133, 24899, 2575, 461, 16, 389, 4631, 16, 389, 8949, 16, 389, 350, 16, 389, 13478, 16, 1234, 18, 15330, 1769, 203, 3639, 3626, 1827, 18650, 10832, 24899, 13478, 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.7.6; //SPDX-License-Identifier: MIT import {DiceRoll} from "./DiceRoll.sol"; contract MetablocksJoseph { address private owner; DiceRoll private diceRollPlugin; string[] private avatars; // uint public gmyPosition; // Event Definitions event PlayerJoined( address indexed playerAddress, string gameName, string avatar, string message ); // Event Definitions event PlayerStartedTurn( address indexed playerAddress, string gameName, uint8 newPosition, string message ); constructor(address diceRollContract) { owner = msg.sender; diceRollPlugin = DiceRoll(diceRollContract); // Create land createLand(1, "Mayfair", 80); createLand(3, "Adelaide", 80); createLand(4, "City Grill", 150); createLand(5, "VLINE", 98); createLand(6, "Melbourne", 200); createLand(8, "Mildura", 200); // Create available avatars avatars.push("LedgerNano"); avatars.push("BTCCoin"); avatars.push("BowTie"); avatars.push("Ghost"); // Step 1: Create player who wants to host game createPlayer("jrocco2"); // Step 2: Create game createGame("JoesGame", 2); } // ----- PLAYERS ENTITY ----- struct Player { string username; address playerAddress; uint256 balance; uint8 positionOnBoard; address gameHostAddress; string avatar; } function createPlayer(string memory username) public { Player memory myPlayer; myPlayer.username = username; myPlayer.playerAddress = msg.sender; playerMapping[msg.sender] = myPlayer; } function setupPlayer(string memory gameName) private { // Setup player //playerMapping[msg.sender] is a Player playerMapping[msg.sender].gameHostAddress = hostMapping[gameName]; playerMapping[msg.sender].positionOnBoard = 0; // Monoply Rule: Each player is given $1500 playerMapping[msg.sender].balance = 1500; playerMapping[msg.sender].avatar = avatars[ gameMapping[playerMapping[msg.sender].gameHostAddress] .players .length - 1 ]; } mapping(address => Player) public playerMapping; // ----- GAME ENTITY ----- struct Game { string name; int256 timePerMove; bool hasStarted; address creatorAddress; address[] players; Player currentPlayer; } // mapping this way means one player can only host one game // and therefore must remove their game in order to create another mapping(address => Game) private gameMapping; mapping(string => address) private hostMapping; function createGame(string memory name, int256 timePerMove) public { require( playerMapping[msg.sender].playerAddress == msg.sender, "You have to create your player before you can create a game" ); Game memory myGame; myGame.name = name; myGame.timePerMove = timePerMove; myGame.hasStarted = false; myGame.creatorAddress = msg.sender; gameMapping[msg.sender] = myGame; gameMapping[msg.sender].players.push(msg.sender); hostMapping[name] = msg.sender; setupPlayer(name); emit PlayerJoined( msg.sender, name, playerMapping[msg.sender].avatar, "Let's play Metablocks" ); } function joinGame(string memory name) public { require(hostMapping[name] != address(0), "Invalid name"); require( hostMapping[name] != playerMapping[msg.sender].gameHostAddress, "You have already joined this game" ); // Monoply Rule: There is usually 8 players in a game (but works with more) require( gameMapping[hostMapping[name]].players.length < 8, "This game has reached the maximum number of players" ); require( gameMapping[hostMapping[name]].hasStarted == false, "The game has already started" ); require( playerMapping[msg.sender].playerAddress == msg.sender, "You have to create your player before you can join a game" ); gameMapping[hostMapping[name]].players.push(msg.sender); setupPlayer(name); emit PlayerJoined( msg.sender, name, playerMapping[msg.sender].avatar, "Let's do it" ); } function startGame() public { // require(gameMapping[hostMapping[name]].creatorAddress == msg.sender,"Only the host can start the game they have created"); require( gameMapping[msg.sender].creatorAddress != address(0), "You are not hosting any games" ); require( gameMapping[msg.sender].players.length >= 2, "Not enough players" ); gameMapping[msg.sender].hasStarted = true; //TODO: DO VRF HERE TO CHOOSE WHO PLAYS FIRST, atm it's fifo gameMapping[msg.sender].currentPlayer = playerMapping[ gameMapping[msg.sender].players[0] ]; // AND ROLL DICE FOR PLAYER diceRollPlugin.rollDice(); } function debugForceMoveBaseGame() external { // require(gameMapping[hostMapping[name]].creatorAddress == msg.sender,"Only the host can start the game they have created"); gameMapping[msg.sender].hasStarted = true; //TODO: DO VRF HERE TO CHOOSE WHO PLAYS FIRST, atm it's fifo gameMapping[msg.sender].currentPlayer = playerMapping[ gameMapping[msg.sender].players[0] ]; playerMapping[msg.sender].positionOnBoard++; emit PlayerStartedTurn( msg.sender, gameMapping[playerMapping[msg.sender].gameHostAddress].name, playerMapping[msg.sender].positionOnBoard, // playerMapping[msg.sender].username string(abi.encodePacked(playerMapping[msg.sender].username, " rolls ", uint2str(diceRollPlugin.getMostRecentRoll()))) ); } function endGame() public { require( gameMapping[msg.sender].creatorAddress != address(0), "You are not hosting any games" ); gameMapping[msg.sender].hasStarted = false; } function removeGame(string memory name) private { require( gameMapping[hostMapping[name]].creatorAddress == msg.sender || owner == msg.sender, "Only the host can remove the game they have created" ); delete gameMapping[hostMapping[name]]; delete hostMapping[name]; } function showMeMyGame() public view returns ( string memory, int256, address, address[] memory ) { Game memory myGame = gameMapping[msg.sender]; return ( myGame.name, myGame.timePerMove, myGame.creatorAddress, myGame.players ); } // ----- GAME FUNCTIONALITY ----- function rollDice() public { require( playerMapping[msg.sender].gameHostAddress != address(0), "Player has not joined a game" ); // VRF rollDice then...... // playerMapping[msg.sender].positionOnBoard += diceRoll; // NEXT PLAYERS TURN } function pickUpCard() public { require( playerMapping[msg.sender].gameHostAddress != address(0), "Player has not joined a game" ); // Pick up card and do some function based on card } function getRollStartTurn() public { require( playerMapping[msg.sender].gameHostAddress != address(0), "Player has not joined a game" ); require( gameMapping[playerMapping[msg.sender].gameHostAddress] .currentPlayer .playerAddress == msg.sender, "It's not your turn" ); playerMapping[msg.sender].positionOnBoard = calculateGameTile( playerMapping[msg.sender].positionOnBoard, diceRollPlugin.getMostRecentRoll() ); emit PlayerStartedTurn( msg.sender, gameMapping[playerMapping[msg.sender].gameHostAddress].name, playerMapping[msg.sender].positionOnBoard, // playerMapping[msg.sender].username string(abi.encodePacked(playerMapping[msg.sender].username, " rolls ", uint2str(diceRollPlugin.getMostRecentRoll()))) ); } function endTurn() public { require( playerMapping[msg.sender].gameHostAddress != address(0), "Player has not joined a game" ); require( gameMapping[playerMapping[msg.sender].gameHostAddress] .currentPlayer .playerAddress == msg.sender, "It's not your turn" ); Player memory next = playerMapping[ calculateNextPlayer( gameMapping[playerMapping[msg.sender].gameHostAddress], gameMapping[playerMapping[msg.sender].gameHostAddress] .currentPlayer .playerAddress ) ]; gameMapping[playerMapping[msg.sender].gameHostAddress] .currentPlayer = next; diceRollPlugin.rollDice(); } function getCurrentPlayerAddress() external view returns (address currentPlayAddr) { return gameMapping[playerMapping[msg.sender].gameHostAddress] .currentPlayer .playerAddress; } function getMyPosition() external view returns (uint8 myPosition) { return uint8(playerMapping[msg.sender].positionOnBoard); } function calculateGameTile(uint8 currentPosition, uint8 diceRoll) private returns (uint8) { return (currentPosition + diceRoll) % 40; } function calculateNextPlayer(Game storage _game, address currentPlayerAddr) private returns (address) { for (uint8 index = 0; index < _game.players.length; index++) { if (_game.players[index] == currentPlayerAddr) { if (index == _game.players.length - 1) { return _game.players[0]; } else { return _game.players[index + 1]; } } } return _game.players[0]; } function buyLand() public {} function swapLand() public {} function payDebt() public {} // ----- LAND ENTITY ----- struct Land { int32 landTileId; string name; int256 value; address ownerAddress; } mapping(int32 => Land) public landMapping; int32[] public landList; // The order of the list is the order of Land on the Monopoly board function createLand( int32 _landTileId, string memory landName, int256 landValue ) private { landMapping[_landTileId] = Land( _landTileId, landName, landValue, owner ); landList.push(_landTileId); } function getLand(int32 _landTileId) public view returns ( int32, string memory, int256 ) { return ( landMapping[_landTileId].landTileId, landMapping[_landTileId].name, landMapping[_landTileId].value ); } // ----------------HELPER--------------- function uint2str(uint _i) internal pure returns (string memory _uintAsString) { 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(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } }
----- GAME ENTITY -----
struct Game { string name; int256 timePerMove; bool hasStarted; address creatorAddress; address[] players; Player currentPlayer; } mapping(string => address) private hostMapping;
15,793,413
[ 1, 13465, 611, 1642, 17020, 9135, 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, 1958, 14121, 288, 203, 3639, 533, 508, 31, 203, 3639, 509, 5034, 813, 2173, 7607, 31, 203, 3639, 1426, 711, 9217, 31, 203, 3639, 1758, 11784, 1887, 31, 203, 3639, 1758, 8526, 18115, 31, 203, 3639, 19185, 783, 12148, 31, 203, 565, 289, 203, 203, 565, 2874, 12, 1080, 516, 1758, 13, 3238, 1479, 3233, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x66AbA71fA1cF5F74e9E7Ee613c510C264776e8ae/sources/lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol
* @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]./
mapping(address => uint256) blockAt;
4,109,930
[ 1, 5394, 716, 353, 2566, 1865, 1281, 7412, 434, 2430, 18, 1220, 6104, 312, 474, 310, 471, 18305, 310, 18, 21020, 4636, 30, 300, 1347, 1375, 2080, 68, 471, 1375, 869, 68, 854, 3937, 1661, 17, 7124, 16, 1375, 8949, 68, 434, 12176, 2080, 10335, 11, 87, 2430, 903, 506, 906, 4193, 358, 1375, 869, 8338, 300, 1347, 1375, 2080, 68, 353, 3634, 16, 1375, 8949, 68, 2430, 903, 506, 312, 474, 329, 364, 1375, 869, 8338, 300, 1347, 1375, 869, 68, 353, 3634, 16, 1375, 8949, 68, 434, 12176, 2080, 10335, 11, 87, 2430, 903, 506, 18305, 329, 18, 300, 1375, 2080, 68, 471, 1375, 869, 68, 854, 5903, 3937, 3634, 18, 2974, 16094, 1898, 2973, 9153, 16, 910, 358, 15187, 30, 9185, 30, 408, 2846, 17, 16351, 87, 18, 4539, 9940, 17, 10468, 63, 7736, 13725, 87, 8009, 19, 2, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1203, 861, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/1313161554/0x910ab4bFB68386BD26b3d5D10D7191e620C721c9/sources/RORA.sol
/* @dev Enables the reward feature. Distribute transaction amount `taxReward_` amount of tokens each transaction when enabled. Emits a {EnabledReward} event. Requirements: - reward feature mush be disabled. - tax must be greater than 0. - tax decimals + 2 must be less than token decimals. (because tax rate is in percentage)/
Owner functions function enableReward(uint32 taxRewardBuy_, uint32 taxRewardSell_, uint32 taxRewardTransfer_, uint32 taxRewardDecimals_) public onlyOwner { require(!_rewardEnabled, "Reward feature is already enabled."); require(taxRewardBuy_ > 0 || taxRewardSell_ > 0 || taxRewardTransfer_ > 0, "Tax rates must be greater than 0."); require(taxRewardDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2"); _rewardEnabled = true; setTaxReward(taxRewardBuy_, taxRewardSell_, taxRewardTransfer_, taxRewardDecimals_); emit EnabledReward(); }
13,232,028
[ 1, 19, 225, 1374, 1538, 326, 19890, 2572, 18, 3035, 887, 2492, 3844, 225, 1375, 8066, 17631, 1060, 67, 68, 3844, 434, 2430, 1517, 2492, 1347, 3696, 18, 7377, 1282, 279, 288, 1526, 17631, 1060, 97, 871, 18, 29076, 30, 300, 19890, 2572, 312, 1218, 506, 5673, 18, 300, 5320, 1297, 506, 6802, 2353, 374, 18, 300, 5320, 15105, 397, 576, 1297, 506, 5242, 2353, 1147, 15105, 18, 261, 26274, 5320, 4993, 353, 316, 11622, 13176, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 3639, 16837, 4186, 203, 203, 565, 445, 4237, 17631, 1060, 12, 11890, 1578, 5320, 17631, 1060, 38, 9835, 67, 16, 2254, 1578, 5320, 17631, 1060, 55, 1165, 67, 16, 2254, 1578, 5320, 17631, 1060, 5912, 67, 16, 2254, 1578, 5320, 17631, 1060, 31809, 67, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 5, 67, 266, 2913, 1526, 16, 315, 17631, 1060, 2572, 353, 1818, 3696, 1199, 1769, 203, 3639, 2583, 12, 8066, 17631, 1060, 38, 9835, 67, 405, 374, 747, 5320, 17631, 1060, 55, 1165, 67, 405, 374, 747, 5320, 17631, 1060, 5912, 67, 405, 374, 16, 315, 7731, 17544, 1297, 506, 6802, 2353, 374, 1199, 1769, 203, 3639, 2583, 12, 8066, 17631, 1060, 31809, 67, 397, 576, 225, 1648, 15105, 9334, 315, 7731, 15105, 1297, 506, 5242, 2353, 1147, 15105, 300, 576, 8863, 203, 203, 3639, 389, 266, 2913, 1526, 273, 638, 31, 203, 3639, 444, 7731, 17631, 1060, 12, 8066, 17631, 1060, 38, 9835, 67, 16, 5320, 17631, 1060, 55, 1165, 67, 16, 5320, 17631, 1060, 5912, 67, 16, 5320, 17631, 1060, 31809, 67, 1769, 203, 203, 3639, 3626, 14666, 17631, 1060, 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 ]
pragma solidity ^0.5.0; interface ICourtStake{ function lockedStake(uint256 amount, address beneficiar, uint256 StartReleasingTime, uint256 batchCount, uint256 batchPeriod) external; } interface IMERC20 { function mint(address account, uint amount) external; } /** * @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. * * _Available since v2.4.0._ */ 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. * * _Available since v2.4.0._ */ 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. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @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. * * 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 Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing 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. */ 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. // 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 != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @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]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @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 ERC20;` 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)); } 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. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "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"); } } } contract CourtFarming_RoomLPStake { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public constant stakedToken = IERC20(0xBE55c87dFf2a9f5c95cB5C07572C51fd91fe0732); IMERC20 public constant courtToken = IMERC20(0x0538A9b4f4dcB0CB01A7fA34e17C0AC947c22553); uint256 private _totalStaked; mapping(address => uint256) private _balances; // last updated block number uint256 private _lastUpdateBlock; // incentive rewards uint256 public incvFinishBlock; // finish incentive rewarding block number uint256 private _incvRewardPerBlock; // incentive reward per block uint256 private _incvAccRewardPerToken; // accumulative reward per token mapping(address => uint256) private _incvRewards; // reward balances mapping(address => uint256) private _incvPrevAccRewardPerToken;// previous accumulative reward per token (for a user) uint256 public incvStartReleasingTime; // incentive releasing time uint256 public incvBatchPeriod; // incentive batch period uint256 public incvBatchCount; // incentive batch count mapping(address => uint256) public incvWithdrawn; address public owner; enum TransferRewardState { Succeeded, RewardsStillLocked } address public courtStakeAddress; event Staked(address indexed user, uint256 amount); event Unstaked(address indexed user, uint256 amount); event ClaimReward(address indexed user, uint256 reward); event ClaimIncentiveReward(address indexed user, uint256 reward); event StakeRewards(address indexed user, uint256 amount, uint256 lockTime); event CourtStakeChanged(address oldAddress, address newAddress); event StakeParametersChanged(uint256 incvRewardPerBlock, uint256 incvRewardFinsishBlock, uint256 incvLockTime); constructor () public { owner = msg.sender; uint256 incvRewardsPerBlock = 57870370370370369; uint256 incvRewardsPeriodInDays = 90; incvStartReleasingTime = 1620914400; // 13/05/2021 // check https://www.epochconverter.com/ for timestamp incvBatchPeriod = 1 days; incvBatchCount = 1; _stakeParametrsCalculation(incvRewardsPerBlock, incvRewardsPeriodInDays, incvStartReleasingTime); _lastUpdateBlock = blockNumber(); } function _stakeParametrsCalculation(uint256 incvRewardsPerBlock, uint256 incvRewardsPeriodInDays, uint256 iLockTime) internal{ uint256 incvRewardBlockCount = incvRewardsPeriodInDays * 5760; uint256 incvRewardPerBlock = incvRewardsPerBlock; _incvRewardPerBlock = incvRewardPerBlock * (1e18); incvFinishBlock = blockNumber().add(incvRewardBlockCount); incvStartReleasingTime = iLockTime; } function changeStakeParameters( uint256 incvRewardsPerBlock, uint256 incvRewardsPeriodInDays, uint256 iLockTime) public { require(msg.sender == owner, "can be called by owner only"); updateReward(address(0)); _stakeParametrsCalculation(incvRewardsPerBlock, incvRewardsPeriodInDays, iLockTime); emit StakeParametersChanged( _incvRewardPerBlock, incvFinishBlock, incvStartReleasingTime); } function updateReward(address account) public { // reward algorithm // in general: rewards = (reward per token ber block) user balances uint256 cnBlock = blockNumber(); // update accRewardPerToken, in case totalSupply is zero; do not increment accRewardPerToken if (_totalStaked > 0) { uint256 incvlastRewardBlock = cnBlock < incvFinishBlock ? cnBlock : incvFinishBlock; if (incvlastRewardBlock > _lastUpdateBlock) { _incvAccRewardPerToken = incvlastRewardBlock.sub(_lastUpdateBlock) .mul(_incvRewardPerBlock).div(_totalStaked) .add(_incvAccRewardPerToken); } } _lastUpdateBlock = cnBlock; if (account != address(0)) { uint256 incAccRewardPerTokenForUser = _incvAccRewardPerToken.sub(_incvPrevAccRewardPerToken[account]); if (incAccRewardPerTokenForUser > 0) { _incvRewards[account] = _balances[account] .mul(incAccRewardPerTokenForUser) .div(1e18) .add(_incvRewards[account]); _incvPrevAccRewardPerToken[account] = _incvAccRewardPerToken; } } } function stake(uint256 amount) public { updateReward(msg.sender); if (amount > 0) { _totalStaked = _totalStaked.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakedToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } } function unstake(uint256 amount, bool claim) public { updateReward(msg.sender); if (amount > 0) { _totalStaked = _totalStaked.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakedToken.safeTransfer(msg.sender, amount); emit Unstaked(msg.sender, amount); } claim = false; } function stakeIncvRewards(uint256 amount) public returns (bool) { updateReward(msg.sender); uint256 incvReward = _incvRewards[msg.sender]; if (amount > incvReward || courtStakeAddress == address(0)) { return false; } _incvRewards[msg.sender] -= amount; // no need to use safe math sub, since there is check for amount > reward courtToken.mint(address(this), amount); ICourtStake courtStake = ICourtStake(courtStakeAddress); courtStake.lockedStake(amount, msg.sender, incvStartReleasingTime, incvBatchCount, incvBatchPeriod); emit StakeRewards(msg.sender, amount, incvStartReleasingTime); } function setCourtStake(address courtStakeAdd) public { require(msg.sender == owner, "only contract owner can change"); address oldAddress = courtStakeAddress; courtStakeAddress = courtStakeAdd; IERC20 courtTokenERC20 = IERC20(address(courtToken)); courtTokenERC20.approve(courtStakeAdd, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); emit CourtStakeChanged(oldAddress, courtStakeAdd); } function rewards(address account) public view returns (uint256 reward, uint256 incvReward) { // read version of update uint256 cnBlock = blockNumber(); uint256 incvAccRewardPerToken = _incvAccRewardPerToken; // update accRewardPerToken, in case totalSupply is zero; do not increment accRewardPerToken if (_totalStaked > 0) { uint256 incvLastRewardBlock = cnBlock < incvFinishBlock ? cnBlock : incvFinishBlock; if (incvLastRewardBlock > _lastUpdateBlock) { incvAccRewardPerToken = incvLastRewardBlock.sub(_lastUpdateBlock) .mul(_incvRewardPerBlock).div(_totalStaked) .add(incvAccRewardPerToken); } } incvReward = _balances[account] .mul(incvAccRewardPerToken.sub(_incvPrevAccRewardPerToken[account])) .div(1e18) .add(_incvRewards[account]) .sub(incvWithdrawn[account]); reward = 0; } function incvRewardInfo() external view returns (uint256 cBlockNumber, uint256 incvRewardPerBlock, uint256 incvRewardFinishBlock, uint256 incvRewardFinishTime, uint256 incvRewardLockTime) { cBlockNumber = blockNumber(); incvRewardFinishBlock = incvFinishBlock; incvRewardPerBlock = _incvRewardPerBlock.div(1e18); if( cBlockNumber < incvFinishBlock){ incvRewardFinishTime = block.timestamp.add(incvFinishBlock.sub(cBlockNumber).mul(15)); }else{ incvRewardFinishTime = block.timestamp.sub(cBlockNumber.sub(incvFinishBlock).mul(15)); } incvRewardLockTime=incvStartReleasingTime; } // expected reward, // please note this is only expectation, because total balance may changed during the day function expectedRewardsToday(uint256 amount) external view returns (uint256 reward, uint256 incvReward) { reward = 0; uint256 totalIncvRewardPerDay = _incvRewardPerBlock * 5760; incvReward = totalIncvRewardPerDay.div(_totalStaked.add(amount)).mul(amount).div(1e18); } function lastUpdateBlock() external view returns(uint256) { return _lastUpdateBlock; } function balanceOf(address account) external view returns (uint256) { return _balances[account]; } function totalStaked() external view returns (uint256) { return _totalStaked; } function blockNumber() public view returns (uint256) { return block.number; } function getCurrentTime() public view returns(uint256){ return block.timestamp; } function getVestedAmount(uint256 lockedAmount, uint256 time) internal view returns(uint256){ // if time < StartReleasingTime: then return 0 if(time < incvStartReleasingTime){ return 0; } // if locked amount 0 return 0 if (lockedAmount == 0){ return 0; } // elapsedBatchCount = ((time - startReleasingTime) / batchPeriod) + 1 uint256 elapsedBatchCount = time.sub(incvStartReleasingTime) .div(incvBatchPeriod) .add(1); // vestedAmount = lockedAmount * elapsedBatchCount / batchCount uint256 vestedAmount = lockedAmount .mul(elapsedBatchCount) .div(incvBatchCount); if(vestedAmount > lockedAmount){ vestedAmount = lockedAmount; } return vestedAmount; } function incvRewardClaim() public returns(uint256 amount){ updateReward(msg.sender); amount = getVestedAmount(_incvRewards[msg.sender], getCurrentTime()).sub(incvWithdrawn[msg.sender]); if(amount > 0){ incvWithdrawn[msg.sender] = incvWithdrawn[msg.sender].add(amount); courtToken.mint(msg.sender, amount); emit ClaimIncentiveReward(msg.sender, amount); } } function getBeneficiaryInfo(address ibeneficiary) external view returns(address beneficiary, uint256 totalLocked, uint256 withdrawn, uint256 releasableAmount, uint256 nextBatchTime, uint256 currentTime){ beneficiary = ibeneficiary; currentTime = getCurrentTime(); totalLocked = _incvRewards[ibeneficiary]; withdrawn = incvWithdrawn[ibeneficiary]; ( , uint256 incvReward) = rewards(ibeneficiary); releasableAmount = getVestedAmount(incvReward, getCurrentTime()).sub(incvWithdrawn[beneficiary]); nextBatchTime = getIncNextBatchTime(incvReward, ibeneficiary, currentTime); } function getIncNextBatchTime(uint256 lockedAmount, address beneficiary, uint256 time) internal view returns(uint256){ // if total vested equal to total locked then return 0 if(getVestedAmount(lockedAmount, time) == _incvRewards[beneficiary]){ return 0; } // if time less than startReleasingTime: then return sartReleasingTime if(time <= incvStartReleasingTime){ return incvStartReleasingTime; } // find the next batch time uint256 elapsedBatchCount = time.sub(incvStartReleasingTime) .div(incvBatchPeriod) .add(1); uint256 nextBatchTime = elapsedBatchCount .mul(incvBatchPeriod) .add(incvStartReleasingTime); return nextBatchTime; } }
if total vested equal to total locked then return 0 if time less than startReleasingTime: then return sartReleasingTime
function getIncNextBatchTime(uint256 lockedAmount, address beneficiary, uint256 time) internal view returns(uint256){ if(getVestedAmount(lockedAmount, time) == _incvRewards[beneficiary]){ return 0; } if(time <= incvStartReleasingTime){ return incvStartReleasingTime; } time.sub(incvStartReleasingTime) .div(incvBatchPeriod) .add(1); uint256 nextBatchTime = elapsedBatchCount .mul(incvBatchPeriod) .add(incvStartReleasingTime); return nextBatchTime; }
1,711,379
[ 1, 430, 2078, 331, 3149, 3959, 358, 2078, 8586, 1508, 327, 374, 309, 813, 5242, 2353, 787, 17018, 11730, 950, 30, 1508, 327, 272, 485, 17018, 11730, 950, 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, 7854, 71, 2134, 4497, 950, 12, 11890, 5034, 8586, 6275, 16, 1758, 27641, 74, 14463, 814, 16, 2254, 5034, 813, 13, 2713, 1476, 1135, 12, 11890, 5034, 15329, 203, 203, 3639, 309, 12, 588, 58, 3149, 6275, 12, 15091, 6275, 16, 813, 13, 422, 389, 9523, 90, 17631, 14727, 63, 70, 4009, 74, 14463, 814, 5717, 95, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 309, 12, 957, 1648, 7290, 90, 1685, 17018, 11730, 950, 15329, 203, 5411, 327, 7290, 90, 1685, 17018, 11730, 950, 31, 203, 3639, 289, 203, 203, 3639, 813, 18, 1717, 12, 9523, 90, 1685, 17018, 11730, 950, 13, 203, 3639, 263, 2892, 12, 9523, 90, 4497, 5027, 13, 203, 3639, 263, 1289, 12, 21, 1769, 203, 203, 3639, 2254, 5034, 1024, 4497, 950, 273, 203, 3639, 9613, 4497, 1380, 203, 3639, 263, 16411, 12, 9523, 90, 4497, 5027, 13, 203, 3639, 263, 1289, 12, 9523, 90, 1685, 17018, 11730, 950, 1769, 203, 203, 3639, 327, 1024, 4497, 950, 31, 203, 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 ]
./partial_match/1/0xABD0061755A180052703f72F06CEf8c2Eb1384B6/sources/new.sol
exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract BahamasNetwork is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public marketingWallet; address public devWallet; address public lpWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; bool inSwap; mapping (address => bool) public _unauthorized; mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event LimitsRemoved(); 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 lpWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); modifier swapping() { inSwap = true; _; inSwap = false; } constructor() ERC20("Bahamas Network", "BN") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 12; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 8; uint256 _sellMarketingFee = 15; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 10; uint256 totalSupply = 10000000 * 1e9; maxTransactionAmount = (totalSupply * 1) /100; maxWallet = (totalSupply * 1)/ 100; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0xa1DF493DF409f5F2b28b676EcF9c64B2Cb89f106); devWallet = address(0xa1DF493DF409f5F2b28b676EcF9c64B2Cb89f106); lpWallet = msg.sender; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromFees(marketingWallet, true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromMaxTransaction(marketingWallet, true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply); } receive() external payable {} function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; } function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; emit LimitsRemoved(); return true; } function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= ((totalSupply() * 1) / 10000) / 1e9, "Swap amount cannot be lower than 0.01% total supply." ); require( newAmount <= ((totalSupply() * 1) / 100) / 1e9, "Swap amount cannot be higher than 1% total supply." ); swapTokensAtAmount = newAmount * 1e9; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 5) / 1000) / 1e9, "Cannot set maxTransactionAmount lower than 0.5%" ); maxTransactionAmount = newNum * 1e9; } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 100) / 1e9, "Cannot set maxWallet lower than 1%" ); maxWallet = newNum * 1e9; } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function updateBuyFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { require((_marketingFee + _liquidityFee + _devFee) <= 25 ,"Buy fee cant be sent more than 25%"); buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; } function updateSellFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { require((_marketingFee + _liquidityFee + _devFee) <= 25 ,"Sell fee cant be sent more than 25% "); sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } 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 != uniswapV2Pair, "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 updateLPWallet(address newLPWallet) external onlyOwner { emit lpWalletUpdated(newLPWallet, lpWallet); lpWallet = newLPWallet; } 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"); require(!_unauthorized[from] && !_unauthorized[to]); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwap ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !inSwap && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapBack(); } bool takeFee = !inSwap; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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"); require(!_unauthorized[from] && !_unauthorized[to]); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwap ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !inSwap && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapBack(); } bool takeFee = !inSwap; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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"); require(!_unauthorized[from] && !_unauthorized[to]); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwap ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !inSwap && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapBack(); } bool takeFee = !inSwap; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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"); require(!_unauthorized[from] && !_unauthorized[to]); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwap ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !inSwap && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapBack(); } bool takeFee = !inSwap; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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"); require(!_unauthorized[from] && !_unauthorized[to]); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwap ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !inSwap && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapBack(); } bool takeFee = !inSwap; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } if ( 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"); require(!_unauthorized[from] && !_unauthorized[to]); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwap ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !inSwap && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapBack(); } bool takeFee = !inSwap; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } else if ( 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"); require(!_unauthorized[from] && !_unauthorized[to]); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwap ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !inSwap && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapBack(); } bool takeFee = !inSwap; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } } else if (!_isExcludedMaxTransactionAmount[to]) { 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"); require(!_unauthorized[from] && !_unauthorized[to]); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwap ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !inSwap && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapBack(); } bool takeFee = !inSwap; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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"); require(!_unauthorized[from] && !_unauthorized[to]); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwap ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !inSwap && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapBack(); } bool takeFee = !inSwap; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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"); require(!_unauthorized[from] && !_unauthorized[to]); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwap ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !inSwap && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapBack(); } bool takeFee = !inSwap; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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"); require(!_unauthorized[from] && !_unauthorized[to]); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwap ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !inSwap && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapBack(); } bool takeFee = !inSwap; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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"); require(!_unauthorized[from] && !_unauthorized[to]); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwap ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !inSwap && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapBack(); } bool takeFee = !inSwap; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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"); require(!_unauthorized[from] && !_unauthorized[to]); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwap ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !inSwap && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapBack(); } bool takeFee = !inSwap; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function manageUnauthorizedAddress(address unauth, bool value) public onlyOwner{ require(unauth != uniswapV2Pair); _unauthorized[unauth] = value; } function manageUnauthorizedAddresses(address[] memory unauths, bool value) public onlyOwner{ for(uint256 i = 0; i < unauths.length; i++){ require(unauths[i] != uniswapV2Pair); _unauthorized[unauths[i]] = value; } } function manageUnauthorizedAddresses(address[] memory unauths, bool value) public onlyOwner{ for(uint256 i = 0; i < unauths.length; i++){ require(unauths[i] != uniswapV2Pair); _unauthorized[unauths[i]] = value; } } function manualSwapBack() external onlyOwner { swapBack(); } 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 addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, lpWallet, block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapBack() private swapping{ uint256 contractBalance = balanceOf(address(this)); uint256 TotalLiquidityFee = buyLiquidityFee + sellLiquidityFee; uint256 TotalDevFee = buyDevFee + sellDevFee; uint256 TotalFees = buyTotalFees + sellTotalFees; uint256 totalTokensToSwap = swapTokensAtAmount; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } uint256 amountToSwapForETH = totalTokensToSwap.sub(liquidityTokens); swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance; uint256 ethForDev = ethBalance.mul(TotalDevFee).div(TotalFees); uint256 ethForLiquidity = ethBalance.mul(TotalLiquidityFee).div(TotalFees); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, liquidityTokens ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function swapBack() private swapping{ uint256 contractBalance = balanceOf(address(this)); uint256 TotalLiquidityFee = buyLiquidityFee + sellLiquidityFee; uint256 TotalDevFee = buyDevFee + sellDevFee; uint256 TotalFees = buyTotalFees + sellTotalFees; uint256 totalTokensToSwap = swapTokensAtAmount; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } uint256 amountToSwapForETH = totalTokensToSwap.sub(liquidityTokens); swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance; uint256 ethForDev = ethBalance.mul(TotalDevFee).div(TotalFees); uint256 ethForLiquidity = ethBalance.mul(TotalLiquidityFee).div(TotalFees); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, liquidityTokens ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } uint256 liquidityTokens = ((totalTokensToSwap * TotalLiquidityFee) / TotalFees ) / 2; (success, ) = address(devWallet).call{value: ethForDev}(""); function swapBack() private swapping{ uint256 contractBalance = balanceOf(address(this)); uint256 TotalLiquidityFee = buyLiquidityFee + sellLiquidityFee; uint256 TotalDevFee = buyDevFee + sellDevFee; uint256 TotalFees = buyTotalFees + sellTotalFees; uint256 totalTokensToSwap = swapTokensAtAmount; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } uint256 amountToSwapForETH = totalTokensToSwap.sub(liquidityTokens); swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance; uint256 ethForDev = ethBalance.mul(TotalDevFee).div(TotalFees); uint256 ethForLiquidity = ethBalance.mul(TotalLiquidityFee).div(TotalFees); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, liquidityTokens ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function swapBack() private swapping{ uint256 contractBalance = balanceOf(address(this)); uint256 TotalLiquidityFee = buyLiquidityFee + sellLiquidityFee; uint256 TotalDevFee = buyDevFee + sellDevFee; uint256 TotalFees = buyTotalFees + sellTotalFees; uint256 totalTokensToSwap = swapTokensAtAmount; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } uint256 amountToSwapForETH = totalTokensToSwap.sub(liquidityTokens); swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance; uint256 ethForDev = ethBalance.mul(TotalDevFee).div(TotalFees); uint256 ethForLiquidity = ethBalance.mul(TotalLiquidityFee).div(TotalFees); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, liquidityTokens ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } }
15,579,561
[ 1, 338, 17704, 1317, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 16351, 605, 9795, 301, 345, 3906, 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, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 203, 565, 1758, 1071, 13667, 310, 16936, 31, 203, 565, 1758, 1071, 4461, 16936, 31, 203, 565, 1758, 1071, 12423, 16936, 31, 203, 203, 565, 2254, 5034, 1071, 943, 3342, 6275, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 203, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 629, 31, 203, 203, 565, 2254, 5034, 1071, 30143, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 30143, 3882, 21747, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 48, 18988, 24237, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 8870, 14667, 31, 203, 203, 565, 2254, 5034, 1071, 357, 80, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 357, 80, 3882, 21747, 14667, 31, 203, 565, 2254, 5034, 1071, 357, 80, 48, 18988, 24237, 14667, 31, 203, 565, 2254, 5034, 1071, 357, 80, 8870, 14667, 31, 203, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 2954, 281, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 389, 291, 2 ]
./partial_match/1/0x1e5Ec00e7598d3f60471e45138c5d3c5172326eB/sources/contracts/AvoFactory.sol
empty interface used for Natspec docs for nice layout in automatically generated docs: @title AvoFactory v1.0.0 @notice Deploys Avocado smart wallet contracts at deterministic addresses using Create2. Upgradeable through AvoFactoryProxy
interface AvoFactory_V1 { pragma solidity >=0.8.18; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import { IAvocado } from "./Avocado.sol"; import { IAvocadoMultisigV1 } from "./interfaces/IAvocadoMultisigV1.sol"; import { IAvoRegistry } from "./interfaces/IAvoRegistry.sol"; import { IAvoFactory } from "./interfaces/IAvoFactory.sol"; import { IAvoForwarder } from "./interfaces/IAvoForwarder.sol"; }
9,166,788
[ 1, 5531, 1560, 1399, 364, 423, 2323, 705, 3270, 364, 13752, 3511, 316, 6635, 4374, 3270, 30, 282, 8789, 83, 1733, 331, 21, 18, 20, 18, 20, 225, 4019, 383, 1900, 8789, 504, 6821, 13706, 9230, 20092, 622, 25112, 6138, 1450, 1788, 22, 18, 17699, 429, 3059, 8789, 83, 1733, 3886, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 5831, 8789, 83, 1733, 67, 58, 21, 288, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 28, 18, 2643, 31, 203, 5666, 288, 5267, 289, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 5471, 19, 1887, 18, 18281, 14432, 203, 5666, 288, 10188, 6934, 289, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 17, 15097, 429, 19, 5656, 19, 5471, 19, 4435, 6934, 18, 18281, 14432, 203, 5666, 288, 467, 3769, 504, 6821, 289, 628, 25165, 3769, 504, 6821, 18, 18281, 14432, 203, 5666, 288, 467, 3769, 504, 6821, 5049, 291, 360, 58, 21, 289, 628, 25165, 15898, 19, 45, 3769, 504, 6821, 5049, 291, 360, 58, 21, 18, 18281, 14432, 203, 5666, 288, 467, 3769, 83, 4243, 289, 628, 25165, 15898, 19, 45, 3769, 83, 4243, 18, 18281, 14432, 203, 5666, 288, 467, 3769, 83, 1733, 289, 628, 25165, 15898, 19, 45, 3769, 83, 1733, 18, 18281, 14432, 203, 5666, 288, 467, 3769, 83, 30839, 289, 628, 25165, 15898, 19, 45, 3769, 83, 30839, 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 ]
./full_match/80001/0xe13f70F0d60A0ADEcB451aECaed71e3cB7e12EDe/sources/contracts/Boxes.sol
a list of all boxes owned by the user user address => array of Boxes
mapping (address => Box[]) public boxesByUser;
5,673,736
[ 1, 69, 666, 434, 777, 14356, 16199, 635, 326, 729, 729, 1758, 516, 526, 434, 8549, 281, 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, 2874, 261, 2867, 516, 8549, 63, 5717, 1071, 14356, 25895, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-07-09 */ /** *Submitted for verification at Etherscan.io on 2020-07-09 */ pragma solidity 0.5.7; /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ contract INXMMaster { address public tokenAddress; address public owner; uint public pauseTime; function delegateCallBack(bytes32 myid) external; function masterInitialized() public view returns(bool); function isInternal(address _add) public view returns(bool); function isPause() public view returns(bool check); function isOwner(address _add) public view returns(bool); function isMember(address _add) public view returns(bool); function checkIsAuthToGoverned(address _add) public view returns(bool); function updatePauseTime(uint _time) public; function dAppLocker() public view returns(address _add); function dAppToken() public view returns(address _add); function getLatestAddress(bytes2 _contractName) public view returns(address payable contractAddress); } contract Iupgradable { INXMMaster public ms; address public nxMasterAddress; modifier onlyInternal { require(ms.isInternal(msg.sender)); _; } modifier isMemberAndcheckPause { require(ms.isPause() == false && ms.isMember(msg.sender) == true); _; } modifier onlyOwner { require(ms.isOwner(msg.sender)); _; } modifier checkPause { require(ms.isPause() == false); _; } modifier isMember { require(ms.isMember(msg.sender), "Not member"); _; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public; /** * @dev change master address * @param _masterAddress is the new address */ function changeMasterAddress(address _masterAddress) public { if (address(ms) != address(0)) { require(address(ms) == msg.sender, "Not master"); } ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } } /** * @title ERC1132 interface * @dev see https://github.com/ethereum/EIPs/issues/1132 */ contract IERC1132 { /** * @dev Reasons why a user's tokens have been locked */ mapping(address => bytes32[]) public lockReason; /** * @dev locked token structure */ struct LockToken { uint256 amount; uint256 validity; bool claimed; } /** * @dev Holds number & validity of tokens locked for a given reason for * a specified address */ mapping(address => mapping(bytes32 => LockToken)) public locked; /** * @dev Records data of all the tokens Locked */ event Locked( address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity ); /** * @dev Records data of all the tokens unlocked */ event Unlocked( address indexed _of, bytes32 indexed _reason, uint256 _amount ); /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function lock(bytes32 _reason, uint256 _amount, uint256 _time) public returns (bool); /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount); /** * @dev Returns total tokens held by an address (locked + transferable) * @param _of The address to query the total balance of */ function totalBalanceOf(address _of) public view returns (uint256 amount); /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLock(bytes32 _reason, uint256 _time) public returns (bool); /** * @dev Increase number of tokens locked for a specified reason * @param _reason The reason to lock tokens * @param _amount Number of tokens to be increased */ function increaseLockAmount(bytes32 _reason, uint256 _amount) public returns (bool); /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Unlocks the unlockable tokens of a specified address * @param _of Address of user, claiming back unlockable tokens */ function unlock(address _of) public returns (uint256 unlockableTokens); /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { 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); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, 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 numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts 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 Subtracts two numbers, 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 numbers, 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 numbers 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; } } /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ contract NXMToken is IERC20 { using SafeMath for uint256; event WhiteListed(address indexed member); event BlackListed(address indexed member); mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; mapping (address => bool) public whiteListed; mapping(address => uint) public isLockedForMV; uint256 private _totalSupply; string public name = "NXM"; string public symbol = "NXM"; uint8 public decimals = 18; address public operator; modifier canTransfer(address _to) { require(whiteListed[_to]); _; } modifier onlyOperator() { if (operator != address(0)) require(msg.sender == operator); _; } constructor(address _founderAddress, uint _initialSupply) public { _mint(_founderAddress, _initialSupply); } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query 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]; } /** * @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 Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @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 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 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 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 Adds a user to whitelist * @param _member address to add to whitelist */ function addToWhiteList(address _member) public onlyOperator returns (bool) { whiteListed[_member] = true; emit WhiteListed(_member); return true; } /** * @dev removes a user from whitelist * @param _member address to remove from whitelist */ function removeFromWhiteList(address _member) public onlyOperator returns (bool) { whiteListed[_member] = false; emit BlackListed(_member); return true; } /** * @dev change operator address * @param _newOperator address of new operator */ function changeOperator(address _newOperator) public onlyOperator returns (bool) { operator = _newOperator; return true; } /** * @dev burns an amount of the tokens of the message sender * account. * @param amount The amount that will be burnt. */ function burn(uint256 amount) public returns (bool) { _burn(msg.sender, amount); return true; } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public returns (bool) { _burnFrom(from, value); return true; } /** * @dev function that mints an amount of the token and assigns it to * an account. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function mint(address account, uint256 amount) public onlyOperator { _mint(account, amount); } /** * @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 canTransfer(to) returns (bool) { require(isLockedForMV[msg.sender] < now); // if not voted under governance require(value <= _balances[msg.sender]); _transfer(to, value); return true; } /** * @dev Transfer tokens to the operator from the specified address * @param from The address to transfer from. * @param value The amount to be transferred. */ function operatorTransfer(address from, uint256 value) public onlyOperator returns (bool) { require(value <= _balances[from]); _transferFrom(from, operator, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public canTransfer(to) returns (bool) { require(isLockedForMV[from] < now); // if not voted under governance require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); _transferFrom(from, to, value); return true; } /** * @dev Lock the user's tokens * @param _of user's address. */ function lockForMemberVote(address _of, uint _days) public onlyOperator { if (_days.add(now) > isLockedForMV[_of]) isLockedForMV[_of] = _days.add(now); } /** * @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) internal { _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); } /** * @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 ) internal { _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); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function _mint(address account, uint256 amount) internal { require(account != address(0)); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burn(address account, uint256 amount) internal { require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } interface IPooledStaking { function pushReward(address contractAddress, uint amount) external; function pushBurn(address contractAddress, uint amount) external; function hasPendingActions() external view returns (bool); function contractStake(address contractAddress) external view returns (uint); function stakerReward(address staker) external view returns (uint); function stakerDeposit(address staker) external view returns (uint); function stakerContractStake(address staker, address contractAddress) external view returns (uint); function withdraw(uint amount) external; function stakerMaxWithdrawable(address stakerAddress) external view returns (uint); function withdrawReward(address stakerAddress) external; } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ contract TokenController is IERC1132, Iupgradable { using SafeMath for uint256; event Burned(address indexed member, bytes32 lockedUnder, uint256 amount); NXMToken public token; IPooledStaking public pooledStaking; uint public minCALockTime = uint(30).mul(1 days); bytes32 private constant CLA = bytes32("CLA"); /** * @dev Just for interface */ function changeDependentContractAddress() public { token = NXMToken(ms.tokenAddress()); pooledStaking = IPooledStaking(ms.getLatestAddress('PS')); } /** * @dev to change the operator address * @param _newOperator is the new address of operator */ function changeOperator(address _newOperator) public onlyInternal { token.changeOperator(_newOperator); } /** * @dev Proxies token transfer through this contract to allow staking when members are locked for voting * @param _from Source address * @param _to Destination address * @param _value Amount to transfer */ function operatorTransfer(address _from, address _to, uint _value) onlyInternal external returns (bool) { require(msg.sender == address(pooledStaking), "Call is only allowed from PooledStaking address"); require(token.operatorTransfer(_from, _value), "Operator transfer failed"); require(token.transfer(_to, _value), "Internal transfer failed"); return true; } /** * @dev Locks a specified amount of tokens, * for CLA reason and for a specified time * @param _reason The reason to lock tokens, currently restricted to CLA * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function lock(bytes32 _reason, uint256 _amount, uint256 _time) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); require(minCALockTime <= _time,"Should lock for minimum time"); // If tokens are already locked, then functions extendLock or // increaseLockAmount should be used to make any changes _lock(msg.sender, _reason, _amount, _time); return true; } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds * @param _of address whose tokens are to be locked */ function lockOf(address _of, bytes32 _reason, uint256 _amount, uint256 _time) public onlyInternal returns (bool) { // If tokens are already locked, then functions extendLock or // increaseLockAmount should be used to make any changes _lock(_of, _reason, _amount, _time); return true; } /** * @dev Extends lock for reason CLA for a specified time * @param _reason The reason to lock tokens, currently restricted to CLA * @param _time Lock extension time in seconds */ function extendLock(bytes32 _reason, uint256 _time) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); _extendLock(msg.sender, _reason, _time); return true; } /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLockOf(address _of, bytes32 _reason, uint256 _time) public onlyInternal returns (bool) { _extendLock(_of, _reason, _time); return true; } /** * @dev Increase number of tokens locked for a CLA reason * @param _reason The reason to lock tokens, currently restricted to CLA * @param _amount Number of tokens to be increased */ function increaseLockAmount(bytes32 _reason, uint256 _amount) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); require(_tokensLocked(msg.sender, _reason) > 0); token.operatorTransfer(msg.sender, _amount); locked[msg.sender][_reason].amount = locked[msg.sender][_reason].amount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW emit Locked(msg.sender, _reason, _amount, locked[msg.sender][_reason].validity); return true; } /** * @dev burns tokens of an address * @param _of is the address to burn tokens of * @param amount is the amount to burn * @return the boolean status of the burning process */ function burnFrom (address _of, uint amount) public onlyInternal returns (bool) { return token.burnFrom(_of, amount); } /** * @dev Burns locked tokens of a user * @param _of address whose tokens are to be burned * @param _reason lock reason for which tokens are to be burned * @param _amount amount of tokens to burn */ function burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal { _burnLockedTokens(_of, _reason, _amount); } /** * @dev reduce lock duration for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock reduction time in seconds */ function reduceLock(address _of, bytes32 _reason, uint256 _time) public onlyInternal { _reduceLock(_of, _reason, _time); } /** * @dev Released locked tokens of an address locked for a specific reason * @param _of address whose tokens are to be released from lock * @param _reason reason of the lock * @param _amount amount of tokens to release */ function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal { _releaseLockedTokens(_of, _reason, _amount); } /** * @dev Adds an address to whitelist maintained in the contract * @param _member address to add to whitelist */ function addToWhitelist(address _member) public onlyInternal { token.addToWhiteList(_member); } /** * @dev Removes an address from the whitelist in the token * @param _member address to remove */ function removeFromWhitelist(address _member) public onlyInternal { token.removeFromWhiteList(_member); } /** * @dev Mints new token for an address * @param _member address to reward the minted tokens * @param _amount number of tokens to mint */ function mint(address _member, uint _amount) public onlyInternal { token.mint(_member, _amount); } /** * @dev Lock the user's tokens * @param _of user's address. */ function lockForMemberVote(address _of, uint _days) public onlyInternal { token.lockForMemberVote(_of, _days); } /** * @dev Unlocks the unlockable tokens against CLA of a specified address * @param _of Address of user, claiming back unlockable tokens against CLA */ function unlock(address _of) public checkPause returns (uint256 unlockableTokens) { unlockableTokens = _tokensUnlockable(_of, CLA); if (unlockableTokens > 0) { locked[_of][CLA].claimed = true; emit Unlocked(_of, CLA, unlockableTokens); require(token.transfer(_of, unlockableTokens)); } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "MNCLT") { minCALockTime = val.mul(1 days); } else { revert("Invalid param code"); } } /** * @dev Gets the validity of locked tokens of a specified address * @param _of The address to query the validity * @param reason reason for which tokens were locked */ function getLockedTokensValidity(address _of, bytes32 reason) public view returns (uint256 validity) { validity = locked[_of][reason].validity; } /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens) { for (uint256 i = 0; i < lockReason[_of].length; i++) { unlockableTokens = unlockableTokens.add(_tokensUnlockable(_of, lockReason[_of][i])); } } /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount) { return _tokensLocked(_of, _reason); } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount) { return _tokensUnlockable(_of, _reason); } function totalSupply() public view returns (uint256) { return token.totalSupply(); } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount) { return _tokensLockedAtTime(_of, _reason, _time); } /** * @dev Returns the total amount of tokens held by an address: * transferable + locked + staked for pooled staking - pending burns. * Used by Claims and Governance in member voting to calculate the user's vote weight. * * @param _of The address to query the total balance of * @param _of The address to query the total balance of */ function totalBalanceOf(address _of) public view returns (uint256 amount) { amount = token.balanceOf(_of); for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(_tokensLocked(_of, lockReason[_of][i])); } uint stakerReward = pooledStaking.stakerReward(_of); uint stakerDeposit = pooledStaking.stakerDeposit(_of); amount = amount.add(stakerDeposit).add(stakerReward); } /** * @dev Returns the total locked tokens at time * Returns the total amount of locked and staked tokens at a given time. Used by MemberRoles to check eligibility * for withdraw / switch membership. Includes tokens locked for Claim Assessment and staked for Risk Assessment. * Does not take into account pending burns. * * @param _of member whose locked tokens are to be calculate * @param _time timestamp when the tokens should be locked */ function totalLockedBalance(address _of, uint256 _time) public view returns (uint256 amount) { for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(_tokensLockedAtTime(_of, lockReason[_of][i], _time)); } amount = amount.add(pooledStaking.stakerDeposit(_of)); } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _of address whose tokens are to be locked * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function _lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time) internal { require(_tokensLocked(_of, _reason) == 0); require(_amount != 0); if (locked[_of][_reason].amount == 0) { lockReason[_of].push(_reason); } require(token.operatorTransfer(_of, _amount)); uint256 validUntil = now.add(_time); //solhint-disable-line locked[_of][_reason] = LockToken(_amount, validUntil, false); emit Locked(_of, _reason, _amount, validUntil); } /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function _tokensLocked(address _of, bytes32 _reason) internal view returns (uint256 amount) { if (!locked[_of][_reason].claimed) { amount = locked[_of][_reason].amount; } } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function _tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) internal view returns (uint256 amount) { if (locked[_of][_reason].validity > _time) { amount = locked[_of][_reason].amount; } } /** * @dev Extends lock for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function _extendLock(address _of, bytes32 _reason, uint256 _time) internal { require(_tokensLocked(_of, _reason) > 0); emit Unlocked(_of, _reason, locked[_of][_reason].amount); locked[_of][_reason].validity = locked[_of][_reason].validity.add(_time); emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity); } /** * @dev reduce lock duration for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock reduction time in seconds */ function _reduceLock(address _of, bytes32 _reason, uint256 _time) internal { require(_tokensLocked(_of, _reason) > 0); emit Unlocked(_of, _reason, locked[_of][_reason].amount); locked[_of][_reason].validity = locked[_of][_reason].validity.sub(_time); emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity); } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function _tokensUnlockable(address _of, bytes32 _reason) internal view returns (uint256 amount) { if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) { amount = locked[_of][_reason].amount; } } /** * @dev Burns locked tokens of a user * @param _of address whose tokens are to be burned * @param _reason lock reason for which tokens are to be burned * @param _amount amount of tokens to burn */ function _burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal { uint256 amount = _tokensLocked(_of, _reason); require(amount >= _amount); if (amount == _amount) { locked[_of][_reason].claimed = true; } locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount); if (locked[_of][_reason].amount == 0) { _removeReason(_of, _reason); } token.burn(_amount); emit Burned(_of, _reason, _amount); } /** * @dev Released locked tokens of an address locked for a specific reason * @param _of address whose tokens are to be released from lock * @param _reason reason of the lock * @param _amount amount of tokens to release */ function _releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal { uint256 amount = _tokensLocked(_of, _reason); require(amount >= _amount); if (amount == _amount) { locked[_of][_reason].claimed = true; } locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount); if (locked[_of][_reason].amount == 0) { _removeReason(_of, _reason); } require(token.transfer(_of, _amount)); emit Unlocked(_of, _reason, _amount); } function _removeReason(address _of, bytes32 _reason) internal { uint len = lockReason[_of].length; for (uint i = 0; i < len; i++) { if (lockReason[_of][i] == _reason) { lockReason[_of][i] = lockReason[_of][len.sub(1)]; lockReason[_of].pop(); break; } } } }
* @dev Multiplies two numbers, reverts on overflow./ 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
function lock(bytes32 _reason, uint256 _amount, uint256 _time) public returns (bool); function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount); function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount); function totalBalanceOf(address _of) public view returns (uint256 amount); function extendLock(bytes32 _reason, uint256 _time) public returns (bool); function increaseLockAmount(bytes32 _reason, uint256 _amount) public returns (bool); function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount); function unlock(address _of) public returns (uint256 unlockableTokens); function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens); } } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; }
5,376,626
[ 1, 5002, 5259, 2795, 5600, 16, 15226, 87, 603, 9391, 18, 19, 31849, 14850, 30, 333, 353, 19315, 7294, 2353, 29468, 296, 69, 11, 486, 3832, 3634, 16, 1496, 326, 27641, 7216, 353, 13557, 309, 296, 70, 11, 353, 2546, 18432, 18, 2164, 30, 2333, 30, 6662, 18, 832, 19, 3678, 62, 881, 84, 292, 267, 19, 3190, 94, 881, 84, 292, 267, 17, 30205, 560, 19, 13469, 19, 25, 3787, 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, 2176, 12, 3890, 1578, 389, 10579, 16, 2254, 5034, 389, 8949, 16, 2254, 5034, 389, 957, 13, 203, 3639, 1071, 1135, 261, 6430, 1769, 203, 21281, 565, 445, 2430, 8966, 12, 2867, 389, 792, 16, 1731, 1578, 389, 10579, 13, 203, 3639, 1071, 1476, 1135, 261, 11890, 5034, 3844, 1769, 203, 377, 203, 565, 445, 2430, 8966, 861, 950, 12, 2867, 389, 792, 16, 1731, 1578, 389, 10579, 16, 2254, 5034, 389, 957, 13, 203, 3639, 1071, 1476, 1135, 261, 11890, 5034, 3844, 1769, 203, 377, 203, 565, 445, 2078, 13937, 951, 12, 2867, 389, 792, 13, 203, 3639, 1071, 1476, 1135, 261, 11890, 5034, 3844, 1769, 203, 377, 203, 565, 445, 2133, 2531, 12, 3890, 1578, 389, 10579, 16, 2254, 5034, 389, 957, 13, 203, 3639, 1071, 1135, 261, 6430, 1769, 203, 377, 203, 565, 445, 10929, 2531, 6275, 12, 3890, 1578, 389, 10579, 16, 2254, 5034, 389, 8949, 13, 203, 3639, 1071, 1135, 261, 6430, 1769, 203, 203, 565, 445, 2430, 7087, 429, 12, 2867, 389, 792, 16, 1731, 1578, 389, 10579, 13, 203, 3639, 1071, 1476, 1135, 261, 11890, 5034, 3844, 1769, 203, 7010, 565, 445, 7186, 12, 2867, 389, 792, 13, 203, 3639, 1071, 1135, 261, 11890, 5034, 7186, 429, 5157, 1769, 203, 203, 565, 445, 336, 7087, 429, 5157, 12, 2867, 389, 792, 13, 203, 3639, 1071, 1476, 1135, 261, 11890, 5034, 7186, 429, 5157, 1769, 203, 203, 97, 203, 203, 97, 203, 203, 565, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; //Interfaces import './interfaces/ISettings.sol'; //Inheritance import './Ownable.sol'; contract Settings is ISettings, Ownable { mapping (string => uint) public parameters; /** * @notice Initial parameters and values: * MaximumNumberOfPoolsPerUser - 2; * MaximumPerformanceFee - 30% (3000 / 10000); * MaximumNumberOfPositionsInPool - 6; * MarketplaceProtocolFee - 1% (100 / 10000) * MarketplaceAssetManagerFee - 2% (200 / 10000) * MaximumNumberOfNFTPoolTokens - 1,000,000 * MinimumNumberOfNFTPoolTokens - 10 * MaximumNFTPoolSeedPrice - $1,000 (10 ** 21) * MinimumNFTPoolSeedPrice - $0.10 (10 ** 17) */ constructor() Ownable() {} /* ========== VIEWS ========== */ /** * @dev Given the name of a parameter, returns the value of the parameter * @param parameter The name of the parameter to get value for * @return uint The value of the given parameter */ function getParameterValue(string memory parameter) external view override returns(uint) { return parameters[parameter]; } /* ========== RESTRICTED FUNCTIONS ========== */ /** * @dev Updates the address for the given contract; meant to be called by Settings contract owner * @param parameter The name of the parameter to change * @param newValue The new value of the given parameter */ function setParameterValue(string memory parameter, uint newValue) external onlyOwner { require(newValue > 0, "Value cannot be negative"); uint oldValue = parameters[parameter]; parameters[parameter] = newValue; emit SetParameterValue(parameter, oldValue, newValue, block.timestamp); } /* ========== MODIFIERS ========== */ modifier isValidAddress(address addressToCheck) { require(addressToCheck != address(0), "Address is not valid"); _; } /* ========== EVENTS ========== */ event SetParameterValue(string parameter,uint oldValue, uint newValue, uint timestamp); }
* @notice Initial parameters and values: MaximumNumberOfPoolsPerUser - 2; MaximumPerformanceFee - 30% (3000 / 10000); MaximumNumberOfPositionsInPool - 6; MarketplaceProtocolFee - 1% (100 / 10000) MarketplaceAssetManagerFee - 2% (200 / 10000) MaximumNumberOfNFTPoolTokens - 1,000,000 MinimumNumberOfNFTPoolTokens - 10 MaximumNFTPoolSeedPrice - $1,000 (10 21) MinimumNFTPoolSeedPrice - $0.10 (10 17)/
constructor() Ownable() {}
952,265
[ 1, 4435, 1472, 471, 924, 30, 540, 18848, 9226, 16639, 2173, 1299, 300, 576, 31, 540, 18848, 25024, 14667, 300, 5196, 9, 261, 23, 3784, 342, 12619, 1769, 540, 18848, 9226, 11024, 382, 2864, 300, 1666, 31, 540, 6622, 24577, 5752, 14667, 300, 404, 9, 261, 6625, 342, 12619, 13, 540, 6622, 24577, 6672, 1318, 14667, 300, 576, 9, 261, 6976, 342, 12619, 13, 540, 18848, 9226, 50, 4464, 2864, 5157, 300, 404, 16, 3784, 16, 3784, 540, 23456, 9226, 50, 4464, 2864, 5157, 300, 1728, 540, 18848, 50, 4464, 2864, 12702, 5147, 300, 271, 21, 16, 3784, 261, 2163, 225, 9035, 13, 540, 23456, 50, 4464, 2864, 12702, 5147, 300, 271, 20, 18, 2163, 261, 2163, 225, 8043, 13176, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 3885, 1435, 14223, 6914, 1435, 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, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-03-15 */ /** *Submitted for verification at Etherscan.io on 2020-05-19 */ pragma solidity ^0.4.23; /** * @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 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; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } /** * @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 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); } 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) { require((_value == 0 ) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public 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 GBAA is StandardToken{ string public constant name = "GBAA"; // solium-disable-line uppercase string public constant symbol = "GBAA"; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase uint256 public constant INITIAL_SUPPLY = 88488600000000000000000000; uint256 public constant MAX_SUPPLY = 100 * 10000 * 10000 * (10 ** uint256(decimals)); /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor() GBAA() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } /** * The fallback function. */ function() payable public { revert(); } }
* @dev Constructor that gives msg.sender all of existing tokens./
constructor() GBAA() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); }
15,322,056
[ 1, 6293, 716, 14758, 1234, 18, 15330, 777, 434, 2062, 2430, 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 ]
[ 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, 12316, 1435, 25069, 5284, 1435, 1071, 288, 203, 4963, 3088, 1283, 67, 273, 28226, 67, 13272, 23893, 31, 203, 70, 26488, 63, 3576, 18, 15330, 65, 273, 28226, 67, 13272, 23893, 31, 203, 18356, 12279, 12, 20, 92, 20, 16, 1234, 18, 15330, 16, 28226, 67, 13272, 23893, 1769, 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, -100, -100, -100, -100, -100, -100, -100, -100, -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-03-19 */ /** *Submitted for verification at Etherscan.io on 2017-12-31 */ pragma solidity ^0.4.18; // ----------------------------------------------------------------------------------------------- // CryptoCatsMarket v3 // // Ethereum contract for Cryptocats (cryptocats.thetwentysix.io), // a digital asset marketplace DAPP for unique 8-bit cats on the Ethereum blockchain. // // Versions: // 3.0 - Bug fix to make ETH value sent in with getCat function withdrawable by contract owner. // Special thanks to BokkyPooBah (https://github.com/bokkypoobah) who found this issue! // 2.0 - Remove claimCat function with getCat function that is payable and accepts incoming ETH. // Feature added to set ETH pricing by each cat release and also for specific cats // 1.0 - Feature added to create new cat releases, add attributes and offer to sell/buy cats // 0.0 - Initial contract to support ownership of 12 unique 8-bit cats on the Ethereum blockchain // // Original contract code based off Cryptopunks DAPP by the talented people from Larvalabs // (https://github.com/larvalabs/cryptopunks) // // (c) Nas Munawar / Gendry Morales / Jochy Reyes / TheTwentySix. 2017. The MIT Licence. // ---------------------------------------------------------------------------------------------- contract CryptoCatsMarket { /* modifier to add to function that should only be callable by contract owner */ modifier onlyBy(address _account) { require(msg.sender == _account); _; } /* You can use this hash to verify the image file containing all cats */ string public imageHash = "3b82cfd5fb39faff3c2c9241ca5a24439f11bdeaa7d6c0771eb782ea7c963917"; /* Variables to store contract owner and contract token standard details */ address owner; string public standard = 'CryptoCats'; string public name; string public symbol; uint8 public decimals; uint256 public _totalSupply; // Store reference to previous cryptocat contract containing alpha release owners // PROD - previous contract address // address public previousContractAddress = 0x9508008227b6b3391959334604677d60169EF540; // ROPSTEN - previous contract address address public previousContractAddress = 0xccEC9B9cB223854C46843A1990c36C4A37D80E2e; uint8 public contractVersion; bool public totalSupplyIsLocked; bool public allCatsAssigned = false; // boolean flag to indicate if all available cats are claimed uint public catsRemainingToAssign = 0; // variable to track cats remaining to be assigned/claimed uint public currentReleaseCeiling; // variable to track maximum cat index for latest release /* Create array to store cat index to owner address */ mapping (uint => address) public catIndexToAddress; /* Create array to store cat release id to price in wei for all cats in that release */ mapping (uint32 => uint) public catReleaseToPrice; /* Create array to store cat index to any exception price deviating from release price */ mapping (uint => uint) public catIndexToPriceException; /* Create an array with all balances */ mapping (address => uint) public balanceOf; /* Store type descriptor string for each attribute number */ mapping (uint => string) public attributeType; /* Store up to 6 cat attribute strings where attribute types are defined in attributeType */ mapping (uint => string[6]) public catAttributes; /* Struct that is used to describe seller offer details */ struct Offer { bool isForSale; // flag identifying if cat is for sale uint catIndex; address seller; // owner address uint minPrice; // price in ETH owner is willing to sell cat for address sellOnlyTo; // address identifying only buyer that seller is wanting to offer cat to } uint[] public releaseCatIndexUpperBound; // Store sale Offer details for each cat made for sale by its owner mapping (uint => Offer) public catsForSale; // Store pending withdrawal amounts in ETH that a failed bidder or successful seller is able to withdraw mapping (address => uint) public pendingWithdrawals; /* Define event types to publish transaction details related to transfer and buy/sell activities */ event CatTransfer(address indexed from, address indexed to, uint catIndex); event CatOffered(uint indexed catIndex, uint minPrice, address indexed toAddress); event CatBought(uint indexed catIndex, uint price, address indexed fromAddress, address indexed toAddress); event CatNoLongerForSale(uint indexed catIndex); /* Define event types used to publish to EVM log when cat assignment/claim and cat transfer occurs */ event Assign(address indexed to, uint256 catIndex); event Transfer(address indexed from, address indexed to, uint256 value); /* Define event for reporting new cats release transaction details into EVM log */ event ReleaseUpdate(uint256 indexed newCatsAdded, uint256 totalSupply, uint256 catPrice, string newImageHash); /* Define event for logging update to cat price for existing release of cats (only impacts unclaimed cats) */ event UpdateReleasePrice(uint32 releaseId, uint256 catPrice); /* Define event for logging transactions that change any cat attributes into EVM log*/ event UpdateAttribute(uint indexed attributeNumber, address indexed ownerAddress, bytes32 oldValue, bytes32 newValue); /* Initializes contract with initial supply tokens to the creator of the contract */ function CryptoCatsMarket() payable { owner = msg.sender; // Set contract creation sender as owner _totalSupply = 625; // Set total supply catsRemainingToAssign = _totalSupply; // Initialise cats remaining to total supply amount name = "CRYPTOCATS"; // Set the name for display purposes symbol = "CCAT"; // Set the symbol for display purposes decimals = 0; // Amount of decimals for display purposes contractVersion = 3; currentReleaseCeiling = 625; totalSupplyIsLocked = false; releaseCatIndexUpperBound.push(12); // Register release 0 getting to 12 cats releaseCatIndexUpperBound.push(189); // Register release 1 getting to 189 cats releaseCatIndexUpperBound.push(_totalSupply); // Register release 2 getting to 625 cats catReleaseToPrice[0] = 0; // Set price for release 0 catReleaseToPrice[1] = 0; // Set price for release 1 catReleaseToPrice[2] = 80000000000000000; // Set price for release 2 to Wei equivalent of 0.08 ETH } /* Admin function to make total supply permanently locked (callable by owner only) */ function lockTotalSupply() onlyBy(owner) { totalSupplyIsLocked = true; } /* Admin function to set attribute type descriptor text (callable by owner only) */ function setAttributeType(uint attributeIndex, string descriptionText) onlyBy(owner) { require(attributeIndex >= 0 && attributeIndex < 6); attributeType[attributeIndex] = descriptionText; } /* Admin function to release new cat index numbers and update image hash for new cat releases */ function releaseCats(uint32 _releaseId, uint numberOfCatsAdded, uint256 catPrice, string newImageHash) onlyBy(owner) returns (uint256 newTotalSupply) { require(!totalSupplyIsLocked); // Check that new cat releases still available require(numberOfCatsAdded > 0); // Require release to have more than 0 cats currentReleaseCeiling = currentReleaseCeiling + numberOfCatsAdded; // Add new cats to release ceiling uint _previousSupply = _totalSupply; _totalSupply = _totalSupply + numberOfCatsAdded; catsRemainingToAssign = catsRemainingToAssign + numberOfCatsAdded; // Update cats remaining to assign count imageHash = newImageHash; // Update image hash catReleaseToPrice[_releaseId] = catPrice; // Update price for new release of cats releaseCatIndexUpperBound.push(_totalSupply); // Track upper bound of cat index for this release ReleaseUpdate(numberOfCatsAdded, _totalSupply, catPrice, newImageHash); // Send EVM event containing details of release return _totalSupply; // Return new total supply of cats } /* Admin function to update price for an entire release of cats still available for claiming */ function updateCatReleasePrice(uint32 _releaseId, uint256 catPrice) onlyBy(owner) { require(_releaseId <= releaseCatIndexUpperBound.length); // Check that release is id valid catReleaseToPrice[_releaseId] = catPrice; // Update price for cat release UpdateReleasePrice(_releaseId, catPrice); // Send EVM event with release id and price details } /* Migrate details of previous contract cat owners addresses and cat balances to new contract instance */ function migrateCatOwnersFromPreviousContract(uint startIndex, uint endIndex) onlyBy(owner) { PreviousCryptoCatsContract previousCatContract = PreviousCryptoCatsContract(previousContractAddress); for (uint256 catIndex = startIndex; catIndex <= endIndex; catIndex++) { // Loop through cat index based on start/end index address catOwner = previousCatContract.catIndexToAddress(catIndex); // Retrieve owner address from previous contract if (catOwner != 0x0) { // Check that cat index has an owner address and is not unclaimed catIndexToAddress[catIndex] = catOwner; // Update owner address in current contract uint256 ownerBalance = previousCatContract.balanceOf(catOwner); balanceOf[catOwner] = ownerBalance; // Update owner cat balance } } catsRemainingToAssign = previousCatContract.catsRemainingToAssign(); // Update count of total cats remaining to assign from prev contract } /* Add value for cat attribute that has been defined (only for cat owner) */ function setCatAttributeValue(uint catIndex, uint attrIndex, string attrValue) { require(catIndex < _totalSupply); // cat index requested should not exceed total supply require(catIndexToAddress[catIndex] == msg.sender); // require sender to be cat owner require(attrIndex >= 0 && attrIndex < 6); // require that attribute index is 0 - 5 bytes memory tempAttributeTypeText = bytes(attributeType[attrIndex]); require(tempAttributeTypeText.length != 0); // require that attribute being stored is not empty catAttributes[catIndex][attrIndex] = attrValue; // store attribute value string in contract based on cat index } /* Transfer cat by owner to another wallet address Different usage in Cryptocats than in normal token transfers This will transfer an owner's cat to another wallet's address Cat is identified by cat index passed in as _value */ function transfer(address _to, uint256 _value) returns (bool success) { if (_value < _totalSupply && // ensure cat index is valid catIndexToAddress[_value] == msg.sender && // ensure sender is owner of cat balanceOf[msg.sender] > 0) { // ensure sender balance of cat exists balanceOf[msg.sender]--; // update (reduce) cat balance from owner catIndexToAddress[_value] = _to; // set new owner of cat in cat index balanceOf[_to]++; // update (include) cat balance for recepient Transfer(msg.sender, _to, _value); // trigger event with transfer details to EVM success = true; // set success as true after transfer completed } else { success = false; // set success as false if conditions not met } return success; // return success status } /* Returns count of how many cats are owned by an owner */ function balanceOf(address _owner) constant returns (uint256 balance) { require(balanceOf[_owner] != 0); // requires that cat owner balance is not 0 return balanceOf[_owner]; // return number of cats owned from array of balances by owner address } /* Return total supply of cats existing */ function totalSupply() constant returns (uint256 totalSupply) { return _totalSupply; } /* Claim cat at specified index if it is unassigned - Deprecated as replaced with getCat function in v2.0 */ // function claimCat(uint catIndex) { // require(!allCatsAssigned); // require all cats have not been assigned/claimed // require(catsRemainingToAssign != 0); // require cats remaining to be assigned count is not 0 // require(catIndexToAddress[catIndex] == 0x0); // require owner address for requested cat index is empty // require(catIndex < _totalSupply); // require cat index requested does not exceed total supply // require(catIndex < currentReleaseCeiling); // require cat index to not be above current ceiling of released cats // catIndexToAddress[catIndex] = msg.sender; // Assign sender's address as owner of cat // balanceOf[msg.sender]++; // Increase sender's balance holder // catsRemainingToAssign--; // Decrease cats remaining count // Assign(msg.sender, catIndex); // Triggers address assignment event to EVM's // // log to allow javascript callbacks // } /* Return the release index for a cat based on the cat index */ function getCatRelease(uint catIndex) returns (uint32) { for (uint32 i = 0; i < releaseCatIndexUpperBound.length; i++) { // loop through release index record array if (releaseCatIndexUpperBound[i] > catIndex) { // check if highest cat index for release is higher than submitted cat index return i; // return release id } } } /* Gets cat price for a particular cat index */ function getCatPrice(uint catIndex) returns (uint catPrice) { require(catIndex < _totalSupply); // Require that cat index is valid if(catIndexToPriceException[catIndex] != 0) { // Check if there is any exception pricing return catIndexToPriceException[catIndex]; // Return price if there is overriding exception pricing } uint32 releaseId = getCatRelease(catIndex); return catReleaseToPrice[releaseId]; // Return cat price based on release pricing if no exception pricing } /* Sets exception price in Wei that differs from release price for single cat based on cat index */ function setCatPrice(uint catIndex, uint catPrice) onlyBy(owner) { require(catIndex < _totalSupply); // Require that cat index is valid require(catPrice > 0); // Check that cat price is not 0 catIndexToPriceException[catIndex] = catPrice; // Create cat price record in exception pricing array for this cat index } /* Get cat with no owner at specified index by paying price */ function getCat(uint catIndex) payable { require(!allCatsAssigned); // require all cats have not been assigned/claimed require(catsRemainingToAssign != 0); // require cats remaining to be assigned count is not 0 require(catIndexToAddress[catIndex] == 0x0); // require owner address for requested cat index is empty require(catIndex < _totalSupply); // require cat index requested does not exceed total supply require(catIndex < currentReleaseCeiling); // require cat index to not be above current ceiling of released cats require(getCatPrice(catIndex) <= msg.value); // require ETH amount sent with tx is sufficient for cat price catIndexToAddress[catIndex] = msg.sender; // Assign sender's address as owner of cat balanceOf[msg.sender]++; // Increase sender's balance holder catsRemainingToAssign--; // Decrease cats remaining count pendingWithdrawals[owner] += msg.value; // Add paid amount to pending withdrawals for contract owner (bugfix in v3.0) Assign(msg.sender, catIndex); // Triggers address assignment event to EVM's // log to allow javascript callbacks } /* Get address of owner based on cat index */ function getCatOwner(uint256 catIndex) public returns (address) { require(catIndexToAddress[catIndex] != 0x0); return catIndexToAddress[catIndex]; // Return address at array position of cat index } /* Get address of contract owner who performed contract creation and initialisation */ function getContractOwner() public returns (address) { return owner; // Return address of contract owner } /* Indicate that cat is no longer for sale (by cat owner only) */ function catNoLongerForSale(uint catIndex) { require (catIndexToAddress[catIndex] == msg.sender); // Require that sender is cat owner require (catIndex < _totalSupply); // Require that cat index is valid catsForSale[catIndex] = Offer(false, catIndex, msg.sender, 0, 0x0); // Switch cat for sale flag to false and reset all other values CatNoLongerForSale(catIndex); // Create EVM event logging that cat is no longer for sale } /* Create sell offer for cat with a certain minimum sale price in wei (by cat owner only) */ function offerCatForSale(uint catIndex, uint minSalePriceInWei) { require (catIndexToAddress[catIndex] == msg.sender); // Require that sender is cat owner require (catIndex < _totalSupply); // Require that cat index is valid catsForSale[catIndex] = Offer(true, catIndex, msg.sender, minSalePriceInWei, 0x0); // Set cat for sale flag to true and update with price details CatOffered(catIndex, minSalePriceInWei, 0x0); // Create EVM event to log details of cat sale } /* Create sell offer for cat only to a particular buyer address with certain minimum sale price in wei (by cat owner only) */ function offerCatForSaleToAddress(uint catIndex, uint minSalePriceInWei, address toAddress) { require (catIndexToAddress[catIndex] == msg.sender); // Require that sender is cat owner require (catIndex < _totalSupply); // Require that cat index is valid catsForSale[catIndex] = Offer(true, catIndex, msg.sender, minSalePriceInWei, toAddress); // Set cat for sale flag to true and update with price details and only sell to address CatOffered(catIndex, minSalePriceInWei, toAddress); // Create EVM event to log details of cat sale } /* Buy cat that is currently on offer */ function buyCat(uint catIndex) payable { require (catIndex < _totalSupply); // require that cat index is valid and less than total cat index Offer offer = catsForSale[catIndex]; require (offer.isForSale); // require that cat is marked for sale // require buyer to have required address if indicated in offer require (msg.value >= offer.minPrice); // require buyer sent enough ETH require (offer.seller == catIndexToAddress[catIndex]); // require seller must still be owner of cat if (offer.sellOnlyTo != 0x0) { // if cat offer sell only to address is not blank require (offer.sellOnlyTo == msg.sender); // require that buyer is allowed to buy offer } address seller = offer.seller; catIndexToAddress[catIndex] = msg.sender; // update cat owner address to buyer's address balanceOf[seller]--; // reduce cat balance of seller balanceOf[msg.sender]++; // increase cat balance of buyer Transfer(seller, msg.sender, 1); // create EVM event logging transfer of 1 cat from seller to owner CatNoLongerForSale(catIndex); // create EVM event logging cat is no longer for sale pendingWithdrawals[seller] += msg.value; // increase pending withdrawal amount of seller based on amount sent in buyer's message CatBought(catIndex, msg.value, seller, msg.sender); // create EVM event logging details of cat purchase } /* Withdraw any pending ETH amount that is owed to failed bidder or successful seller */ function withdraw() { uint amount = pendingWithdrawals[msg.sender]; // store amount that can be withdrawn by sender pendingWithdrawals[msg.sender] = 0; // zero pending withdrawal amount msg.sender.transfer(amount); // before performing transfer to message sender } } contract PreviousCryptoCatsContract { /* You can use this hash to verify the image file containing all cats */ string public imageHash = "e055fe5eb1d95ea4e42b24d1038db13c24667c494ce721375bdd827d34c59059"; /* Variables to store contract owner and contract token standard details */ address owner; string public standard = 'CryptoCats'; string public name; string public symbol; uint8 public decimals; uint256 public _totalSupply; // Store reference to previous cryptocat contract containing alpha release owners // PROD address public previousContractAddress = 0xa185B9E63FB83A5a1A13A4460B8E8605672b6020; // ROPSTEN // address public previousContractAddress = 0x0b0DB7bd68F944C219566E54e84483b6c512737B; uint8 public contractVersion; bool public totalSupplyIsLocked; bool public allCatsAssigned = false; // boolean flag to indicate if all available cats are claimed uint public catsRemainingToAssign = 0; // variable to track cats remaining to be assigned/claimed uint public currentReleaseCeiling; // variable to track maximum cat index for latest release /* Create array to store cat index to owner address */ mapping (uint => address) public catIndexToAddress; /* Create an array with all balances */ mapping (address => uint) public balanceOf; /* Initializes contract with initial supply tokens to the creator of the contract */ function PreviousCryptoCatsContract() payable { owner = msg.sender; // Set contract creation sender as owner } /* Returns count of how many cats are owned by an owner */ function balanceOf(address _owner) constant returns (uint256 balance) { require(balanceOf[_owner] != 0); // requires that cat owner balance is not 0 return balanceOf[_owner]; // return number of cats owned from array of balances by owner address } /* Return total supply of cats existing */ function totalSupply() constant returns (uint256 totalSupply) { return _totalSupply; } /* Get address of owner based on cat index */ function getCatOwner(uint256 catIndex) public returns (address) { require(catIndexToAddress[catIndex] != 0x0); return catIndexToAddress[catIndex]; // Return address at array position of cat index } /* Get address of contract owner who performed contract creation and initialisation */ function getContractOwner() public returns (address) { return owner; // Return address of contract owner } }
require cat index to not be above current ceiling of released cats
require(catIndex < currentReleaseCeiling);
8,073,866
[ 1, 6528, 6573, 770, 358, 486, 506, 5721, 783, 5898, 4973, 434, 15976, 27525, 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, 3639, 2583, 12, 2574, 1016, 411, 783, 7391, 39, 73, 4973, 1769, 4202, 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 ]
./partial_match/1/0x69E4bf938FB99D765dAEc594Ed2b16A00D16EaaA/sources/TypicalTigersMigration.sol
* @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./ Check that tokenId was not transferred by `_beforeTokenTransfer` hook Clear approvals from the previous owner Decrease balance with checked arithmetic, because an `ownerOf` override may invalidate the assumption that `_balances[from] >= 1`. `_balances[to]` could overflow in the conditions described in `_mint`. That would require all 2**256 token ids to be minted, which in practice is impossible.
function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId, 1); require(ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); delete _tokenApprovals[tokenId]; _balances[from] -= 1; unchecked { _balances[to] += 1; } _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId, 1); }
3,658,601
[ 1, 1429, 18881, 1375, 2316, 548, 68, 628, 1375, 2080, 68, 358, 1375, 869, 8338, 225, 2970, 1061, 7423, 358, 288, 13866, 1265, 5779, 333, 709, 10522, 1158, 17499, 603, 1234, 18, 15330, 18, 29076, 30, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 2316, 548, 68, 1147, 1297, 506, 16199, 635, 1375, 2080, 8338, 7377, 1282, 279, 288, 5912, 97, 871, 18, 19, 2073, 716, 1147, 548, 1703, 486, 906, 4193, 635, 1375, 67, 5771, 1345, 5912, 68, 3953, 10121, 6617, 4524, 628, 326, 2416, 3410, 31073, 448, 11013, 598, 5950, 30828, 16, 2724, 392, 1375, 8443, 951, 68, 3849, 2026, 11587, 326, 24743, 716, 1375, 67, 70, 26488, 63, 2080, 65, 1545, 404, 8338, 1375, 67, 70, 26488, 63, 869, 65, 68, 3377, 9391, 316, 326, 4636, 11893, 316, 1375, 67, 81, 474, 8338, 12466, 4102, 2583, 777, 576, 5034, 1147, 3258, 358, 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, 389, 13866, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 1147, 548, 13, 2713, 5024, 288, 203, 3639, 2583, 12, 8443, 951, 12, 2316, 548, 13, 422, 628, 16, 315, 654, 39, 27, 5340, 30, 7412, 628, 11332, 3410, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 27, 5340, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 203, 3639, 389, 5771, 1345, 5912, 12, 2080, 16, 358, 16, 1147, 548, 16, 404, 1769, 203, 203, 3639, 2583, 12, 8443, 951, 12, 2316, 548, 13, 422, 628, 16, 315, 654, 39, 27, 5340, 30, 7412, 628, 11332, 3410, 8863, 203, 203, 3639, 1430, 389, 2316, 12053, 4524, 63, 2316, 548, 15533, 203, 203, 3639, 389, 70, 26488, 63, 2080, 65, 3947, 404, 31, 203, 203, 3639, 22893, 288, 203, 5411, 389, 70, 26488, 63, 869, 65, 1011, 404, 31, 203, 3639, 289, 203, 203, 3639, 389, 995, 414, 63, 2316, 548, 65, 273, 358, 31, 203, 203, 3639, 3626, 12279, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 203, 3639, 389, 5205, 1345, 5912, 12, 2080, 16, 358, 16, 1147, 548, 16, 404, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.9 <0.9.0; /* _______ _ _ __ __ |__ __| (_) | \ \ / / | |_ __ _| |__ ___ \ V / | | '__| | '_ \ / _ \ > < | | | | | |_) | __// . \ __|_|_|_ |_|_.__/ \___/_/_\_\ | \/ (_) | | | __ \ | \ / |_ _ __ | |_ | |__) |_ _ ___ ___ | |\/| | | '_ \| __| | ___/ _` / __/ __| | | | | | | | | |_ | | | (_| \__ \__ \ |_| |_|_|_| |_|\__| |_| \__,_|___/___/ */ import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract TribeXMintPass is ERC721, Ownable, ReentrancyGuard { address public CROSSMINT_ADDRESS = 0xdAb1a1854214684acE522439684a145E62505233; address public TRIBEX_COLD_ADDRESS = 0xaBffc43Bafd9c811a351e7051feD9d8be2ad082f; string public wholeURI; uint256 public costPublicSale = 0.15 ether; uint256 public costCrossmint = 0.15 ether; uint16 public totalSupply = 0; uint16 public maxSupply = 5000; uint16 public maxMintAmount = 12; bool public paused = false; constructor( string memory _name, string memory _symbol, string memory _initWholeURI ) ERC721(_name, _symbol) { setWholeURI(_initWholeURI); } //MINTING for PublicSale function mintPublicSale(uint8 _mintAmount) external payable { require(_mintAmount <= maxMintAmount, "Max allowed mint amount exceeded for PublicSale"); require(msg.value >= costPublicSale * _mintAmount, "Insufficient ETH amount"); _mintInternal(msg.sender, _mintAmount); } //MINTING for Crossmint function mintCrossmint(address _mintToAddress, uint8 _mintAmount) external payable { require(msg.sender == CROSSMINT_ADDRESS, "This function is for Crossmint only."); require(msg.value >= costCrossmint * _mintAmount, "Insufficient ETH amount"); _mintInternal(_mintToAddress, _mintAmount); } //MINTING for onlyOwner function mintOnlyOwner(address _mintToAddress, uint8 _mintAmount) external payable onlyOwner { _mintInternal(_mintToAddress, _mintAmount); } //INTERNAL mint function _mintInternal(address _mintToAddress, uint8 _mintAmount) internal { require(!paused, "Please wait until unpaused"); require(_mintAmount > 0, "Need to mint more than 0"); require(totalSupply + _mintAmount <= maxSupply, "Not enough NFTs left to mint that many!"); for (uint8 i = 1; i <= _mintAmount; i++) { incrementTotalSupply(); _safeMint(_mintToAddress, totalSupply); } } function incrementTotalSupply() internal { totalSupply += 1; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "tokenId does not exist"); return wholeURI; } //--------ONLY OWNER--------// //SETTERS FOR ADDRESSES function setCrossmintAddress(address _newCrossmintAddress) public onlyOwner { CROSSMINT_ADDRESS = _newCrossmintAddress; } function setTribexColdAddress(address newTribexColdAddress) public onlyOwner { TRIBEX_COLD_ADDRESS = newTribexColdAddress; } //SETTERS FOR STRINGS function setWholeURI(string memory _newWholeURI) public onlyOwner { wholeURI = _newWholeURI; } //SETTERS FOR COSTS function setCostPublicSale(uint256 _newCostPublicSale) public onlyOwner { costPublicSale = _newCostPublicSale; } function setCostCrossMint(uint256 _costCrossmint) public onlyOwner { costCrossmint = _costCrossmint; } //SETTERS FOR MAXSUPPLY function setMaxSupply(uint16 _newMaxSupply) public onlyOwner { maxSupply = _newMaxSupply; } //SETTERS FOR MAXMINTAMOUNT function setMaxMintAmount(uint16 _newMaxMintAmount) public onlyOwner { maxMintAmount = _newMaxMintAmount; } //SETTERS FOR PAUSED function pause() public onlyOwner { paused = true; } function unpause() public onlyOwner { paused = false; } //WITHDRAWALS function withdraw() public payable onlyOwner nonReentrant { // ================This will pay 100%========================= (bool coldsuccess, ) = payable(TRIBEX_COLD_ADDRESS).call{value: address(this).balance}(""); require(coldsuccess); // ==================================================================== // This will payout the OWNER the remainder of the contract balance if any left. (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); // ===================================================================== } } // SPDX-License-Identifier: MIT // 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; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^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() { _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); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // 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; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @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 _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @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 baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @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 || 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 { _setApprovalForAll(_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 _owners[tokenId] != address(0); } /** * @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 || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `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); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(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); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(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 from incorrect 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); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @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()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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` 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 tokenId ) 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. * - `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 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) 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 // 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; } } // SPDX-License-Identifier: MIT // 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); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^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 // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^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 // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/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 // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^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); }
MINTING for onlyOwner
function mintOnlyOwner(address _mintToAddress, uint8 _mintAmount) external payable onlyOwner { _mintInternal(_mintToAddress, _mintAmount); }
13,618,115
[ 1, 49, 3217, 1360, 364, 1338, 5541, 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, 312, 474, 3386, 5541, 12, 2867, 389, 81, 474, 774, 1887, 16, 2254, 28, 389, 81, 474, 6275, 13, 3903, 8843, 429, 1338, 5541, 288, 203, 202, 202, 67, 81, 474, 3061, 24899, 81, 474, 774, 1887, 16, 389, 81, 474, 6275, 1769, 203, 202, 97, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-03-30 */ // SPDX-License-Identifier: MIT // File: contracts/IKWWData.sol pragma solidity ^0.8.4; interface IKWWData { struct KangarooDetails{ //Timestamp of the date the kangaroo is born uint64 birthTime; //Dad token id uint32 dadId; //Mom token id uint32 momId; //Couple token id uint32 coupleId; //If the kangaroo is on boat, the boatId will be set here uint16 boatId; //If the kangaroo moved to another land, the new landId will be set here uint16 landId; //The generation of the kangaroo (genesis - gen0) NOT CHANGING uint8 gen; //Status of the kangaroo in the game // 0 - Australian // 1 - Sailing // 2 - Kangaroo Island // 3 - Pregnant uint8 status; //Type of the kangaroo (Pirate, Native, etc.) uint8 bornState; } struct CoupleDetails{ //Timestamp when the pregnancy started uint64 pregnancyStarted; uint8 babiesCounter; //false - wild world, true - hospital bool paidHospital; bool activePregnant; } function initKangaroo(uint32 tokenId, uint32 dadId, uint32 momId) external; } // File: contracts/IKWWGameManager.sol pragma solidity ^0.8.4; interface IKWWGameManager{ enum ContractTypes {KANGAROOS, BOATS, LANDS, VAULT, DATA, BOATS_DATA, MOVING_BOATS, VOTING} function getContract(uint8 _type) external view returns(address); } interface IKWWMovingBoats { struct MovingBoatDetails{ uint256 id; //When the sail started uint64 startSailTime; //Kangaroos on the boat uint32[] kangaroos; //Types of the boat (Pirate, Native, etc.) uint8 boatState; //What is the route of the boat? uint8 route; } } interface Vault{ function depositToVault(address owner, uint256[] memory tokens, uint8 assetsType, bool frozen) external; function withdrawFromVault(address owner, uint256[] calldata tokenIds) external ; function setAssetFrozen(uint256 token, bool isFrozen) external ; function getHolder(uint256 tokenId) external view returns (address); function depositBoatFees(uint16 totalSupply) external payable; function boatAvailableToWithdraw(uint16 totalSupply, uint16 boatId) external view returns(uint256); function withdrawBoatFees(uint16 totalSupply, uint16 boatId, address addr) external; function depositLandFees(uint16 landId) external payable; } interface KangarooData{ function setCouple(uint32 male, uint32 female) external ; function kangarooTookBoat(uint32 tokenId, uint16 boatId) external ; function kangarooReachedIsland(uint32 tokenId) external ; function kangarooStartPregnancy(uint32 dadId, uint32 momId, bool hospital) external ; function birthKangaroos(uint32 dadId, uint32 momId) external ; function getKangaroo(uint32 tokenId) external view returns(IKWWData.KangarooDetails memory); function isCouples(uint32 male, uint32 female) external view returns(bool); function getCouple(uint32 tokenId) external view returns(uint32); function kangarooIsMale(uint32 tokenId) external pure returns(bool); function getKangarooGen(uint32 tokenId) external view returns(uint8); function baseMaxBabiesAllowed(uint32 token) external view returns(uint8); function getStatus(uint32 tokenId) external view returns(uint8); function isBaby(uint32 tokenId) external view returns(bool); function getBornState(uint32 tokenId) external view returns(uint8); function couplesData(uint64 coupleId) external view returns(IKWWData.CoupleDetails memory); } interface BoatsData{ } interface MovingBoatsData{ function startSail(uint8 boatState, uint8 route, uint32[] calldata kangaroos) external; function getLastId() external view returns(uint256); function getKangaroos(uint16 tokenId) external view returns(uint32[] memory); function getRoute(uint16 tokenId) external view returns(uint8); function sailEnd(uint16 tokenId) external view returns(uint64); } interface Voting{ function getBoatPrice(uint16 token) external view returns(uint256); } interface INFT{ function totalSupply() external view returns (uint256); function ownerOf(uint256 tokenId) external view returns (address); } // interface KangaroosNFT{ // function totalSupply() external view returns (uint256); // function ownerOf(uint256 tokenId) external view returns (address); // } // interface BoatsNFT{ // function totalSupply() external view returns (uint256); // function ownerOf(uint256 tokenId) external view returns (address); // } // interface LandsNFT{ // function totalSupply() external view returns (uint256); // function ownerOf(uint256 tokenId) external view returns (address); // } // 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: contracts/KWWGameManager.sol pragma solidity ^0.8.4; contract KWWGameManager is IKWWGameManager, Ownable{ event CoupleStartedSailing(uint32 indexed _male, uint32 indexed _female, uint16 _boatId); event ArrivedIsland(uint32 indexed _male, uint32 indexed _female); event PregnancyStarted(uint32 indexed _male, uint32 indexed _female, bool isHospital); event BabiesBorn(uint32 indexed _male, uint32 indexed _female); event ArrivedContinent(uint32 indexed _male, uint32 indexed _female); event SailBackStarted(uint32 indexed _male, uint32 indexed _female, uint16 _boatId); mapping(uint8 => address) contracts; uint256 priceHospital = 0.07 ether; /* GAME */ //Step 1 - Couple pick boat and start sail function coupleStartJourney(uint32 male, uint32 female) public payable { //Check ownership require(isOwnerOrStaked(male, ContractTypes.KANGAROOS) && isOwnerOrStaked(female, ContractTypes.KANGAROOS), "Missing permissions - you're not the owner of one of the tokens"); //Check if not babies require(!getData().isBaby(male) && !getData().isBaby(female), "One of the kangaroos is baby"); //Check if from same state require(getData().getBornState(male) == getData().getBornState(female),"Couple not from the same born state"); //Check if from same gen require(getData().getKangarooGen(male) == getData().getKangarooGen(female),"Couple not from the same generation"); //Check if genders match - male is really male require(getData().kangarooIsMale(male) == true && getData().kangarooIsMale(female) == false,"Couple genders mismatched"); //Check status == 0 require(getData().getStatus(male) == 0 && getData().getStatus(female) == 0, "Status doesn't fit this step"); //Is single before starting the journey require(getData().getCouple(male) == 0 && getData().getCouple(female) == 0, "Can't change couple"); //Pay to boat owners require(getVoting().getBoatPrice(1) <= msg.value, "Renting fee is too low"); getVault().depositBoatFees{value:msg.value}(uint16(getBoatNFT().totalSupply()) - 1); //Change status of boat - active + update num kangaroos uint32[] memory kangaroosArr = new uint32[](2); kangaroosArr[0] = male; kangaroosArr[1] = female; getMovingBoats().startSail(getData().getBornState(male), 1, kangaroosArr); uint16 movingBoatId = uint16(getMovingBoats().getLastId()); //deposit kangaroos vault - with freezing depositCouple(male, female, true); //SAVE THEM AS A COUPLE - Create couples journey mapping(uint64=>coupleData) getData().setCouple(male, female); //Change status of kangaroos getData().kangarooTookBoat(male, movingBoatId); getData().kangarooTookBoat(female, movingBoatId); //Trigger event "CoupleStartedSailing(uint32 male, uint32 female, uint8 boatId)" emit CoupleStartedSailing(male, female, movingBoatId); } function arrivedToIsland(uint32 male, uint32 female) public{ //Check ownership require(isOwnerOrStaked(male, ContractTypes.KANGAROOS) && isOwnerOrStaked(female, ContractTypes.KANGAROOS), "Missing permissions - you're not the owner of one of the tokens"); //Is Couples require(getData().isCouples(male, female), "Not Couples"); //Check that the time really passed, and they arrived uint16 boatId = getData().getKangaroo(male).boatId; require(getMovingBoats().sailEnd(boatId) < block.timestamp, "Still on sail"); //Check boat route is to island require(getMovingBoats().getRoute(boatId) == 1, "not in the route to kangaroo island"); //Check status == 1 require(getData().getStatus(male) == 1 && getData().getStatus(female) == 1, "Status doesn't fit this step"); //Change status of kangaroos getData().kangarooReachedIsland(male); getData().kangarooReachedIsland(female); //Trigger event "ArrivedIsland(uint32 male, uint32 female)" emit ArrivedIsland(male, female); } function pregnancyOnWildWorld(uint32 male, uint32 female) public { //Check ownership require(isOwnerOrStaked(male, ContractTypes.KANGAROOS) && isOwnerOrStaked(female, ContractTypes.KANGAROOS), "Missing permissions - you're not the owner of one of the tokens"); //Check status == 2 require(getData().getStatus(male) == 2 && getData().getStatus(female) == 2, "Status doesn't fit this step"); //Is Couples require(getData().isCouples(male, female), "Not Couples"); //Change status of kangaroos getData().kangarooStartPregnancy(male, female, false); //Trigger event "PregnancyStarted(uint32 male, uint32 female, Wild World)" emit PregnancyStarted(male, female, false); } function pregnancyOnHospital(uint32 male, uint32 female) public payable{ //Check ownership require(isOwnerOrStaked(male, ContractTypes.KANGAROOS) && isOwnerOrStaked(female, ContractTypes.KANGAROOS), "Missing permissions - you're not the owner of one of the tokens"); //Check status == 2 require(getData().getStatus(male) == 2 && getData().getStatus(female) == 2, "Status doesn't fit this step"); //Is Couples require(getData().isCouples(male, female), "Not Couples"); //Check full payment require(priceHospital <= msg.value, "Hospital fee too low"); //Change status of kangaroos getData().kangarooStartPregnancy(male, female, true); //Split Payment getVault().depositLandFees{value:msg.value}(1); //Trigger event "PregnancyStarted(uint32 male, uint32 female, Hospital)" emit PregnancyStarted(male, female, true); } function birthBabies(uint32 male, uint32 female) public { //Check ownership require(isOwnerOrStaked(male, ContractTypes.KANGAROOS) && isOwnerOrStaked(female, ContractTypes.KANGAROOS), "Missing permissions - you're not the owner of one of the tokens"); //Check status == 3 require(getData().getStatus(male) == 3 && getData().getStatus(female) == 3, "Status doesn't fit this step"); //Is Couples require(getData().isCouples(male, female), "Not Couples"); //Change status of kangaroos getData().birthKangaroos(male, female); //Trigger event "Babies Born(uint32 male, uint32 female)" emit BabiesBorn(male, female); } function coupleSailBack(uint32 male, uint32 female, uint32 baby1, uint32 baby2) public{ //Check ownership require(isOwnerOrStaked(male, ContractTypes.KANGAROOS) && isOwnerOrStaked(female, ContractTypes.KANGAROOS), "Missing permissions - you're not the owner of one of the tokens"); //Is Couples require(getData().isCouples(male, female), "Not Couples"); //Check made maximum babies require(getData().baseMaxBabiesAllowed(male) == getCouplesData(male, female).babiesCounter); //Check status == 2 (on kangaroo island) require(getData().getStatus(male) == 2 && getData().getStatus(female) == 2, "Status doesn't fit this step"); //Change status of boat - active + update num kangaroos uint32[] memory kangaroosArr = new uint32[](4); kangaroosArr[0] = male; kangaroosArr[1] = female; kangaroosArr[2] = baby1; kangaroosArr[3] = baby2; getMovingBoats().startSail(getData().getBornState(male), 2, kangaroosArr); uint16 movingBoatId = uint16(getMovingBoats().getLastId()); //Change status of kangaroos getData().kangarooTookBoat(male, movingBoatId); getData().kangarooTookBoat(female, movingBoatId); //Trigger event "SailBackStarted(uint32 male, uint32 female, uint8 boatId)" emit SailBackStarted(male, female, movingBoatId); } function arrivedToContinent(uint32 male, uint32 female) public { //Convert to a couple //Check ownership require(isOwnerOrStaked(male, ContractTypes.KANGAROOS) && isOwnerOrStaked(female, ContractTypes.KANGAROOS), "Missing permissions - you're not the owner of one of the tokens"); //Check that the time really passed, and they arrived uint16 boatId = getData().getKangaroo(male).boatId; require(getMovingBoats().sailEnd(boatId) < block.timestamp, "Still on sail"); //Check boat route is to island (route == 2) require(getMovingBoats().getRoute(boatId) == 2, "not in the route to Australian"); //Check status == 1 (On Boat) require(getData().getStatus(male) == 1 && getData().getStatus(female) == 1, "Status doesn't fit this step"); //Change status of kangaroos //Unfreeze vault asset + option to withdraw getVault().setAssetFrozen(male, false); getVault().setAssetFrozen(female, false); //Trigger event "ArrivedContinent(uint32 male, uint32 female) emit ArrivedContinent(male, female); } /* HELPERS */ function getCouplesData(uint32 male, uint32 female) public view returns(IKWWData.CoupleDetails memory){ return getData().couplesData(pack(male, female)); } function pack(uint32 a, uint32 b) public pure returns(uint64) { return (uint64(a) << 32) | uint64(b); } function boatAvailableToWithdraw(uint16 boatId) public view { getVault().boatAvailableToWithdraw(uint16(getBoatNFT().totalSupply()), boatId); } function withdrawBoatFees(uint16 boatId) public { require(getBoatNFT().ownerOf(boatId) == msg.sender, "caller is not the owner of the boat"); getVault().withdrawBoatFees(uint16(getBoatNFT().totalSupply()), boatId, getBoatNFT().ownerOf(boatId)); } function depositCouple(uint32 dadId, uint32 momId, bool frozen) internal { uint256[] memory arr = new uint256[](2); arr[0] = uint256(dadId); arr[1] = uint256(momId); getVault().depositToVault(msg.sender, arr, uint8(ContractTypes.KANGAROOS), frozen); } function withdrawCouple(uint32 dadId, uint32 momId) internal { uint256[] memory arr = new uint256[](2); arr[0] = uint256(dadId); arr[1] = uint256(momId); getVault().withdrawFromVault(msg.sender, arr); } /* GETTERS */ function getContract(uint8 _type) override view public returns(address){ require(contracts[_type] != address(0),"Contract not exists"); return contracts[_type]; } function getKangaroosNFT() view public returns(INFT){ return INFT(getContract(uint8(ContractTypes.KANGAROOS))); } function getBoatNFT() view public returns(INFT){ return INFT(getContract(uint8(ContractTypes.BOATS))); } function getLandNFT() view public returns(INFT){ return INFT(getContract(uint8(ContractTypes.LANDS))); } function getVault() view public returns(Vault){ return Vault(getContract(uint8(ContractTypes.VAULT))); } function getData() view public returns(KangarooData){ return KangarooData(getContract(uint8(ContractTypes.DATA))); } function getBoatsData() view public returns(BoatsData){ return BoatsData(getContract(uint8(ContractTypes.BOATS_DATA))); } function getMovingBoats() view public returns(MovingBoatsData){ return MovingBoatsData(getContract(uint8(ContractTypes.MOVING_BOATS))); } function getVoting() view public returns(Voting){ return Voting(getContract(uint8(ContractTypes.VOTING))); } function isOwnerOrStaked(uint256 tokenId, ContractTypes _type) internal view returns(bool){ require(contracts[uint8(_type)] != address(0) && contracts[uint8(ContractTypes.VAULT)] != address(0) , "One of the contract not initialized"); bool isOwner = INFT(contracts[uint8(_type)]).ownerOf(tokenId) == msg.sender; bool isStaked = Vault(contracts[uint8(ContractTypes.VAULT)]).getHolder(tokenId) == msg.sender; return isOwner || isStaked; } /* ONLY OWNER */ function addContractType(uint8 typeId, address _addr) public onlyOwner{ contracts[typeId] = _addr; } function setPriceHospital(uint256 price) public onlyOwner{ priceHospital = price; } }
Check ownershipCheck status == 3Is CouplesChange status of kangaroosTrigger event "Babies Born(uint32 male, uint32 female)"
function birthBabies(uint32 male, uint32 female) public { require(isOwnerOrStaked(male, ContractTypes.KANGAROOS) && isOwnerOrStaked(female, ContractTypes.KANGAROOS), "Missing permissions - you're not the owner of one of the tokens"); require(getData().getStatus(male) == 3 && getData().getStatus(female) == 3, "Status doesn't fit this step"); require(getData().isCouples(male, female), "Not Couples"); getData().birthKangaroos(male, female); emit BabiesBorn(male, female); }
15,034,434
[ 1, 1564, 23178, 1564, 1267, 422, 890, 2520, 385, 1395, 6089, 3043, 1267, 434, 417, 539, 14349, 538, 6518, 871, 315, 38, 378, 606, 605, 14245, 12, 11890, 1578, 312, 5349, 16, 2254, 1578, 284, 351, 5349, 2225, 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, 445, 17057, 38, 378, 606, 12, 11890, 1578, 312, 5349, 16, 2254, 1578, 284, 351, 5349, 13, 1071, 288, 203, 3639, 2583, 12, 291, 5541, 1162, 510, 9477, 12, 81, 5349, 16, 13456, 2016, 18, 47, 3388, 985, 51, 4618, 13, 597, 353, 5541, 1162, 510, 9477, 12, 74, 351, 5349, 16, 13456, 2016, 18, 47, 3388, 985, 51, 4618, 3631, 315, 4841, 4371, 300, 1846, 4565, 486, 326, 3410, 434, 1245, 434, 326, 2430, 8863, 203, 3639, 2583, 12, 588, 751, 7675, 588, 1482, 12, 81, 5349, 13, 422, 890, 597, 4303, 7675, 588, 1482, 12, 74, 351, 5349, 13, 422, 890, 16, 315, 1482, 3302, 1404, 4845, 333, 2235, 8863, 203, 3639, 2583, 12, 588, 751, 7675, 291, 39, 1395, 6089, 12, 81, 5349, 16, 284, 351, 5349, 3631, 315, 1248, 385, 1395, 6089, 8863, 203, 3639, 4303, 7675, 22531, 47, 539, 14349, 538, 12, 81, 5349, 16, 284, 351, 5349, 1769, 203, 3639, 3626, 605, 378, 606, 38, 14245, 12, 81, 5349, 16, 284, 351, 5349, 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 ]
./full_match/1/0x2d68676c40Bf820Eb84e3B7d8d77a1C473b08B61/sources/contracts/crossChainSwaps/CrossChainSwaps.sol
@dev helper function to finalize a trade once it has done processing on secondary chain Updates the trade status based on the incomming wormhole message @param message Incomming trade message from wormhole check if correct chain ids are in place
function _completeTrade(TradeResultMessage memory message) private { if (message.primaryChainId != _state.wormholeChainId) { revert SwapError(SwapErrorCode.INVALID_CHAIN_IDS); } Result.SUCCESS ? Status.SUCCESS : Status.FAILED; emit TradeCompleted( message.tradeOfferHash, message.result == Result.SUCCESS ? Status.SUCCESS : Status.FAILED ); }
17,067,112
[ 1, 4759, 445, 358, 12409, 279, 18542, 3647, 518, 711, 2731, 4929, 603, 1377, 9946, 2687, 1377, 15419, 326, 18542, 1267, 2511, 603, 326, 316, 5702, 310, 341, 535, 27167, 883, 225, 883, 657, 5702, 310, 18542, 883, 628, 341, 535, 27167, 866, 309, 3434, 2687, 3258, 854, 316, 3166, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 6226, 22583, 12, 22583, 1253, 1079, 3778, 883, 13, 3238, 288, 203, 3639, 309, 261, 2150, 18, 8258, 3893, 548, 480, 389, 2019, 18, 91, 535, 27167, 3893, 548, 13, 288, 203, 5411, 15226, 12738, 668, 12, 12521, 12012, 18, 9347, 67, 1792, 6964, 67, 19516, 1769, 203, 3639, 289, 203, 5411, 3438, 18, 12778, 203, 5411, 692, 2685, 18, 12778, 203, 5411, 294, 2685, 18, 11965, 31, 203, 203, 3639, 3626, 2197, 323, 9556, 12, 203, 5411, 883, 18, 20077, 10513, 2310, 16, 203, 5411, 883, 18, 2088, 422, 3438, 18, 12778, 692, 2685, 18, 12778, 294, 2685, 18, 11965, 203, 3639, 11272, 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 ]
// UstxDEXv2.sol // SPDX-License-Identifier: MIT // solhint-disable-next-line pragma solidity ^0.8.0; import "./IUSTX.sol"; import "./IERC20.sol"; import "./Roles.sol"; import "./Initializable.sol"; import "./SafeERC20.sol"; /// @title Up Stable Token eXperiment DEX /// @author USTX Team /// @dev This contract implements the DEX functionality for the USTX token (v2). // solhint-disable-next-line contract UstxDEX is Initializable { using Roles for Roles.Role; //SafeERC20 not needed for USDT(TRC20) and USTX(TRC20) using SafeERC20 for IERC20; /***********************************| | Variables && Events | |__________________________________*/ //Constants uint256 private constant MAX_FEE = 200; //maximum fee in BP (2%) uint256 private constant MAX_LAUNCH_FEE = 1000; //maximum fee during launchpad (10%) //Variables uint256 private _decimals; // 6 uint256 private _feeBuy; //buy fee in basis points uint256 private _feeSell; //sell fee in basis points uint256 private _targetRatioExp; //target reserve ratio for expansion in TH (1000s) to circulating cap uint256 private _targetRatioDamp; //target reserve ratio for damping in TH (1000s) to circulating cap uint256 private _expFactor; //expansion factor in TH uint256 private _dampFactor; //damping factor in TH uint256 private _minExp; //minimum expansion in TH uint256 private _maxDamp; //maximum damping in TH uint256 private _collectedFees; //amount of collected fees uint256 private _launchEnabled; //launchpad mode if >=1 uint256 private _launchTargetSize; //number of tokens reserved for launchpad uint256 private _launchPrice; //Launchpad price uint256 private _launchBought; //number of tokens bought so far in Launchpad uint256 private _launchMaxLot; //max number of usdtSold for a single operation during Launchpad uint256 private _launchFee; //Launchpad fee address private _launchTeamAddr; //Launchpad team address bool private _notEntered; //reentrancyguard state bool private _paused; //pausable state Roles.Role private _administrators; uint256 private _numAdmins; uint256 private _minAdmins; uint256 private _version; //contract version uint256[5] private _rtEnable; //reserve token enable uint256[5] private _rtTradeEnable; //reserve token enable for trading uint256[5] private _rtValue; //reserve token value in TH (0-1000) uint256[5] private _rtShift; //reserve token decimal shift IERC20[5] private _rt; //reserve token address (element 0 is USDT) IUSTX private _token; // address of USTX token // Events event TokenBuy(address indexed buyer, uint256 indexed usdtSold, uint256 indexed tokensBought, uint256 price, uint256 tIndex); event TokenSell(address indexed buyer, uint256 indexed tokensSold, uint256 indexed usdtBought, uint256 price, uint256 tIndex); event Snapshot(address indexed operator, uint256 indexed reserveBalance, uint256 indexed tokenBalance); event Paused(address account); event Unpaused(address account); event AdminAdded(address indexed account); event AdminRemoved(address indexed account); /** * @dev initialize function * */ function initialize() public initializer { _launchTeamAddr = _msgSender(); _decimals = 6; _feeBuy = 0; //0% _feeSell = 100; //1% _targetRatioExp = 240; //24% _targetRatioDamp = 260; //26% _expFactor = 1000; //1 _dampFactor = 1000; //1 _minExp = 100; //0.1 _maxDamp = 100; //0.1 _collectedFees = 0; _launchEnabled = 0; _notEntered = true; _paused = false; _numAdmins=0; _addAdmin(_msgSender()); //default admin _minAdmins = 2; //at least 2 admins in charge _version = 1; uint256 j; //initialize reserve variables for (j=0; j<5; j++) { _rtEnable[j]=0; _rtTradeEnable[j]=0; } } /** * @dev upgrade function for V2 */ //function upgradeToV2() public onlyAdmin { // require(_version<2,"Contract already up to date"); // _version=2; // DO THINGS //} /***********************************| | AdminRole | |__________________________________*/ modifier onlyAdmin() { require(isAdmin(_msgSender()), "AdminRole: caller does not have the Admin role"); _; } function isAdmin(address account) public view returns (bool) { return _administrators.has(account); } function addAdmin(address account) public onlyAdmin { _addAdmin(account); } function renounceAdmin() public { require(_numAdmins>_minAdmins, "There must always be a minimum number of admins in charge"); _removeAdmin(_msgSender()); } function _addAdmin(address account) internal { _administrators.add(account); _numAdmins++; emit AdminAdded(account); } function _removeAdmin(address account) internal { _administrators.remove(account); _numAdmins--; emit AdminRemoved(account); } /***********************************| | Pausable | |__________________________________*/ /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyAdmin whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyAdmin whenPaused { _paused = false; emit Unpaused(_msgSender()); } /***********************************| | ReentrancyGuard | |__________________________________*/ /** * @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 make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } /***********************************| | Context | |__________________________________*/ function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /***********************************| | Exchange Functions | |__________________________________*/ /** * @dev Public function to preview token purchase with exact input in USDT * @param usdtSold amount of USDT to sell * @return number of tokens that can be purchased with input usdtSold */ function buyTokenInputPreview(uint256 usdtSold) public view returns (uint256) { require(usdtSold > 0, "USDT sold must greater than 0"); uint256 tokenBalance = _token.balanceOf(address(this)); uint256 reserveBalance = getReserveBalance(); (uint256 tokensBought,,) = _getBoughtMinted(usdtSold,tokenBalance,reserveBalance); return tokensBought; } /** * @dev Public function to preview token sale with exact input in tokens * @param tokensSold amount of token to sell * @return Amount of USDT that can be bought with input Tokens. */ function sellTokenInputPreview(uint256 tokensSold) public view returns (uint256) { require(tokensSold > 0, "Tokens sold must greater than 0"); uint256 tokenBalance = _token.balanceOf(address(this)); uint256 reserveBalance = getReserveBalance(); (uint256 usdtsBought,,) = _getBoughtBurned(tokensSold,tokenBalance,reserveBalance); return usdtsBought; } /** * @dev Public function to buy tokens during launchpad * @param rSell amount of UDST to sell * @param minTokens minimum amount of tokens to buy * @return number of tokens bought */ function buyTokenLaunchInput(uint256 rSell, uint256 tIndex, uint256 minTokens) public whenNotPaused returns (uint256) { require(_launchEnabled>0,"Function allowed only during launchpad"); require(_launchBought<_launchTargetSize,"Launchpad target reached!"); require(rSell<=_launchMaxLot,"Order too big for Launchpad"); require(tIndex<5, "INVALID_INDEX"); require(_rtEnable[tIndex]>0 && _rtTradeEnable[tIndex]>0,"Token disabled"); return _buyLaunchpadInput(rSell, tIndex, minTokens, _msgSender(), _msgSender()); } /** * @dev Public function to buy tokens during launchpad and transfer them to recipient * @param rSell amount of UDST to sell * @param minTokens minimum amount of tokens to buy * @param recipient recipient of the transaction * @return number of tokens bought */ function buyTokenLaunchTransferInput(uint256 rSell, uint256 tIndex, uint256 minTokens, address recipient) public whenNotPaused returns(uint256) { require(_launchEnabled>0,"Function allowed only during launchpad"); require(recipient != address(this) && recipient != address(0),"Recipient cannot be DEX or address 0"); require(_launchBought<_launchTargetSize,"Launchpad target reached!"); require(rSell<=_launchMaxLot,"Order too big for Launchpad"); require(tIndex<5, "INVALID_INDEX"); require(_rtEnable[tIndex]>0 && _rtTradeEnable[tIndex]>0,"Token disabled"); return _buyLaunchpadInput(rSell, tIndex, minTokens, _msgSender(), recipient); } /** * @dev Public function to buy tokens * @param rSell amount of UDST to sell * @param minTokens minimum amount of tokens to buy * @param tIndex index of the reserve token to swap * @return number of tokens bought */ function buyTokenInput(uint256 rSell, uint256 tIndex, uint256 minTokens) public whenNotPaused returns (uint256) { require(_launchEnabled==0,"Function not allowed during launchpad"); require(tIndex<5, "INVALID_INDEX"); require(_rtEnable[tIndex]>0 && _rtTradeEnable[tIndex]>0,"Token disabled"); return _buyStableInput(rSell, tIndex, minTokens, _msgSender(), _msgSender()); } /** * @dev Public function to buy tokens and transfer them to recipient * @param rSell amount of UDST to sell * @param minTokens minimum amount of tokens to buy * @param tIndex index of the reserve token to swap * @param recipient recipient of the transaction * @return number of tokens bought */ function buyTokenTransferInput(uint256 rSell, uint256 tIndex, uint256 minTokens, address recipient) public whenNotPaused returns(uint256) { require(_launchEnabled==0,"Function not allowed during launchpad"); require(recipient != address(this) && recipient != address(0),"Recipient cannot be DEX or address 0"); require(tIndex<5, "INVALID_INDEX"); require(_rtEnable[tIndex]>0 && _rtTradeEnable[tIndex]>0,"Token disabled"); return _buyStableInput(rSell, tIndex, minTokens, _msgSender(), recipient); } /** * @dev Public function to sell tokens * @param tokensSold number of tokens to sell * @param minUsdts minimum number of UDST to buy * @return number of USDTs bought */ function sellTokenInput(uint256 tokensSold, uint256 tIndex, uint256 minUsdts) public whenNotPaused returns (uint256) { require(_launchEnabled==0,"Function not allowed during launchpad"); require(tIndex<5, "INVALID_INDEX"); require(_rtEnable[tIndex]>0 && _rtTradeEnable[tIndex]>0,"Token disabled"); return _sellStableInput(tokensSold, tIndex, minUsdts, _msgSender(), _msgSender()); } /** * @dev Public function to sell tokens and trasnfer USDT to recipient * @param tokensSold number of tokens to sell * @param minUsdts minimum number of UDST to buy * @param recipient recipient of the transaction * @return number of USDTs bought */ function sellTokenTransferInput(uint256 tokensSold, uint256 tIndex, uint256 minUsdts, address recipient) public whenNotPaused returns (uint256) { require(_launchEnabled==0,"Function not allowed during launchpad"); require(recipient != address(this) && recipient != address(0),"Recipient cannot be DEX or address 0"); require(tIndex<5, "INVALID_INDEX"); require(_rtEnable[tIndex]>0 && _rtTradeEnable[tIndex]>0,"Token disabled"); return _sellStableInput(tokensSold, tIndex, minUsdts, _msgSender(), recipient); } /** * @dev public function to setup the reserve after launchpad (onlyAdmin, whenPaused) * @param startPrice target price * @return new reserve value */ function setupReserve(uint256 startPrice) public onlyAdmin whenPaused returns (uint256) { require(startPrice>0,"Price cannot be 0"); uint256 tokenBalance = _token.balanceOf(address(this)); uint256 reserveBalance = getReserveBalance(); uint256 newReserve = reserveBalance * (10**_decimals) / startPrice; uint256 temp; if (newReserve>tokenBalance) { temp = newReserve - tokenBalance; _token.mint(address(this),temp); } else { temp = tokenBalance - newReserve; _token.burn(temp); } return newReserve; } /** * @dev public function to swap 1:1 between reserve tokens (onlyAdmin) * @param amount, amount to swap (6 decimal places) * @param tIndexIn, index of token to sell * @param tIndexOut, index of token to buy * @return amount swapped */ function swapReserveTokens(uint256 amount, uint256 tIndexIn, uint256 tIndexOut) public onlyAdmin returns (uint256) { require(amount > 0,"Amount should be higher than 0"); require(tIndexIn <5 && tIndexOut <5 && tIndexIn != tIndexOut,"Index out of bounds or equal"); require(_rtEnable[tIndexIn]>0 && _rtEnable[tIndexOut]>0,"Tokens disabled"); _swapReserveTokens(amount, tIndexIn, tIndexOut, _msgSender()); return amount; } /** * @dev private function to swap 1:1 between reserve tokens (nonReentrant) * @param amount, amount to swap (6 decimal places) * @param tIndexIn, index of token to sell * @param tIndexOut, index of token to buy * @param buyer, recipient * @return amount swapped */ function _swapReserveTokens(uint256 amount, uint256 tIndexIn, uint256 tIndexOut, address buyer) private nonReentrant returns (uint256) { if (tIndexIn==0) { _rt[tIndexIn].transferFrom(buyer, address(this), amount*(10**_rtShift[tIndexIn])); } else { _rt[tIndexIn].safeTransferFrom(buyer, address(this), amount*(10**_rtShift[tIndexIn])); } if (tIndexOut==0) { _rt[tIndexOut].transfer(buyer, amount*(10**_rtShift[tIndexOut])); } else { _rt[tIndexOut].safeTransfer(buyer, amount*(10**_rtShift[tIndexOut])); } return amount; } /** * @dev Private function to buy tokens with exact input in USDT * */ function _buyStableInput(uint256 usdtSold, uint256 tIndex, uint256 minTokens, address buyer, address recipient) private nonReentrant returns (uint256) { require(usdtSold > 0 && minTokens > 0,"USDT sold and min tokens should be higher than 0"); uint256 tokenBalance = _token.balanceOf(address(this)); uint256 reserveBalance = getReserveBalance(); (uint256 tokensBought, uint256 minted, uint256 fee) = _getBoughtMinted(usdtSold,tokenBalance,reserveBalance); _collectedFees = _collectedFees + fee; fee = fee*(10**_rtShift[tIndex]); require(tokensBought >= minTokens, "Tokens bought lower than requested minimum amount"); if (minted>0) { _token.mint(address(this),minted); } if (tIndex==0) { _rt[tIndex].transferFrom(buyer, address(this), usdtSold*(10**_rtShift[tIndex])); if (fee>0) { _rt[tIndex].transfer(_launchTeamAddr,fee); //transfer fees to team } } else { _rt[tIndex].safeTransferFrom(buyer, address(this), usdtSold*(10**_rtShift[tIndex])); if (fee>0) { _rt[tIndex].safeTransfer(_launchTeamAddr,fee); //transfer fees to team } } _token.transfer(address(recipient),tokensBought); tokenBalance = _token.balanceOf(address(this)); //update token reserve reserveBalance = getReserveBalance(); //update usdt reserve uint256 newPrice = reserveBalance * (10**_decimals) / tokenBalance; //calc new price emit TokenBuy(buyer, usdtSold, tokensBought, newPrice, tIndex); //emit TokenBuy event emit Snapshot(buyer, reserveBalance, tokenBalance); //emit Snapshot event return tokensBought; } /** * @dev Private function to buy tokens during launchpad with exact input in USDT * */ function _buyLaunchpadInput(uint256 usdtSold, uint256 tIndex, uint256 minTokens, address buyer, address recipient) private nonReentrant returns (uint256) { require(usdtSold > 0 && minTokens > 0, "USDT sold and min tokens should be higher than 0"); uint256 tokensBought = usdtSold * (10**_decimals) / _launchPrice; uint256 fee = usdtSold * _launchFee * (10**_rtShift[tIndex]) / 10000; require(tokensBought >= minTokens, "Tokens bought lower than requested minimum amount"); _launchBought = _launchBought + tokensBought; _token.mint(address(this),tokensBought); //mint new tokens if (tIndex==0) { _rt[0].transferFrom(buyer, address(this), usdtSold * (10**_rtShift[tIndex])); //add usdtSold to reserve _rt[0].transfer(_launchTeamAddr,fee); //transfer fees to team } else { _rt[tIndex].safeTransferFrom(buyer, address(this), usdtSold * (10**_rtShift[tIndex])); //add usdtSold to reserve _rt[tIndex].safeTransfer(_launchTeamAddr,fee); //transfer fees to team } _token.transfer(address(recipient),tokensBought); //transfer tokens to recipient emit TokenBuy(buyer, usdtSold, tokensBought, _launchPrice, tIndex); emit Snapshot(buyer, getReserveBalance(), _token.balanceOf(address(this))); return tokensBought; } /** * @dev Private function to sell tokens with exact input in tokens * */ function _sellStableInput(uint256 tokensSold, uint256 tIndex, uint256 minUsdts, address buyer, address recipient) private nonReentrant returns (uint256) { require(tokensSold > 0 && minUsdts > 0, "Tokens sold and min USDT should be higher than 0"); uint256 tokenBalance = _token.balanceOf(address(this)); uint256 reserveBalance = getReserveBalance(); (uint256 usdtsBought, uint256 burned, uint256 fee) = _getBoughtBurned(tokensSold,tokenBalance,reserveBalance); _collectedFees = _collectedFees + fee; fee = fee * (10**_rtShift[tIndex]); //adjust for correct number of decimals require(usdtsBought >= minUsdts, "USDT bought lower than requested minimum amount"); if (burned>0) { _token.burn(burned); } _token.transferFrom(buyer, address(this), tokensSold); //transfer tokens to DEX if (tIndex==0) { //USDT no safeERC20 _rt[0].transfer(recipient,usdtsBought * (10**_rtShift[tIndex])); //transfer USDT to user if (fee>0) { _rt[0].transfer(_launchTeamAddr,fee); //transfer fees to team } } else { _rt[tIndex].safeTransfer(recipient,usdtsBought * (10**_rtShift[tIndex])); //transfer USDT to user if (fee>0) { _rt[tIndex].safeTransfer(_launchTeamAddr,fee); //transfer fees to team } } tokenBalance = _token.balanceOf(address(this)); //update token reserve reserveBalance = getReserveBalance(); //update usdt reserve uint256 newPrice = reserveBalance * (10**_decimals) / tokenBalance; //calc new price emit TokenSell(buyer, tokensSold, usdtsBought, newPrice, tIndex); //emit Token event emit Snapshot(buyer, reserveBalance, tokenBalance); //emit Snapshot event return usdtsBought; } /** * @dev Private function to get expansion correction * */ function _getExp(uint256 tokenReserve, uint256 usdtReserve) private view returns (uint256,uint256) { uint256 tokenCirc = _token.totalSupply(); //total tokenCirc = tokenCirc - tokenReserve; uint256 price = getPrice(); //multiplied by 10**decimals uint256 cirCap = price * tokenCirc; //multiplied by 10**decimals uint256 ratio = usdtReserve * 1000000000 / cirCap; uint256 exp = ratio * 1000 / _targetRatioExp; if (exp<1000) { exp=1000; } exp = exp - 1000; exp=exp * _expFactor / 1000; if (exp<_minExp) { exp=_minExp; } if (exp>1000) { exp = 1000; } return (exp,ratio); } /** * @dev Private function to get k exponential factor for expansion * */ function _getKXe(uint256 pool, uint256 trade, uint256 exp) private pure returns (uint256) { uint256 temp = 1000-exp; temp = trade * temp; temp = temp / 1000; temp = temp + pool; temp = temp * 1000000000; uint256 kexp = temp / pool; return kexp; } /** * @dev Private function to get k exponential factor for damping * */ function _getKXd(uint256 pool, uint256 trade, uint256 exp) private pure returns (uint256) { uint256 temp = 1000-exp; temp = trade * temp; temp = temp / 1000; temp = temp+ pool; uint256 kexp = pool * 1000000000 / temp; return kexp; } /** * @dev Private function to get amount of tokens bought and minted * */ function _getBoughtMinted(uint256 usdtSold, uint256 tokenReserve, uint256 usdtReserve) private view returns (uint256,uint256,uint256) { uint256 fees = usdtSold * _feeBuy / 10000; uint256 usdtSoldNet = usdtSold - fees; (uint256 exp,) = _getExp(tokenReserve,usdtReserve); uint256 kexp = _getKXe(usdtReserve,usdtSoldNet,exp); uint256 temp = tokenReserve * usdtReserve; //k temp = temp * kexp; temp = temp * kexp; uint256 kn = temp / 1000000000000000000; //uint256 kn=tokenReserve.mul(usdtReserve).mul(kexp).mul(kexp).div(1000000); temp = tokenReserve * usdtReserve; //k usdtReserve = usdtReserve + usdtSoldNet; //uint256 usdtReserveNew= usdtReserve.add(usdtSoldNet); temp = temp / usdtReserve; //USTXamm uint256 tokensBought = tokenReserve -temp; //out=tokenReserve-USTXamm temp=kn / usdtReserve; //USXTPool_n uint256 minted=temp + tokensBought - tokenReserve; return (tokensBought, minted, fees); } /** * @dev Private function to get damping correction * */ function _getDamp(uint256 tokenReserve, uint256 usdtReserve) private view returns (uint256,uint256) { uint256 tokenCirc = _token.totalSupply(); //total tokenCirc = tokenCirc - tokenReserve; uint256 price = getPrice(); //multiplied by 10**decimals uint256 cirCap = price * tokenCirc; //multiplied by 10**decimals uint256 ratio = usdtReserve * 1000000000/ cirCap; //in TH if (ratio>_targetRatioDamp) { ratio=_targetRatioDamp; } uint256 damp = _targetRatioDamp - ratio; damp = damp * _dampFactor / _targetRatioDamp; if (damp<_maxDamp) { damp=_maxDamp; } if (damp>1000) { damp = 1000; } return (damp,ratio); } /** * @dev Private function to get number of USDT bought and tokens burned * */ function _getBoughtBurned(uint256 tokenSold, uint256 tokenReserve, uint256 usdtReserve) private view returns (uint256,uint256,uint256) { (uint256 damp,) = _getDamp(tokenReserve,usdtReserve); uint256 kexp = _getKXd(tokenReserve,tokenSold,damp); uint256 k = tokenReserve * usdtReserve; //k uint256 temp = k * kexp; temp = temp * kexp; uint256 kn = temp / 1000000000000000000; //uint256 kn=tokenReserve.mul(usdtReserve).mul(kexp).mul(kexp).div(1000000); tokenReserve = tokenReserve + tokenSold; //USTXpool_n temp = k / tokenReserve; //USDamm uint256 usdtsBought = usdtReserve - temp; //out usdtReserve = temp; temp = kn / usdtReserve; //USTXPool_n uint256 burned=tokenReserve - temp; temp = usdtsBought * _feeSell / 10000; //fee usdtsBought = usdtsBought - temp; return (usdtsBought, burned, temp); } /**************************************| | Getter and Setter Functions | |_____________________________________*/ /** * @dev Function to set Token address (only admin) * @param tokenAddress address of the traded token contract */ function setTokenAddr(address tokenAddress) public onlyAdmin { require(tokenAddress != address(0), "INVALID_ADDRESS"); _token = IUSTX(tokenAddress); } /** * @dev Function to set reserve token address (only admin) * @param reserveAddress address of the reserve token contract * @param index token index in array 0-4 * @param decimals number of decimals */ function setReserveTokenAddr(uint256 index, address reserveAddress, uint256 decimals) public onlyAdmin { require(reserveAddress != address(0), "INVALID_ADDRESS"); require(index<5, "INVALID_INDEX"); require(decimals>=6, "INVALID_DECIMALS"); _rt[index] = IERC20(reserveAddress); _rtShift[index] = decimals-_decimals; _rtEnable[index] = 0; _rtTradeEnable[index] = 0; _rtValue[index] = 1000; } /** * @dev Function to enable reserve token (only admin) * @param index token index in array 0-4 * @param enable 0-1 */ function setReserveTokenEnable(uint256 index, uint256 enable) public onlyAdmin { require(index<5, "INVALID_INDEX"); _rtEnable[index] = enable; } /** * @dev Function to enable reserve token trading (only admin) * @param index token index in array 0-4 * @param enable 0-1 */ function setReserveTokenTradeEnable(uint256 index, uint256 enable) public onlyAdmin { require(index<5, "INVALID_INDEX"); _rtTradeEnable[index] = enable; } /** * @dev Function to set reserve token value, relative to 1USD (only admin) * @param index token index in array 0-4 * @param value in TH (0-1000) */ function setReserveTokenValue(uint256 index, uint256 value) public onlyAdmin { require(index<5, "INVALID_INDEX"); require(value<=1000, "Invalid value range"); _rtValue[index] = value; } /** * @dev Function to set fees (only admin) * @param feeBuy fee for buy operations (in basis points) * @param feeSell fee for sell operations (in basis points) */ function setFees(uint256 feeBuy, uint256 feeSell) public onlyAdmin { require(feeBuy<=MAX_FEE && feeSell<=MAX_FEE,"Fees cannot be higher than MAX_FEE"); _feeBuy=feeBuy; _feeSell=feeSell; } /** * @dev Function to get fees * @return buy and sell fees in basis points * */ function getFees() public view returns (uint256, uint256) { return (_feeBuy, _feeSell); } /** * @dev Function to set target ratio level (only admin) * @param ratioExp target reserve ratio for expansion (in thousandths) * @param ratioDamp target reserve ratio for damping (in thousandths) */ function setTargetRatio(uint256 ratioExp, uint256 ratioDamp) public onlyAdmin { require(ratioExp<=1000 && ratioExp>=10 && ratioDamp<=1000 && ratioDamp >=10,"Target ratio must be between 1% and 100%"); _targetRatioExp = ratioExp; //in TH _targetRatioDamp = ratioDamp; //in TH } /** * @dev Function to get target ratio level * return ratioExp and ratioDamp in thousandths * */ function getTargetRatio() public view returns (uint256, uint256) { return (_targetRatioExp, _targetRatioDamp); } /** * @dev Function to get currect reserve ratio level * return current ratio in thousandths * */ function getCurrentRatio() public view returns (uint256) { uint256 tokenBalance = _token.balanceOf(address(this)); uint256 reserveBalance = getReserveBalance(); uint256 tokenCirc = _token.totalSupply(); //total tokenCirc = tokenCirc - tokenBalance; uint256 price = getPrice(); //multiplied by 10**decimals uint256 cirCap = price * tokenCirc; //multiplied by 10**decimals uint256 ratio = reserveBalance * 1000000000 / cirCap; //in TH return ratio; } /** * @dev Function to set target expansion factors (only admin) * @param expF expansion factor (in thousandths) * @param minExp minimum expansion coefficient to use (in thousandths) */ function setExpFactors(uint256 expF, uint256 minExp) public onlyAdmin { require(expF<=10000 && minExp<=1000,"Expansion factor cannot be more than 1000% and the minimum expansion cannot be over 100%"); _expFactor=expF; _minExp=minExp; } /** * @dev Function to get expansion factors * @return _expFactor and _minExp in thousandths * */ function getExpFactors() public view returns (uint256, uint256) { return (_expFactor,_minExp); } /** * @dev Function to set target damping factors (only admin) * @param dampF damping factor (in thousandths) * @param maxDamp maximum damping to use (in thousandths) */ function setDampFactors(uint256 dampF, uint256 maxDamp) public onlyAdmin { require(dampF<=1000 && maxDamp<=1000,"Damping factor cannot be more than 100% and the maximum damping be over 100%"); _dampFactor=dampF; _maxDamp=maxDamp; } /** * @dev Function to get damping factors * @return _dampFactor and _maxDamp in thousandths * */ function getDampFactors() public view returns (uint256, uint256) { return (_dampFactor,_maxDamp); } /** * @dev Function to get current price * @return current price * */ function getPrice() public view returns (uint256) { if (_launchEnabled>0) { return (_launchPrice); }else { uint256 tokenBalance = _token.balanceOf(address(this)); uint256 reserveBalance = getReserveBalance(); return (reserveBalance * (10**_decimals) / tokenBalance); //price with decimals } } /** * @dev Function to get address of the traded token contract * @return Address of token that is traded on this exchange * */ function getTokenAddress() public view returns (address) { return address(_token); } /** * @dev Function to get the address of the reserve token contract * @param index token index in array 0-4 * @return Address of token, relative decimal shift, enable, gradeenable, value, balance */ function getReserveData(uint256 index) public view returns (address, uint256, uint256, uint256, uint256, uint256) { uint256 bal=_rt[index].balanceOf(address(this)); return (address(_rt[index]), _rtShift[index], _rtEnable[index], _rtTradeEnable[index], _rtValue[index], bal); } /** * @dev Function to get total reserve balance * @return reserve balance */ function getReserveBalance() public view returns (uint256) { uint256 j=0; uint256 temp; uint256 reserve=0; for (j=0; j<5; j++) { temp=0; if (_rtEnable[j]>0) { temp = _rt[j].balanceOf(address(this)); temp = temp * _rtValue[j] / 1000; temp = temp / (10**_rtShift[j]); } reserve += temp; } return reserve; } /** * @dev Function to get current reserves balance * @return USD reserve, USTX reserve, USTX circulating, collected fees */ function getBalances() public view returns (uint256,uint256,uint256,uint256) { uint256 tokenBalance = _token.balanceOf(address(this)); uint256 reserveBalance = getReserveBalance(); uint256 tokenCirc = _token.totalSupply() - tokenBalance; return (reserveBalance,tokenBalance,tokenCirc,_collectedFees); } /** * @dev Function to get every reserve token balance * @return b0, b1, b2, b3, b4 balances */ function getEveryReserveBalance() public view returns (uint256,uint256,uint256,uint256,uint256) { uint256 j=0; uint256[5] memory b; for (j=0; j<5; j++) { if (_rtEnable[j]>0) { b[j] = _rt[j].balanceOf(address(this)); b[j] = b[j] / (10**_rtShift[j]); } } return (b[0], b[1], b[2], b[3], b[4]); } /** * @dev Function to enable launchpad (only admin) * @param price launchpad fixed price * @param target launchpad target USTX sale * @param maxLot launchpad maximum purchase size in USDT * @param fee launchpad fee for the dev team (in basis points) * @return true if launchpad is enabled */ function enableLaunchpad(uint256 price, uint256 target, uint256 maxLot, uint256 fee) public onlyAdmin returns (bool) { require(price>0 && target>0 && maxLot>0 && fee<=MAX_LAUNCH_FEE,"Price, target and max lotsize cannot be 0. Fee must be lower than MAX_LAUNCH_FEE"); _launchPrice = price; //in USDT units _launchTargetSize = target; //in USTX units _launchBought = 0; //in USTX units _launchFee = fee; //in bp _launchMaxLot = maxLot; //in USDT units _launchEnabled = 1; return true; } /** * @dev Function to disable launchpad (only admin) * * */ function disableLaunchpad() public onlyAdmin { _launchEnabled = 0; } /** * @dev Function to get launchpad status (only admin) * @return enabled state, price, amount of tokens bought, target tokens, max ourschase lot, fee * */ function getLaunchpadStatus() public view returns (uint256, uint256, uint256, uint256, uint256, uint256) { return (_launchEnabled,_launchPrice,_launchBought,_launchTargetSize,_launchMaxLot,_launchFee); } /** * @dev Set team address (only admin) * @param team address for collecting fees */ function setTeamAddress(address team) public onlyAdmin { require(team != address(0) && team != address(this), "Invalid team address"); _launchTeamAddr = team; } }
* @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 make it call a `private` function that does the actual work./ On the first call to nonReentrant, _notEntered will be true Any calls to nonReentrant after this point will fail By storing the original value once again, a refund is triggered (see https:eips.ethereum.org/EIPS/eip-2200)
modifier nonReentrant() { require(_notEntered, "ReentrancyGuard: reentrant call"); _notEntered = false; _; _notEntered = true; } |__________________________________*/
12,534,527
[ 1, 25828, 87, 279, 6835, 628, 4440, 6174, 16, 5122, 578, 16807, 715, 18, 21020, 279, 1375, 5836, 426, 8230, 970, 68, 445, 628, 4042, 1375, 5836, 426, 8230, 970, 68, 445, 353, 486, 3260, 18, 2597, 353, 3323, 358, 5309, 333, 628, 5865, 310, 635, 10480, 326, 1375, 5836, 426, 8230, 970, 68, 445, 3903, 16, 471, 1221, 518, 745, 279, 1375, 1152, 68, 445, 716, 1552, 326, 3214, 1440, 18, 19, 2755, 326, 1122, 745, 358, 1661, 426, 8230, 970, 16, 389, 902, 10237, 329, 903, 506, 638, 5502, 4097, 358, 1661, 426, 8230, 970, 1839, 333, 1634, 903, 2321, 2525, 15729, 326, 2282, 460, 3647, 3382, 16, 279, 16255, 353, 10861, 261, 5946, 2333, 30, 73, 7146, 18, 546, 822, 379, 18, 3341, 19, 41, 2579, 55, 19, 73, 625, 17, 3787, 713, 13, 2, 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, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1661, 426, 8230, 970, 1435, 288, 203, 3639, 2583, 24899, 902, 10237, 329, 16, 315, 426, 8230, 12514, 16709, 30, 283, 8230, 970, 745, 8863, 203, 203, 3639, 389, 902, 10237, 329, 273, 629, 31, 203, 203, 3639, 389, 31, 203, 203, 3639, 389, 902, 10237, 329, 273, 638, 31, 203, 565, 289, 203, 203, 202, 96, 21157, 21157, 972, 5549, 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 ]
./partial_match/4/0xCCE8143220Cc59789C5C885b2dF28F3F31263a87/sources/TKOstaking.sol
TKO token contract address Fee collect address Fee collect address reward rate 0.05% per day Staking total time transaction fee 0.02 percent
contract TKOstaking is Ownable { using SafeMath for uint; using EnumerableSet for EnumerableSet.AddressSet; event RewardsTransferred(address holder, uint amount); address public constant tokenAddress = 0x14513241b964201A3E5497dBA5CC46eF4D5cb6d0; address public constant feeAddress = 0x59BA4C88129D6178657fC039D6f70a8873628826; address public constant TKOFoundationWallet = 0x585a8CbE3da9FA0aAe424D6D25bb1029D0F78e98; uint public totalClaimedRewards = 0; uint public rewardRate = 5; uint public constant rewardInterval = 1 days; uint public stakingTotalTime; uint public stakingFeeRate = 2; EnumerableSet.AddressSet private holders; mapping (address => uint) public depositedTokens; mapping (address => uint) public stakingTime; mapping (address => uint) public lastClaimedTime; mapping (address => uint) public totalEarnedTokens; constructor() public{ stakingTotalTime = now + 180 days; } function stakingPoolStop() public onlyOwner{ require(now >= stakingTotalTime,"Pool is not over yet!"); uint256 balance = Token(tokenAddress).balanceOf(address(this)); require(Token(tokenAddress).transfer(TKOFoundationWallet, balance), "Could not transfer tokens."); } function updateRewardRate(uint _newRewardRate) public onlyOwner{ rewardRate = _newRewardRate; } function updateFeeRate(uint _newFeeRate) public onlyOwner{ stakingFeeRate = _newFeeRate; } function updateStakingTime(uint _timeInDays) public onlyOwner{ stakingTotalTime = now + _timeInDays.mul(86400); } function updateAccount(address account) private { uint pendingDivs = getPendingDivs(account); if (pendingDivs > 0) { require(Token(tokenAddress).transfer(account, pendingDivs), "Could not transfer tokens."); totalEarnedTokens[account] = totalEarnedTokens[account].add(pendingDivs); totalClaimedRewards = totalClaimedRewards.add(pendingDivs); emit RewardsTransferred(account, pendingDivs); } lastClaimedTime[account] = now; } function updateAccount(address account) private { uint pendingDivs = getPendingDivs(account); if (pendingDivs > 0) { require(Token(tokenAddress).transfer(account, pendingDivs), "Could not transfer tokens."); totalEarnedTokens[account] = totalEarnedTokens[account].add(pendingDivs); totalClaimedRewards = totalClaimedRewards.add(pendingDivs); emit RewardsTransferred(account, pendingDivs); } lastClaimedTime[account] = now; } function getPendingDivs(address _holder) public view returns (uint) { if (!holders.contains(_holder)) return 0; if (depositedTokens[_holder] == 0) return 0; uint timeDiff = now.sub(lastClaimedTime[_holder]); uint stakedAmount = depositedTokens[_holder]; uint pendingDivs = stakedAmount .mul(rewardRate) .mul(timeDiff) .div(rewardInterval) .div(1e4); return pendingDivs; } function getNumberOfHolders() public view returns (uint) { return holders.length(); } function deposit(uint amountToStake) public { require(now < stakingTotalTime,"Staking pool time is ended"); require(amountToStake > 0, "Cannot deposit 0 Tokens"); require(Token(tokenAddress).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance"); updateAccount(msg.sender); uint fee = amountToStake.mul(stakingFeeRate).div(1e4); uint amountAfterFee = amountToStake.sub(fee); require(Token(tokenAddress).transfer(feeAddress, fee), "Could not transfer deposit fee."); depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountAfterFee); if (!holders.contains(msg.sender)) { holders.add(msg.sender); stakingTime[msg.sender] = now; } } function deposit(uint amountToStake) public { require(now < stakingTotalTime,"Staking pool time is ended"); require(amountToStake > 0, "Cannot deposit 0 Tokens"); require(Token(tokenAddress).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance"); updateAccount(msg.sender); uint fee = amountToStake.mul(stakingFeeRate).div(1e4); uint amountAfterFee = amountToStake.sub(fee); require(Token(tokenAddress).transfer(feeAddress, fee), "Could not transfer deposit fee."); depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountAfterFee); if (!holders.contains(msg.sender)) { holders.add(msg.sender); stakingTime[msg.sender] = now; } } function withdraw(uint amountToWithdraw) public { require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw"); uint fee = amountToWithdraw.mul(stakingFeeRate).div(1e4); uint amountAfterFee = amountToWithdraw.sub(fee); require(Token(tokenAddress).transfer(feeAddress, fee), "Could not transfer deposit fee."); updateAccount(msg.sender); require(Token(tokenAddress).transfer(msg.sender, amountAfterFee), "Could not transfer tokens."); depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw); if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) { holders.remove(msg.sender); } } function withdraw(uint amountToWithdraw) public { require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw"); uint fee = amountToWithdraw.mul(stakingFeeRate).div(1e4); uint amountAfterFee = amountToWithdraw.sub(fee); require(Token(tokenAddress).transfer(feeAddress, fee), "Could not transfer deposit fee."); updateAccount(msg.sender); require(Token(tokenAddress).transfer(msg.sender, amountAfterFee), "Could not transfer tokens."); depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw); if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) { holders.remove(msg.sender); } } function claimDivs() public { updateAccount(msg.sender); } }
8,610,322
[ 1, 56, 47, 51, 1147, 6835, 1758, 30174, 3274, 1758, 30174, 3274, 1758, 19890, 4993, 374, 18, 6260, 9, 1534, 2548, 934, 6159, 2078, 813, 2492, 14036, 374, 18, 3103, 5551, 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, 399, 47, 51, 334, 6159, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 565, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 1887, 694, 31, 203, 377, 203, 565, 871, 534, 359, 14727, 1429, 4193, 12, 2867, 10438, 16, 2254, 3844, 1769, 203, 377, 203, 565, 1758, 1071, 5381, 1147, 1887, 273, 374, 92, 3461, 10593, 1578, 9803, 70, 29, 1105, 6734, 37, 23, 41, 6564, 10580, 72, 12536, 25, 6743, 8749, 73, 42, 24, 40, 25, 7358, 26, 72, 20, 31, 203, 565, 1758, 1071, 5381, 14036, 1887, 273, 374, 92, 6162, 12536, 24, 39, 5482, 24886, 40, 26, 4033, 5292, 10321, 74, 39, 4630, 29, 40, 26, 74, 7301, 69, 5482, 27, 5718, 22, 5482, 5558, 31, 203, 565, 1758, 1071, 5381, 399, 47, 51, 27788, 16936, 273, 374, 92, 25, 7140, 69, 28, 15237, 41, 23, 2414, 29, 2046, 20, 69, 37, 73, 24, 3247, 40, 26, 40, 2947, 9897, 2163, 5540, 40, 20, 42, 8285, 73, 10689, 31, 203, 377, 203, 565, 2254, 1071, 2078, 9762, 329, 17631, 14727, 273, 374, 31, 203, 565, 2254, 1071, 225, 19890, 4727, 273, 1381, 31, 203, 565, 2254, 1071, 5381, 19890, 4006, 273, 404, 4681, 31, 203, 565, 2254, 1071, 384, 6159, 5269, 950, 31, 203, 565, 2254, 1071, 384, 6159, 14667, 4727, 273, 576, 31, 203, 377, 203, 565, 6057, 25121, 694, 18, 1887, 694, 3238, 366, 4665, 31, 203, 377, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 443, 1724, 329, 5157, 31, 2 ]
./full_match/1/0xc4824156785BE733d9B98ac4813DA0c7bc1B7A44/sources/src/uniswapv3lp.sol
* @notice Increases liquidity in the current range @dev Pool must be initialized already to add liquidity @param tokenId The id of the erc721 token @param amount0 The amount to add of token0 @param amount1 The amount to add of token1/ Remove allowance and refund in both assets.
function increaseLiquidityCurrentRange(uint256 tokenId, uint256 amountAdd0, uint256 amountAdd1, uint256 slippage, address referrer) external returns (uint128 liquidity, uint256 amount0, uint256 amount1) { address token0 = deposits[tokenId].token0; address token1 = deposits[tokenId].token1; TransferHelper.safeTransferFrom(token0, msg.sender, address(this), amountAdd0); TransferHelper.safeTransferFrom(token1, msg.sender, address(this), amountAdd1); TransferHelper.safeApprove(token0, address(_posMgr), amountAdd0); TransferHelper.safeApprove(token1, address(_posMgr), amountAdd1); INonfungiblePositionManager.IncreaseLiquidityParams memory params = INonfungiblePositionManager .IncreaseLiquidityParams({ tokenId: tokenId, amount0Desired: amountAdd0, amount1Desired: amountAdd1, amount0Min: slippagify(amountAdd0, slippage), amount1Min: slippagify(amountAdd1, slippage), deadline: block.timestamp }); (liquidity, amount0, amount1) = _posMgr.increaseLiquidity(params); if (amount0 < amountAdd0) { TransferHelper.safeApprove(token0, address(_posMgr), 0); uint256 refund0 = amountAdd0 - amount0; TransferHelper.safeTransfer(token0, msg.sender, refund0); } if (amount1 < amountAdd1) { TransferHelper.safeApprove(token1, address(_posMgr), 0); uint256 refund1 = amountAdd1 - amount1; TransferHelper.safeTransfer(token1, msg.sender, refund1); } { totalLPSupplyFromOwner[tokenId] = totalLPSupplyFromOwner[tokenId] + liquidity; balances[owner()][tokenId] = balances[owner()][tokenId].add(liquidity); } else { LPStakingEngine(nftIdToStakingEngine[tokenId]).deposit(liquidity,msg.sender,referrer); balances[msg.sender][tokenId] = balances[msg.sender][tokenId].add(liquidity); } totalLPSupply[tokenId] = totalLPSupply[tokenId] + liquidity; }
8,480,280
[ 1, 27597, 3304, 4501, 372, 24237, 316, 326, 783, 1048, 225, 8828, 1297, 506, 6454, 1818, 358, 527, 4501, 372, 24237, 225, 1147, 548, 1021, 612, 434, 326, 6445, 71, 27, 5340, 1147, 225, 3844, 20, 1021, 3844, 358, 527, 434, 1147, 20, 225, 3844, 21, 1021, 3844, 358, 527, 434, 1147, 21, 19, 3581, 1699, 1359, 471, 16255, 316, 3937, 7176, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 10929, 48, 18988, 24237, 3935, 2655, 12, 11890, 5034, 1147, 548, 16, 2254, 5034, 3844, 986, 20, 16, 2254, 5034, 3844, 986, 21, 16, 2254, 5034, 272, 3169, 2433, 16, 1758, 14502, 13, 203, 3639, 3903, 203, 3639, 1135, 261, 11890, 10392, 4501, 372, 24237, 16, 2254, 5034, 3844, 20, 16, 2254, 5034, 3844, 21, 13, 203, 565, 288, 203, 3639, 1758, 1147, 20, 273, 443, 917, 1282, 63, 2316, 548, 8009, 2316, 20, 31, 203, 3639, 1758, 1147, 21, 273, 443, 917, 1282, 63, 2316, 548, 8009, 2316, 21, 31, 203, 3639, 12279, 2276, 18, 4626, 5912, 1265, 12, 2316, 20, 16, 1234, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 986, 20, 1769, 203, 3639, 12279, 2276, 18, 4626, 5912, 1265, 12, 2316, 21, 16, 1234, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 986, 21, 1769, 203, 203, 3639, 12279, 2276, 18, 4626, 12053, 537, 12, 2316, 20, 16, 1758, 24899, 917, 9455, 3631, 3844, 986, 20, 1769, 203, 3639, 12279, 2276, 18, 4626, 12053, 537, 12, 2316, 21, 16, 1758, 24899, 917, 9455, 3631, 3844, 986, 21, 1769, 203, 203, 3639, 2120, 265, 12125, 75, 1523, 2555, 1318, 18, 382, 11908, 48, 18988, 24237, 1370, 3778, 859, 273, 2120, 265, 12125, 75, 1523, 2555, 1318, 203, 5411, 263, 382, 11908, 48, 18988, 24237, 1370, 12590, 203, 5411, 1147, 548, 30, 1147, 548, 16, 203, 5411, 3844, 20, 25683, 30, 3844, 986, 20, 16, 203, 5411, 3844, 21, 25683, 30, 3844, 986, 21, 16, 203, 5411, 3844, 20, 2930, 2 ]
./full_match/1/0xbc5f420C1A0ABC1740d16A834C93F8AC9235A5cb/sources/contracts/protocol/PunkGateway.sol
* @notice Deposits a punk given its index - E.g. User deposit NFT Punk and receives the wrapped asset @param punkIndex The index of the CryptoPunk to deposit/
function _depositPunk(uint256 punkIndex) internal { ILendPoolLoan cachedPoolLoan = _getLendPoolLoan(); uint256 loanId = cachedPoolLoan.getCollateralLoanId(address(wrappedPunks), punkIndex); if (loanId != 0) { return; } address owner = punks.punkIndexToAddress(punkIndex); require(owner == _msgSender(), "PunkGateway: not owner of punkIndex"); punks.buyPunk(punkIndex); punks.transferPunk(proxy, punkIndex); wrappedPunks.mint(punkIndex); }
3,219,864
[ 1, 758, 917, 1282, 279, 293, 1683, 864, 2097, 770, 300, 512, 18, 75, 18, 2177, 443, 1724, 423, 4464, 453, 1683, 471, 17024, 326, 5805, 3310, 225, 293, 1683, 1016, 1021, 770, 434, 326, 15629, 52, 1683, 358, 443, 1724, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 389, 323, 1724, 52, 1683, 12, 11890, 5034, 293, 1683, 1016, 13, 2713, 288, 203, 565, 467, 48, 409, 2864, 1504, 304, 3472, 2864, 1504, 304, 273, 389, 588, 48, 409, 2864, 1504, 304, 5621, 203, 203, 565, 2254, 5034, 28183, 548, 273, 3472, 2864, 1504, 304, 18, 588, 13535, 2045, 287, 1504, 304, 548, 12, 2867, 12, 18704, 52, 1683, 87, 3631, 293, 1683, 1016, 1769, 203, 565, 309, 261, 383, 304, 548, 480, 374, 13, 288, 203, 1377, 327, 31, 203, 565, 289, 203, 203, 565, 1758, 3410, 273, 293, 1683, 87, 18, 84, 1683, 1016, 774, 1887, 12, 84, 1683, 1016, 1769, 203, 565, 2583, 12, 8443, 422, 389, 3576, 12021, 9334, 315, 52, 1683, 5197, 30, 486, 3410, 434, 293, 1683, 1016, 8863, 203, 203, 565, 293, 1683, 87, 18, 70, 9835, 52, 1683, 12, 84, 1683, 1016, 1769, 203, 565, 293, 1683, 87, 18, 13866, 52, 1683, 12, 5656, 16, 293, 1683, 1016, 1769, 203, 565, 5805, 52, 1683, 87, 18, 81, 474, 12, 84, 1683, 1016, 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 ]
pragma solidity ^0.4.15; /* @dev ERC Token Standard #20 Interface (https://github.com/ethereum/EIPs/issues/20) */ contract ERC20 { //Use original ERC20 totalSupply function instead of public variable since //we are mapping the functions for upgradeability uint256 public totalSupply; function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // Licensed under the MIT License // Copyright (c) 2017 Curvegrid Inc. /// @title OfflineSecret /// @dev The OfflineSecret contract provide functionality to verify and ensure a caller /// provides a valid secret that was exchanged offline. It offers an additional level of verification /// for sensitive contract operations. contract OfflineSecret { /// @dev Modifier that requires a provided plaintext match a previously stored hash modifier validSecret(address to, string secret, bytes32 hashed) { require(checkSecret(to, secret, hashed)); _; } /// @dev Generate a hash from the provided plaintext. A pure function so can (should) be /// run off-chain. /// @param to address The recipient address, as a salt. /// @param secret string The secret to hash. function generateHash(address to, string secret) public pure returns(bytes32 hashed) { return keccak256(to, secret); } /// @dev Check whether a provided plaintext secret hashes to a provided hash. A pure /// function so can (should) be run off-chain. /// @param to address The recipient address, as a salt. /// @param secret string The secret to hash. /// @param hashed string The hash to check the secret against. function checkSecret(address to, string secret, bytes32 hashed) public pure returns(bool valid) { if (hashed == keccak256(to, secret)) { return true; } return false; } } // Licensed under the MIT License // Copyright (c) 2017 Curvegrid Inc. /// @title Ownable /// @dev The Ownable contract has an owner address, and provides basic authorization control functions, this simplifies /// and the implementation of "user permissions". contract OwnableWithFoundation is OfflineSecret { address public owner; address public newOwnerCandidate; address public foundation; address public newFoundationCandidate; bytes32 public ownerHashed; bytes32 public foundationHashed; event OwnershipRequested(address indexed by, address indexed to, bytes32 hashed); event OwnershipTransferred(address indexed from, address indexed to); event FoundationRequested(address indexed by, address indexed to, bytes32 hashed); event FoundationTransferred(address indexed from, address indexed to); /// @dev The Ownable constructor sets the original `owner` of the contract to the sender /// account. function OwnableWithFoundation(address _owner) public { foundation = msg.sender; owner = _owner; } /// @dev Reverts if called by any account other than the owner. modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } modifier onlyOwnerCandidate() { if (msg.sender != newOwnerCandidate) { revert(); } _; } /// @dev Reverts if called by any account other than the foundation. modifier onlyFoundation() { if (msg.sender != foundation) { revert(); } _; } modifier onlyFoundationCandidate() { if (msg.sender != newFoundationCandidate) { revert(); } _; } /// @dev Proposes to transfer control of the contract to a newOwnerCandidate. /// @param _newOwnerCandidate address The address to transfer ownership to. /// @param _ownerHashed string The hashed secret to use as protection. function requestOwnershipTransfer( address _newOwnerCandidate, bytes32 _ownerHashed) external onlyFoundation { require(_newOwnerCandidate != address(0)); require(_newOwnerCandidate != owner); newOwnerCandidate = _newOwnerCandidate; ownerHashed = _ownerHashed; OwnershipRequested(msg.sender, newOwnerCandidate, ownerHashed); } /// @dev Accept ownership transfer. This method needs to be called by the previously proposed owner. /// @param _ownerSecret string The secret to check against the hash. function acceptOwnership( string _ownerSecret) external onlyOwnerCandidate validSecret(newOwnerCandidate, _ownerSecret, ownerHashed) { address previousOwner = owner; owner = newOwnerCandidate; newOwnerCandidate = address(0); OwnershipTransferred(previousOwner, owner); } /// @dev Proposes to transfer control of the contract to a newFoundationCandidate. /// @param _newFoundationCandidate address The address to transfer oversight to. /// @param _foundationHashed string The hashed secret to use as protection. function requestFoundationTransfer( address _newFoundationCandidate, bytes32 _foundationHashed) external onlyFoundation { require(_newFoundationCandidate != address(0)); require(_newFoundationCandidate != foundation); newFoundationCandidate = _newFoundationCandidate; foundationHashed = _foundationHashed; FoundationRequested(msg.sender, newFoundationCandidate, foundationHashed); } /// @dev Accept foundation transfer. This method needs to be called by the previously proposed foundation. /// @param _foundationSecret string The secret to check against the hash. function acceptFoundation( string _foundationSecret) external onlyFoundationCandidate validSecret(newFoundationCandidate, _foundationSecret, foundationHashed) { address previousFoundation = foundation; foundation = newFoundationCandidate; newFoundationCandidate = address(0); FoundationTransferred(previousFoundation, foundation); } } /* @dev Math operations with safety checks */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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; } 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; } } // Licensed under the MIT License // Copyright (c) 2017 Curvegrid Inc. /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is OwnableWithFoundation { event Pause(); event Unpause(); bool public paused = false; function Pausable(address _owner) public OwnableWithFoundation(_owner) { } /** * @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 Basic ERC20 token contract implementation. /* @dev Kin's BasicToken based on OpenZeppelin's StandardToken. */ contract BasicToken is ERC20 { using SafeMath for uint256; uint256 public totalSupply; mapping (address => mapping (address => uint256)) allowed; mapping (address => uint256) balances; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); /// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. /// @param _spender address The address which will spend the funds. /// @param _value uint256 The amount of tokens to be spent. function approve(address _spender, uint256 _value) public returns (bool) { // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) { revert(); } 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 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]; } /// @dev Gets the balance of the specified address. /// @param _owner address The address to query the the balance of. /// @return uint256 representing the amount owned by the passed address. function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } /// @dev transfer token to a specified address. /// @param _to address The address to transfer to. /// @param _value uint256 The amount to be transferred. function transfer(address _to, uint256 _value) public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /// @dev Transfer tokens from one address to another. /// @param _from address The address which you want to send tokens from. /// @param _to address The address which you want to transfer to. /// @param _value uint256 the amount of tokens to be transferred. function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { 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); Transfer(_from, _to, _value); return true; } } // Licensed under the MIT License // Copyright (c) 2017 Curvegrid Inc. /** * @dev ERC Token Standard #20 Interface (https://github.com/ethereum/EIPs/issues/20) * D1Coin is the main contract for the D1 platform. */ contract D1Coin is BasicToken, Pausable { using SafeMath for uint256; string public constant name = "D1 Coin"; string public constant symbol = "D1"; // Thousands of a token represent the minimum usable unit of token based on // its expected value uint8 public constant decimals = 3; address theCoin = address(this); // Hashed secrets required to unlock coins transferred from one address to another address struct ProtectedBalanceStruct { uint256 balance; bytes32 hashed; } mapping (address => mapping (address => ProtectedBalanceStruct)) protectedBalances; uint256 public protectedSupply; // constructor passes owner (Mint) down to Pausable() => OwnableWithFoundation() function D1Coin(address _owner) public Pausable(_owner) { } event Mint(address indexed minter, address indexed receiver, uint256 value); event ProtectedTransfer(address indexed from, address indexed to, uint256 value, bytes32 hashed); event ProtectedUnlock(address indexed from, address indexed to, uint256 value); event ProtectedReclaim(address indexed from, address indexed to, uint256 value); event Burn(address indexed burner, uint256 value); /// @dev Transfer token to this contract, which is shorthand for the owner (Mint). /// Avoids race conditions in cases where the owner has changed just before a /// transfer is called. /// @param _value uint256 The amount to be transferred. function transferToMint(uint256 _value) external whenNotPaused returns (bool) { return transfer(theCoin, _value); } /// @dev Approve this contract, proxy for owner (Mint), to spend the specified amount of tokens /// on behalf of msg.sender. Avoids race conditions in cases where the owner has changed /// just before an approve is called. /// @param _value uint256 The amount of tokens to be spent. function approveToMint(uint256 _value) external whenNotPaused returns (bool) { return approve(theCoin, _value); } /// @dev Protected transfer tokens to this contract, which is shorthand for the owner (Mint). /// Avoids race conditions in cases where the owner has changed just before a /// transfer is called. /// @param _value uint256 The amount to be transferred. /// @param _hashed string The hashed secret to use as protection. function protectedTransferToMint(uint256 _value, bytes32 _hashed) external whenNotPaused returns (bool) { return protectedTransfer(theCoin, _value, _hashed); } /// @dev Transfer tokens from an address to this contract, a proxy for the owner (Mint). /// Subject to pre-approval from the address. Avoids race conditions in cases where the owner has changed /// just before an approve is called. /// @param _from address The address which you want to send tokens from. /// @param _value uint256 the amount of tokens to be transferred. function withdrawByMint(address _from, uint256 _value) external onlyOwner whenNotPaused returns (bool) { // retrieve allowance uint256 _allowance = allowed[_from][theCoin]; // adjust balances balances[_from] = balances[_from].sub(_value); balances[theCoin] = balances[theCoin].add(_value); // adjust allowance allowed[_from][theCoin] = _allowance.sub(_value); Transfer(_from, theCoin, _value); return true; } /// @dev Creates a specific amount of tokens and credits them to the Mint. /// @param _amount uint256 Amount tokens to mint. function mint(uint256 _amount) external onlyOwner whenNotPaused { require(_amount > 0); totalSupply = totalSupply.add(_amount); balances[theCoin] = balances[theCoin].add(_amount); Mint(msg.sender, theCoin, _amount); // optional in ERC-20 standard, but required by Etherscan Transfer(address(0), theCoin, _amount); } /// @dev Retrieve the protected balance and hashed passphrase for a pending protected transfer. /// @param _from address The address transferred from. /// @param _to address The address transferred to. function protectedBalance(address _from, address _to) public constant returns (uint256 balance, bytes32 hashed) { return(protectedBalances[_from][_to].balance, protectedBalances[_from][_to].hashed); } /// @dev Transfer tokens to a specified address protected by a secret. /// @param _to address The address to transfer to. /// @param _value uint256 The amount to be transferred. /// @param _hashed string The hashed secret to use as protection. function protectedTransfer(address _to, uint256 _value, bytes32 _hashed) public whenNotPaused returns (bool) { require(_value > 0); // "transfers" to address(0) should only be by the burn() function require(_to != address(0)); // explicitly disallow tranfer to the owner, as it's automatically translated into the coin // in protectedUnlock() and protectedReclaim() require(_to != owner); address from = msg.sender; // special case: msg.sender is the owner (Mint) if (msg.sender == owner) { from = theCoin; // ensure Mint is actually holding this supply; not required below because of revert in .sub() require(balances[theCoin].sub(protectedSupply) >= _value); } else { // otherwise, adjust the balances: transfer the tokens to the Mint to have them held in escrow balances[from] = balances[from].sub(_value); balances[theCoin] = balances[theCoin].add(_value); } // protected balance must be zero (unlocked or reclaimed in its entirety) // avoid a situation similar to: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if (protectedBalances[from][_to].balance != 0) { revert(); } // disallow reusing the previous secret // (not intended to prevent reuse of an N-x, x > 1 secret) require(protectedBalances[from][_to].hashed != _hashed); // set the protected balance and hashed value protectedBalances[from][_to].balance = _value; protectedBalances[from][_to].hashed = _hashed; // adjust the protected supply protectedSupply = protectedSupply.add(_value); ProtectedTransfer(from, _to, _value, _hashed); return true; } /// @dev Unlock protected tokens from an address. /// @param _from address The address to transfer from. /// @param _value uint256 The amount to be transferred. /// @param _secret string The secret phrase protecting the tokens. function protectedUnlock(address _from, uint256 _value, string _secret) external whenNotPaused returns (bool) { address to = msg.sender; // special case: msg.sender is the owner (Mint) if (msg.sender == owner) { to = theCoin; } // validate secret against hash require(checkSecret(to, _secret, protectedBalances[_from][to].hashed)); // must transfer all protected tokens at once as secret will have been leaked on the blockchain require(protectedBalances[_from][to].balance == _value); // adjust the balances: the Mint is holding the tokens in escrow balances[theCoin] = balances[theCoin].sub(_value); balances[to] = balances[to].add(_value); // adjust the protected balances and protected supply protectedBalances[_from][to].balance = 0; protectedSupply = protectedSupply.sub(_value); ProtectedUnlock(_from, to, _value); Transfer(_from, to, _value); return true; } /// @dev Reclaim protected tokens granted to a specified address. /// @param _to address The address to the tokens were granted to. /// @param _value uint256 The amount to be transferred. function protectedReclaim(address _to, uint256 _value) external whenNotPaused returns (bool) { address from = msg.sender; // special case: msg.sender is the owner (Mint) if (msg.sender == owner) { from = theCoin; } else { // otherwise, adjust the balances: transfer the tokens to the sender from the Mint, which was holding them in escrow balances[theCoin] = balances[theCoin].sub(_value); balances[from] = balances[from].add(_value); } // must transfer all protected tokens at once require(protectedBalances[from][_to].balance == _value); // adjust the protected balances and protected supply protectedBalances[from][_to].balance = 0; protectedSupply = protectedSupply.sub(_value); ProtectedReclaim(from, _to, _value); return true; } /// @dev Destroys (removes from supply) a specific amount of tokens. /// @param _amount uint256 The amount of tokens to be burned. function burn(uint256 _amount) external onlyOwner whenNotPaused { // The Mint is the owner of this contract. In this implementation, the // address of this contract (proxy for owner's account) is used to control // the money supply. Avoids the problem of having to transfer balances on owner change. require(_amount > 0); require(_amount <= balances[theCoin].sub(protectedSupply)); // account for protected balances // adjust the balances and supply balances[theCoin] = balances[theCoin].sub(_amount); totalSupply = totalSupply.sub(_amount); // not part of the ERC-20 standard, but required by Etherscan Transfer(theCoin, address(0), _amount); Burn(theCoin, _amount); } /// @dev ERC20 behaviour but revert if paused /// @param _spender address The address which will spend the funds. /// @param _value uint256 The amount of tokens to be spent. function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } /// @dev ERC20 behaviour but revert if paused /// @param _owner address The address which owns the funds. /// @param _spender address The address which will spend the funds. /// @return uint256 specifying the amount of tokens still available for the spender. function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return super.allowance(_owner, _spender); } /// @dev ERC20 behaviour but revert if paused /// @param _to address The address to transfer to. /// @param _value uint256 The amount to be transferred. function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { // "transfers" to address(0) should only be by the burn() function require(_to != address(0)); return super.transfer(_to, _value); } /// @dev ERC20 behaviour but revert if paused /// @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 whenNotPaused returns (bool) { // "transfers" to address(0) should only be by the burn() function require(_to != address(0)); // special case: _from is the Mint // note: within the current D1 Coin design, should never encounter this case if (_from == theCoin) { // ensure Mint is not exceeding its balance less protected supply require(_value <= balances[theCoin].sub(protectedSupply)); } return super.transferFrom(_from, _to, _value); } }
@dev Proposes to transfer control of the contract to a newFoundationCandidate. @param _newFoundationCandidate address The address to transfer oversight to. @param _foundationHashed string The hashed secret to use as protection.
function requestFoundationTransfer( address _newFoundationCandidate, bytes32 _foundationHashed) external onlyFoundation { require(_newFoundationCandidate != address(0)); require(_newFoundationCandidate != foundation); newFoundationCandidate = _newFoundationCandidate; foundationHashed = _foundationHashed; FoundationRequested(msg.sender, newFoundationCandidate, foundationHashed); }
5,449,009
[ 1, 626, 10522, 358, 7412, 3325, 434, 326, 6835, 358, 279, 394, 27788, 11910, 18, 225, 389, 2704, 27788, 11910, 1758, 1021, 1758, 358, 7412, 28327, 750, 358, 18, 225, 389, 30493, 2310, 329, 533, 1021, 14242, 4001, 358, 999, 487, 17862, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 590, 27788, 5912, 12, 203, 3639, 1758, 389, 2704, 27788, 11910, 16, 7010, 3639, 1731, 1578, 389, 30493, 2310, 329, 13, 7010, 3639, 3903, 7010, 3639, 1338, 27788, 7010, 565, 288, 203, 3639, 2583, 24899, 2704, 27788, 11910, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 24899, 2704, 27788, 11910, 480, 1392, 367, 1769, 203, 203, 3639, 394, 27788, 11910, 273, 389, 2704, 27788, 11910, 31, 203, 3639, 1392, 367, 2310, 329, 273, 389, 30493, 2310, 329, 31, 203, 203, 3639, 31289, 11244, 12, 3576, 18, 15330, 16, 394, 27788, 11910, 16, 1392, 367, 2310, 329, 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 ]
pragma solidity ^0.4.24; import './SafeMath.sol'; import './ERC20I.sol'; /** * @title Standard ERC20 token * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20I, SafeMath { uint256 totalSupply_; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Total Supply * @return totalSupply_ */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Tokens balance * @param _owner holder address * @return balance amount */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /** * @dev Tranfer tokens to address * @param _to dest address * @param _value tokens amount * @return transfer result */ function transfer(address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); require(balances[msg.sender] >= _value); balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Token allowance * @param _owner holder address * @param _spender spender address * @return remain amount */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Transfer tokens from one address to another * @param _from source address * @param _to dest address * @param _value tokens amount * @return transfer result */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); require(balances[_from] >= _value); require(allowed[_from][msg.sender] >= _value); balances[_from] = safeSub(balances[_from], _value); balances[_to] = safeAdd(balances[_to], _value); allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve transfer * @param _spender holder address * @param _value tokens amount * @return result */ function approve(address _spender, uint256 _value) public returns (bool success) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } }
* @dev Transfer tokens from one address to another @param _from source address @param _to dest address @param _value tokens amount @return transfer result/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); require(balances[_from] >= _value); require(allowed[_from][msg.sender] >= _value); balances[_from] = safeSub(balances[_from], _value); balances[_to] = safeAdd(balances[_to], _value); allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value); emit Transfer(_from, _to, _value); return true; }
15,793,984
[ 1, 5912, 2430, 628, 1245, 1758, 358, 4042, 225, 389, 2080, 1084, 1758, 225, 389, 869, 1570, 1758, 225, 389, 1132, 2430, 3844, 327, 7412, 563, 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 ]
[ 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 565, 2583, 24899, 869, 480, 1758, 12, 20, 10019, 203, 565, 2583, 12, 70, 26488, 63, 67, 2080, 65, 1545, 389, 1132, 1769, 203, 565, 2583, 12, 8151, 63, 67, 2080, 6362, 3576, 18, 15330, 65, 1545, 389, 1132, 1769, 203, 377, 203, 565, 324, 26488, 63, 67, 2080, 65, 273, 4183, 1676, 12, 70, 26488, 63, 67, 2080, 6487, 389, 1132, 1769, 203, 565, 324, 26488, 63, 67, 869, 65, 273, 4183, 986, 12, 70, 26488, 63, 67, 869, 6487, 389, 1132, 1769, 203, 565, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 65, 273, 4183, 1676, 12, 8151, 63, 67, 2080, 6362, 3576, 18, 15330, 6487, 389, 1132, 1769, 203, 377, 203, 565, 3626, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 565, 327, 638, 31, 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 ]
./full_match/4/0xb1086EE7F3cbc3f45065cCc341854A71a94D9062/sources/contracts/ERC721.sol
Clear approvals from the previous owner
function transfer(address _from, address _to, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from, "Cannot transfer a token that you don't own"); require(_to != address(0), "Cannot transfer to the zero address"); _tokenApprovals[_tokenId] = address(0); emit Approval(ownerOf(_tokenId), address(0), _tokenId); _balances[_from]--; _balances[_to]++; _owners[_tokenId] = _to; emit Transfer(_from, _to, _tokenId); }
13,354,330
[ 1, 9094, 6617, 4524, 628, 326, 2416, 3410, 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, 7412, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 2316, 548, 13, 2713, 288, 203, 3639, 2583, 12, 8443, 951, 24899, 2316, 548, 13, 422, 389, 2080, 16, 315, 4515, 7412, 279, 1147, 716, 1846, 2727, 1404, 4953, 8863, 203, 3639, 2583, 24899, 869, 480, 1758, 12, 20, 3631, 315, 4515, 7412, 358, 326, 3634, 1758, 8863, 203, 203, 3639, 389, 2316, 12053, 4524, 63, 67, 2316, 548, 65, 273, 1758, 12, 20, 1769, 203, 3639, 3626, 1716, 685, 1125, 12, 8443, 951, 24899, 2316, 548, 3631, 1758, 12, 20, 3631, 389, 2316, 548, 1769, 203, 203, 3639, 389, 70, 26488, 63, 67, 2080, 65, 413, 31, 203, 3639, 389, 70, 26488, 63, 67, 869, 3737, 15, 31, 203, 3639, 389, 995, 414, 63, 67, 2316, 548, 65, 273, 389, 869, 31, 203, 203, 3639, 3626, 12279, 24899, 2080, 16, 389, 869, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the {Exchange} core. */ abstract contract IExchange { /** * @dev Emitted when a token is purchased. */ event TokenPurchase(address buyer, uint256 ethSold, uint256 tokensBought); /** * @dev Emitted when a token is purchased. */ event EthPurchase(address buyer, uint256 tokenSold, uint256 ethBought); /** * @dev Emitted when liquidity is added to the pool. */ event AddLiquidity(address provider, uint256 ethAmount, uint256 tokenAmount); /** * @dev Emitted when liquidity is removed from the pool. */ event AddLiquidity(address provider, uint256 ethAmount, uint256 tokenAmount); }
* @dev Interface of the {Exchange} core./
abstract contract IExchange { event TokenPurchase(address buyer, uint256 ethSold, uint256 tokensBought); event EthPurchase(address buyer, uint256 tokenSold, uint256 ethBought); event AddLiquidity(address provider, uint256 ethAmount, uint256 tokenAmount); event AddLiquidity(address provider, uint256 ethAmount, uint256 tokenAmount); }
12,703,453
[ 1, 1358, 434, 326, 288, 11688, 97, 2922, 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, 17801, 6835, 467, 11688, 288, 203, 565, 871, 3155, 23164, 12, 2867, 27037, 16, 2254, 5034, 13750, 55, 1673, 16, 2254, 5034, 2430, 13809, 9540, 1769, 203, 203, 565, 871, 512, 451, 23164, 12, 2867, 27037, 16, 2254, 5034, 1147, 55, 1673, 16, 2254, 5034, 13750, 13809, 9540, 1769, 203, 203, 565, 871, 1436, 48, 18988, 24237, 12, 2867, 2893, 16, 2254, 5034, 13750, 6275, 16, 2254, 5034, 1147, 6275, 1769, 203, 203, 565, 871, 1436, 48, 18988, 24237, 12, 2867, 2893, 16, 2254, 5034, 13750, 6275, 16, 2254, 5034, 1147, 6275, 1769, 203, 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 ]
./full_match/137/0x632d83d76E5b325DB698794E677E61523b53a06e/sources/contracts/CloneFactoryV2.sol
@notice Get Template @param templateName : template name @return template : template address
function _template(string memory templateName) internal view virtual returns (address template) { require(templates[templateName] != address(0), "Bad Template"); template = templates[templateName]; }
4,708,029
[ 1, 967, 5035, 282, 15523, 294, 1542, 508, 327, 225, 1542, 294, 1542, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 3202, 12, 1080, 3778, 15523, 13, 2713, 1476, 5024, 1135, 261, 2867, 1542, 13, 288, 203, 3639, 2583, 12, 8502, 63, 3202, 461, 65, 480, 1758, 12, 20, 3631, 315, 6434, 5035, 8863, 203, 203, 3639, 1542, 273, 5539, 63, 3202, 461, 15533, 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 ]
pragma solidity >=0.4.22 <0.9.0; contract PraticaAssicurativa { address private polizia; //Indirizzo ganache polizia address private perito; //Indirizzo ganache perito struct Pratica { uint256 ID; //ID Pratica uint256 costo; //Costo uint256 firmaCount; //Contatore numero firme sulla pratica string nomeIncidente; //Indentificativo incidente string data; //Data string comandoPoliziaMunicipale; //Nome del comando di polizia municipale che ha in gestione la pratica address indirizzoCliente; //Indirizzo cliente che ha aperto la pratica mapping (address => uint256) firme; //Firme } //Questo metodo serve per fare un controllo di convalida per quanto riguarda gli indirizzi della polizia e del perito modifier signOnly { require (msg.sender == polizia|| msg.sender == perito ); _; } constructor() public { polizia= msg.sender; perito = 0x62D6f59fEf467154F6EbC924F8eC74400076a106; //assegna un'indirizzo da ganache } // Mapping utile per memorizzare le pratiche mapping (uint256=> Pratica) public _pratiche; uint256[] public praticheArray; event creazionePratica(uint256 ID, string nomeIncidente, string data, string comandoPoliziaMunicipale, uint256 costo); event praticaFirmata(uint256 ID, string nomeIncidente, string data, string comandoPoliziaMunicipale, uint256 costo); // Creazione nuova pratica function newPratica(uint256 _ID, string memory _nomeIncidente, string memory _data, string memory _comandoPoliziaMunicipale, uint256 _costo) public{ Pratica storage _newpratica = _pratiche[_ID]; // inizializzazione nuova pratica da creare _newpratica.indirizzoCliente = msg.sender; _newpratica.ID = _ID; _newpratica.nomeIncidente = _nomeIncidente; _newpratica.data = _data; _newpratica.comandoPoliziaMunicipale = _comandoPoliziaMunicipale; _newpratica.costo = _costo; _newpratica.firmaCount = 0; praticheArray.push(_ID); emit creazionePratica(_newpratica.ID, _nomeIncidente, _data, _comandoPoliziaMunicipale, _costo); } // funzione per firmare la pratica function firmaPratica(uint256 _ID) signOnly public { Pratica storage pratica = _pratiche[_ID]; // Controllo sull'autenticità delle firme require(address(0) != pratica.indirizzoCliente); require(msg.sender != pratica.indirizzoCliente); // Non è permesso che la stessa persona firmi più volte require(pratica.firme[msg.sender] != 1); pratica.firme[msg.sender] = 1; pratica.firmaCount++; // Controllo se la pratica è stata firmata corretamente da polziia e perito, cosi da procedere con il processo assicurativo if(pratica.firmaCount == 2) emit praticaFirmata(pratica.ID, pratica.nomeIncidente, pratica.data, pratica.comandoPoliziaMunicipale, pratica.costo); } }
assegna un'indirizzo da ganache
perito = 0x62D6f59fEf467154F6EbC924F8eC74400076a106;
5,407,811
[ 1, 345, 307, 1600, 69, 640, 11, 728, 481, 25695, 83, 5248, 314, 304, 807, 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, 3639, 1534, 11250, 273, 374, 92, 8898, 40, 26, 74, 6162, 74, 41, 74, 8749, 27, 29003, 42, 26, 41, 70, 39, 29, 3247, 42, 28, 73, 39, 5608, 24, 3784, 6669, 69, 22135, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; /** * @title TrusterLenderPool * @author Damn Vulnerable DeFi (https://damnvulnerabledefi.xyz) */ contract TrusterLenderPool is ReentrancyGuard { using Address for address; IERC20 public immutable damnValuableToken; constructor (address tokenAddress) { damnValuableToken = IERC20(tokenAddress); } function flashLoan( uint256 borrowAmount, address borrower, address target, bytes calldata data ) external nonReentrant { uint256 balanceBefore = damnValuableToken.balanceOf(address(this)); require(balanceBefore >= borrowAmount, "Not enough tokens in pool"); damnValuableToken.transfer(borrower, borrowAmount); // @audit-info : maybe if this fails, the transfer will still work, however, the borrower will not want to repay the loan. // @audit : this was indeed the issue; the attacker could call the flashLoan(0) function to send it to the target/ target.functionCall(data); // @audit : the target can be the `token` and you can call it's approve function, such that the pool will approve a transfer worth of // the entire pool's balance to the target. Without the require on line 45, the exploit could have triggered as I have initially thought // (through the use of a gimmick contract, that would simply accept the payment but not do anything with it). uint256 balanceAfter = damnValuableToken.balanceOf(address(this)); require(balanceAfter >= balanceBefore, "Flash loan hasn't been paid back"); } }
@audit-info : maybe if this fails, the transfer will still work, however, the borrower will not want to repay the loan. @audit : this was indeed the issue; the attacker could call the flashLoan(0) function to send it to the target/ @audit : the target can be the `token` and you can call it's approve function, such that the pool will approve a transfer worth of the entire pool's balance to the target. Without the require on line 45, the exploit could have triggered as I have initially thought (through the use of a gimmick contract, that would simply accept the payment but not do anything with it).
function flashLoan( uint256 borrowAmount, address borrower, address target, bytes calldata data ) external nonReentrant { uint256 balanceBefore = damnValuableToken.balanceOf(address(this)); require(balanceBefore >= borrowAmount, "Not enough tokens in pool"); damnValuableToken.transfer(borrower, borrowAmount); target.functionCall(data); uint256 balanceAfter = damnValuableToken.balanceOf(address(this)); require(balanceAfter >= balanceBefore, "Flash loan hasn't been paid back"); }
1,807,942
[ 1, 36, 17413, 17, 1376, 294, 6944, 309, 333, 6684, 16, 326, 7412, 903, 4859, 1440, 16, 14025, 16, 326, 29759, 264, 903, 486, 2545, 358, 2071, 528, 326, 28183, 18, 632, 17413, 294, 333, 1703, 316, 323, 329, 326, 5672, 31, 326, 13843, 264, 3377, 745, 326, 9563, 1504, 304, 12, 20, 13, 445, 358, 1366, 518, 358, 326, 1018, 19, 632, 17413, 294, 326, 1018, 848, 506, 326, 1375, 2316, 68, 471, 1846, 848, 745, 518, 1807, 6617, 537, 445, 16, 4123, 716, 326, 2845, 903, 6617, 537, 279, 7412, 26247, 434, 326, 7278, 2845, 1807, 11013, 358, 326, 1018, 18, 27287, 326, 2583, 603, 980, 12292, 16, 326, 15233, 305, 3377, 1240, 10861, 487, 467, 1240, 22458, 286, 83, 9540, 261, 10064, 326, 999, 434, 279, 314, 381, 81, 1200, 6835, 16, 716, 4102, 8616, 2791, 326, 5184, 1496, 486, 741, 6967, 598, 518, 2934, 2, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
[ 1, 565, 445, 9563, 1504, 304, 12, 203, 3639, 2254, 5034, 29759, 6275, 16, 203, 3639, 1758, 29759, 264, 16, 203, 3639, 1758, 1018, 16, 203, 3639, 1731, 745, 892, 501, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1661, 426, 8230, 970, 203, 565, 288, 203, 3639, 2254, 5034, 11013, 4649, 273, 302, 301, 82, 58, 700, 429, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2583, 12, 12296, 4649, 1545, 29759, 6275, 16, 315, 1248, 7304, 2430, 316, 2845, 8863, 203, 540, 203, 3639, 302, 301, 82, 58, 700, 429, 1345, 18, 13866, 12, 70, 15318, 264, 16, 29759, 6275, 1769, 203, 540, 203, 3639, 1018, 18, 915, 1477, 12, 892, 1769, 203, 203, 3639, 2254, 5034, 11013, 4436, 273, 302, 301, 82, 58, 700, 429, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2583, 12, 12296, 4436, 1545, 11013, 4649, 16, 315, 11353, 28183, 13342, 1404, 2118, 30591, 1473, 8863, 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 ]
pragma solidity ^0.4.2; // 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. import "node_modules/wealdtech-solidity/contracts/ens/ENSReverseRegister.sol"; import "node_modules/wealdtech-solidity/contracts/math/SafeMath.sol"; import "node_modules/wealdtech-solidity/contracts/auth/Permissioned.sol"; import "node_modules/wealdtech-solidity/contracts/lifecycle/Pausable.sol"; // Interesting parts of the ENS deed contract Deed { address public owner; address public previousOwner; } // Interesting parts of the ENS registry contract Registry { function owner(bytes32 _hash) public constant returns (address); } // Interesting parts of the ENS registrar contract Registrar { function transfer(bytes32 _hash, address newOwner) public; function entries(bytes32 _hash) public constant returns (uint, Deed, uint, uint, uint); } contract DomainSale is ENSReverseRegister, Pausable { using SafeMath for uint256; Registrar public registrar; mapping (string => Sale) private sales; mapping (address => uint256) private balances; // Auction parameters uint256 private constant AUCTION_DURATION = 24 hours; uint256 private constant HIGH_BID_KICKIN = 7 days; uint256 private constant NORMAL_BID_INCREASE_PERCENTAGE = 10; uint256 private constant HIGH_BID_INCREASE_PERCENTAGE = 50; // Distribution of the sale funds uint256 private constant SELLER_SALE_PERCENTAGE = 90; uint256 private constant START_REFERRER_SALE_PERCENTAGE = 5; uint256 private constant BID_REFERRER_SALE_PERCENTAGE = 5; // ENS string private constant CONTRACT_ENS = "domainsale.eth"; // Hex is namehash("eth") bytes32 private constant NAMEHASH_ETH = 0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae; struct Sale { // The lowest direct purchase price that will be accepted uint256 price; // The lowest auction bid that will be accepted uint256 reserve; // The last bid on the auction. 0 if no bid has been made uint256 lastBid; // The address of the last bider on the auction. 0 if no bid has been made address lastBidder; // The timestamp when this auction started uint256 auctionStarted; // The timestamp at which this auction ends uint256 auctionEnds; // The address of the referrer who started the sale address startReferrer; // The address of the referrer who supplied the winning bid address bidReferrer; } // // Events // // Sent when a name is offered (can occur multiple times if the seller // changes their prices) event Offer(address indexed seller, string name, uint256 price, uint256 reserve); // Sent when a bid is placed for a name event Bid(address indexed bidder, string name, uint256 bid); // Sent when a name is transferred to a new owner event Transfer(address indexed seller, address indexed buyer, string name, uint256 value); // Sent when a sale for a name is cancelled event Cancel(string name); // Sent when funds are withdrawn event Withdraw(address indexed recipient, uint256 amount); // // Modifiers // // Actions that can only be undertaken by the seller of the name. // The owner of the name is this contract, so we use the previous // owner from the deed modifier onlyNameSeller(string _name) { Deed deed; (,deed,,,) = registrar.entries(keccak256(_name)); require(deed.owner() == address(this)); require(deed.previousOwner() == msg.sender); _; } // It is possible for a name to be invalidated, in which case the // owner will be reset modifier deedValid(string _name) { address deed; (,deed,,,) = registrar.entries(keccak256(_name)); require(deed != 0); _; } // Actions that can only be undertaken if the name sale has attracted // no bids. modifier auctionNotStarted(string _name) { require(sales[_name].auctionStarted == 0); _; } // Allow if the name can be bid upon modifier canBid(string _name) { require(sales[_name].reserve != 0); _; } // Allow if the name can be purchased modifier canBuy(string _name) { require(sales[_name].price != 0); _; } /** * @dev Constructor takes the address of the ENS registry */ function DomainSale(address _registry) public ENSReverseRegister(_registry, CONTRACT_ENS) { registrar = Registrar(Registry(_registry).owner(NAMEHASH_ETH)); } // // Accessors for sales struct // /** * @dev return useful information from the sale structure in one go */ function sale(string _name) public constant returns (uint256, uint256, uint256, address, uint256, uint256) { Sale storage s = sales[_name]; return (s.price, s.reserve, s.lastBid, s.lastBidder, s.auctionStarted, s.auctionEnds); } /** * @dev a flag set if this name can be purchased through auction */ function isAuction(string _name) public constant returns (bool) { return sales[_name].reserve != 0; } /** * @dev a flag set if this name can be purchased outright */ function isBuyable(string _name) public constant returns (bool) { return sales[_name].price != 0 && sales[_name].auctionStarted == 0; } /** * @dev a flag set if the auction has started */ function auctionStarted(string _name) public constant returns (bool) { return sales[_name].lastBid != 0; } /** * @dev the time at which the auction ends */ function auctionEnds(string _name) public constant returns (uint256) { return sales[_name].auctionEnds; } /** * @dev minimumBid is the greater of the minimum bid or the last bid + 10%. * If an auction has been going longer than 7 days then it is the last * bid + 50%. */ function minimumBid(string _name) public constant returns (uint256) { Sale storage s = sales[_name]; if (s.auctionStarted == 0) { return s.reserve; } else if (s.auctionStarted.add(HIGH_BID_KICKIN) > now) { return s.lastBid.add(s.lastBid.mul(NORMAL_BID_INCREASE_PERCENTAGE).div(100)); } else { return s.lastBid.add(s.lastBid.mul(HIGH_BID_INCREASE_PERCENTAGE).div(100)); } } /** * @dev price is the instant purchase price. */ function price(string _name) public constant returns (uint256) { return sales[_name].price; } /** * @dev The balance available for withdrawal */ function balance(address addr) public constant returns (uint256) { return balances[addr]; } // // Operations // /** * @dev offer a domain for sale. * The price is the price at which a domain can be purchased directly. * The reserve is the initial lowest price for which a bid can be made. */ function offer(string _name, uint256 _price, uint256 reserve, address referrer) onlyNameSeller(_name) auctionNotStarted(_name) deedValid(_name) ifNotPaused public { require(_price == 0 || _price > reserve); require(_price != 0 || reserve != 0); Sale storage s = sales[_name]; s.reserve = reserve; s.price = _price; s.startReferrer = referrer; Offer(msg.sender, _name, _price, reserve); } /** * @dev cancel a sale for a domain. * This can only happen if there have been no bids for the name. */ function cancel(string _name) onlyNameSeller(_name) auctionNotStarted(_name) deedValid(_name) ifNotPaused public { // Finished with the sale information delete sales[_name]; registrar.transfer(keccak256(_name), msg.sender); Cancel(_name); } /** * @dev buy a domain directly */ function buy(string _name, address bidReferrer) canBuy(_name) deedValid(_name) ifNotPaused public payable { Sale storage s = sales[_name]; require(msg.value >= s.price); require(s.auctionStarted == 0); // Obtain the previous owner from the deed Deed deed; (,deed,,,) = registrar.entries(keccak256(_name)); address previousOwner = deed.previousOwner(); // Transfer the name registrar.transfer(keccak256(_name), msg.sender); Transfer(previousOwner, msg.sender, _name, msg.value); // Distribute funds to referrers distributeFunds(msg.value, previousOwner, s.startReferrer, bidReferrer); // Finished with the sale information delete sales[_name]; // As we're here, return any funds that the sender is owed withdraw(); } /** * @dev bid for a domain */ function bid(string _name, address bidReferrer) canBid(_name) deedValid(_name) ifNotPaused public payable { require(msg.value >= minimumBid(_name)); Sale storage s = sales[_name]; require(s.auctionStarted == 0 || now < s.auctionEnds); if (s.auctionStarted == 0) { // First bid; set the auction start s.auctionStarted = now; } else { // Update the balance for the outbid bidder balances[s.lastBidder] = balances[s.lastBidder].add(s.lastBid); } s.lastBidder = msg.sender; s.lastBid = msg.value; s.auctionEnds = now.add(AUCTION_DURATION); s.bidReferrer = bidReferrer; Bid(msg.sender, _name, msg.value); // As we're here, return any funds that the sender is owed withdraw(); } /** * @dev finish an auction */ function finish(string _name) deedValid(_name) ifNotPaused public { Sale storage s = sales[_name]; require(now > s.auctionEnds); // Obtain the previous owner from the deed Deed deed; (,deed,,,) = registrar.entries(keccak256(_name)); address previousOwner = deed.previousOwner(); registrar.transfer(keccak256(_name), s.lastBidder); Transfer(previousOwner, s.lastBidder, _name, s.lastBid); // Distribute funds to referrers distributeFunds(s.lastBid, previousOwner, s.startReferrer, s.bidReferrer); // Finished with the sale information delete sales[_name]; // As we're here, return any funds that the sender is owed withdraw(); } /** * @dev withdraw any owned balance */ function withdraw() ifNotPaused public { uint256 amount = balances[msg.sender]; if (amount > 0) { balances[msg.sender] = 0; msg.sender.transfer(amount); Withdraw(msg.sender, amount); } } /** * @dev Invalidate an auction if the deed is no longer active */ function invalidate(string _name) ifNotPaused public { // Ensure the deed has been invalidated address deed; (,deed,,,) = registrar.entries(keccak256(_name)); require(deed == 0); Sale storage s = sales[_name]; // Update the balance for the winning bidder balances[s.lastBidder] = balances[s.lastBidder].add(s.lastBid); // Finished with the sale information delete sales[_name]; // Cancel the auction Cancel(_name); // As we're here, return any funds that the sender is owed withdraw(); } // // Internal functions // /** * @dev Distribute funds for a sale to the relevant parties */ function distributeFunds(uint256 amount, address seller, address startReferrer, address bidReferrer) internal { uint256 startReferrerFunds = amount.mul(START_REFERRER_SALE_PERCENTAGE).div(100); balances[startReferrer] = balances[startReferrer].add(startReferrerFunds); uint256 bidReferrerFunds = amount.mul(BID_REFERRER_SALE_PERCENTAGE).div(100); balances[bidReferrer] = balances[bidReferrer].add(bidReferrerFunds); uint256 sellerFunds = amount.sub(startReferrerFunds).sub(bidReferrerFunds); balances[seller] = balances[seller].add(sellerFunds); } }
* @dev a flag set if this name can be purchased through auction/
function isAuction(string _name) public constant returns (bool) { return sales[_name].reserve != 0; }
6,352,971
[ 1, 69, 2982, 444, 309, 333, 508, 848, 506, 5405, 343, 8905, 3059, 279, 4062, 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, 565, 445, 25997, 4062, 12, 1080, 389, 529, 13, 1071, 5381, 1135, 261, 6430, 13, 288, 203, 3639, 327, 272, 5408, 63, 67, 529, 8009, 455, 6527, 480, 374, 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 ]
./full_match/137/0x75E9314BCb751868cEE385Bb24bFe0c3d4a269D3/sources/contracts/token.sol
Contract Address for crowdsale feature
_mint(address(this), 11800000000 * sonbola);
4,754,908
[ 1, 8924, 5267, 364, 276, 492, 2377, 5349, 2572, 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, 3639, 389, 81, 474, 12, 2867, 12, 2211, 3631, 225, 404, 2643, 12648, 380, 18882, 31697, 69, 1769, 377, 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 ]
// Dependency file: @openzeppelin/contracts/utils/Address.sol // 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); } 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); } } } } // Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol // pragma solidity >=0.6.0 <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 `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); } // Dependency file: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol // pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // Dependency file: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol // pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // Dependency file: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol // pragma solidity >=0.6.2; // import '/Users/alexsoong/Source/set-protocol/index-coop-contracts/node_modules/@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( 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 swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // Dependency file: @openzeppelin/contracts/math/Math.sol // pragma solidity >=0.6.0 <0.8.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); } } // Dependency file: @openzeppelin/contracts/math/SafeMath.sol // 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, 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; } } // Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol // pragma solidity >=0.6.0 <0.8.0; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts/utils/Address.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 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"); } } } // Dependency file: @openzeppelin/contracts/utils/ReentrancyGuard.sol // pragma solidity >=0.6.0 <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 () internal { _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 make 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; } } // Dependency file: contracts/interfaces/ISetToken.sol // pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external; function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external; function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns(int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256); function getComponents() external view returns(address[] memory); function getExternalPositionModules(address _component) external view returns(address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory); function isExternalPositionModule(address _component, address _module) external view returns(bool); function isComponent(address _component) external view returns(bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns(int256); function isInitializedModule(address _module) external view returns(bool); function isPendingModule(address _module) external view returns(bool); function isLocked() external view returns (bool); } // Dependency file: contracts/interfaces/IBasicIssuanceModule.sol /* Copyright 2020 Set Labs Inc. 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.6.10; // import { ISetToken } from "contracts/interfaces/ISetToken.sol"; interface IBasicIssuanceModule { function getRequiredComponentUnitsForIssue( ISetToken _setToken, uint256 _quantity ) external returns(address[] memory, uint256[] memory); function issue(ISetToken _setToken, uint256 _quantity, address _to) external; function redeem(ISetToken _token, uint256 _quantity, address _to) external; } // Dependency file: contracts/interfaces/IController.sol /* Copyright 2020 Set Labs Inc. 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.6.10; interface IController { function addSet(address _setToken) external; function feeRecipient() external view returns(address); function getModuleFee(address _module, uint256 _feeType) external view returns(uint256); function isModule(address _module) external view returns(bool); function isSet(address _setToken) external view returns(bool); function isSystemContract(address _contractAddress) external view returns (bool); function resourceId(uint256 _id) external view returns(address); } // Dependency file: contracts/interfaces/IWETH.sol // pragma solidity >=0.6.10; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // Dependency file: @openzeppelin/contracts/math/SignedSafeMath.sol // pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // 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; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // Dependency file: contracts/lib/PreciseUnitMath.sol /* Copyright 2020 Set Labs Inc. 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.6.10; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 constant internal PRECISE_UNIT = 10 ** 18; int256 constant internal PRECISE_UNIT_INT = 10 ** 18; // Max unsigned integer value uint256 constant internal MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 constant internal MAX_INT_256 = type(int256).max; int256 constant internal MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0, "Value must be positive"); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } } // Dependency file: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol // pragma solidity >=0.5.0; 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; } // Dependency file: external/contracts/UniSushiV2Library.sol // pragma solidity >=0.5.0; // import '/Users/alexsoong/Source/set-protocol/index-coop-contracts/node_modules/@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; library UniSushiV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // fetches and sorts the reserves for a pair function getReserves(address pair, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pair).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // Root file: contracts/exchangeIssuance/ExchangeIssuance.sol /* Copyright 2021 Index Cooperative 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.6.10; // import { Address } from "@openzeppelin/contracts/utils/Address.sol"; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { IUniswapV2Factory } from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; // import { IUniswapV2Router02 } from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; // import { Math } from "@openzeppelin/contracts/math/Math.sol"; // import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; // import { IBasicIssuanceModule } from "contracts/interfaces/IBasicIssuanceModule.sol"; // import { IController } from "contracts/interfaces/IController.sol"; // import { ISetToken } from "contracts/interfaces/ISetToken.sol"; // import { IWETH } from "contracts/interfaces/IWETH.sol"; // import { PreciseUnitMath } from "contracts/lib/PreciseUnitMath.sol"; // import { UniSushiV2Library } from "external/contracts/UniSushiV2Library.sol"; /** * @title ExchangeIssuance * @author Index Coop * * Contract for issuing and redeeming any SetToken using ETH or an ERC20 as the paying/receiving currency. * All swaps are done using the best price found on Uniswap or Sushiswap. * */ contract ExchangeIssuance is ReentrancyGuard { using Address for address payable; using SafeMath for uint256; using PreciseUnitMath for uint256; using SafeERC20 for IERC20; using SafeERC20 for ISetToken; /* ============ Enums ============ */ enum Exchange { Uniswap, Sushiswap, None } /* ============ Constants ============= */ uint256 constant private MAX_UINT96 = 2**96 - 1; address constant public ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /* ============ State Variables ============ */ address public WETH; IUniswapV2Router02 public uniRouter; IUniswapV2Router02 public sushiRouter; address public immutable uniFactory; address public immutable sushiFactory; IController public immutable setController; IBasicIssuanceModule public immutable basicIssuanceModule; /* ============ Events ============ */ event ExchangeIssue( address indexed _recipient, // The recipient address of the issued SetTokens ISetToken indexed _setToken, // The issued SetToken IERC20 indexed _inputToken, // The address of the input asset(ERC20/ETH) used to issue the SetTokens uint256 _amountInputToken, // The amount of input tokens used for issuance uint256 _amountSetIssued // The amount of SetTokens received by the recipient ); event ExchangeRedeem( address indexed _recipient, // The recipient address which redeemed the SetTokens ISetToken indexed _setToken, // The redeemed SetToken IERC20 indexed _outputToken, // The address of output asset(ERC20/ETH) received by the recipient uint256 _amountSetRedeemed, // The amount of SetTokens redeemed for output tokens uint256 _amountOutputToken // The amount of output tokens received by the recipient ); event Refund( address indexed _recipient, // The recipient address which redeemed the SetTokens uint256 _refundAmount // The amount of ETH redunded to the recipient ); /* ============ Modifiers ============ */ modifier isSetToken(ISetToken _setToken) { require(setController.isSet(address(_setToken)), "ExchangeIssuance: INVALID SET"); _; } /* ============ Constructor ============ */ constructor( address _weth, address _uniFactory, IUniswapV2Router02 _uniRouter, address _sushiFactory, IUniswapV2Router02 _sushiRouter, IController _setController, IBasicIssuanceModule _basicIssuanceModule ) public { uniFactory = _uniFactory; uniRouter = _uniRouter; sushiFactory = _sushiFactory; sushiRouter = _sushiRouter; setController = _setController; basicIssuanceModule = _basicIssuanceModule; WETH = _weth; IERC20(WETH).safeApprove(address(uniRouter), PreciseUnitMath.maxUint256()); IERC20(WETH).safeApprove(address(sushiRouter), PreciseUnitMath.maxUint256()); } /* ============ Public Functions ============ */ /** * Runs all the necessary approval functions required for a given ERC20 token. * This function can be called when a new token is added to a SetToken during a * rebalance. * * @param _token Address of the token which needs approval */ function approveToken(IERC20 _token) public { _safeApprove(_token, address(uniRouter), MAX_UINT96); _safeApprove(_token, address(sushiRouter), MAX_UINT96); _safeApprove(_token, address(basicIssuanceModule), MAX_UINT96); } /* ============ External Functions ============ */ receive() external payable { // required for weth.withdraw() to work properly require(msg.sender == WETH, "ExchangeIssuance: Direct deposits not allowed"); } /** * Runs all the necessary approval functions required for a list of ERC20 tokens. * * @param _tokens Addresses of the tokens which need approval */ function approveTokens(IERC20[] calldata _tokens) external { for (uint256 i = 0; i < _tokens.length; i++) { approveToken(_tokens[i]); } } /** * Runs all the necessary approval functions required before issuing * or redeeming a SetToken. This function need to be called only once before the first time * this smart contract is used on any particular SetToken. * * @param _setToken Address of the SetToken being initialized */ function approveSetToken(ISetToken _setToken) isSetToken(_setToken) external { address[] memory components = _setToken.getComponents(); for (uint256 i = 0; i < components.length; i++) { // Check that the component does not have external positions require( _setToken.getExternalPositionModules(components[i]).length == 0, "ExchangeIssuance: EXTERNAL_POSITIONS_NOT_ALLOWED" ); approveToken(IERC20(components[i])); } } /** * Issues SetTokens for an exact amount of input ERC20 tokens. * The ERC20 token must be approved by the sender to this contract. * * @param _setToken Address of the SetToken being issued * @param _inputToken Address of input token * @param _amountInput Amount of the input token / ether to spend * @param _minSetReceive Minimum amount of SetTokens to receive. Prevents unnecessary slippage. * * @return setTokenAmount Amount of SetTokens issued to the caller */ function issueSetForExactToken( ISetToken _setToken, IERC20 _inputToken, uint256 _amountInput, uint256 _minSetReceive ) isSetToken(_setToken) external nonReentrant returns (uint256) { require(_amountInput > 0, "ExchangeIssuance: INVALID INPUTS"); _inputToken.safeTransferFrom(msg.sender, address(this), _amountInput); uint256 amountEth = address(_inputToken) == WETH ? _amountInput : _swapTokenForWETH(_inputToken, _amountInput); uint256 setTokenAmount = _issueSetForExactWETH(_setToken, _minSetReceive, amountEth); emit ExchangeIssue(msg.sender, _setToken, _inputToken, _amountInput, setTokenAmount); return setTokenAmount; } /** * Issues SetTokens for an exact amount of input ether. * * @param _setToken Address of the SetToken to be issued * @param _minSetReceive Minimum amount of SetTokens to receive. Prevents unnecessary slippage. * * @return setTokenAmount Amount of SetTokens issued to the caller */ function issueSetForExactETH( ISetToken _setToken, uint256 _minSetReceive ) isSetToken(_setToken) external payable nonReentrant returns(uint256) { require(msg.value > 0, "ExchangeIssuance: INVALID INPUTS"); IWETH(WETH).deposit{value: msg.value}(); uint256 setTokenAmount = _issueSetForExactWETH(_setToken, _minSetReceive, msg.value); emit ExchangeIssue(msg.sender, _setToken, IERC20(ETH_ADDRESS), msg.value, setTokenAmount); return setTokenAmount; } /** * Issues an exact amount of SetTokens for given amount of input ERC20 tokens. * The excess amount of tokens is returned in an equivalent amount of ether. * * @param _setToken Address of the SetToken to be issued * @param _inputToken Address of the input token * @param _amountSetToken Amount of SetTokens to issue * @param _maxAmountInputToken Maximum amount of input tokens to be used to issue SetTokens. The unused * input tokens are returned as ether. * * @return amountEthReturn Amount of ether returned to the caller */ function issueExactSetFromToken( ISetToken _setToken, IERC20 _inputToken, uint256 _amountSetToken, uint256 _maxAmountInputToken ) isSetToken(_setToken) external nonReentrant returns (uint256) { require(_amountSetToken > 0 && _maxAmountInputToken > 0, "ExchangeIssuance: INVALID INPUTS"); _inputToken.safeTransferFrom(msg.sender, address(this), _maxAmountInputToken); uint256 initETHAmount = address(_inputToken) == WETH ? _maxAmountInputToken : _swapTokenForWETH(_inputToken, _maxAmountInputToken); uint256 amountEthSpent = _issueExactSetFromWETH(_setToken, _amountSetToken, initETHAmount); uint256 amountEthReturn = initETHAmount.sub(amountEthSpent); if (amountEthReturn > 0) { IWETH(WETH).withdraw(amountEthReturn); (payable(msg.sender)).sendValue(amountEthReturn); } emit Refund(msg.sender, amountEthReturn); emit ExchangeIssue(msg.sender, _setToken, _inputToken, _maxAmountInputToken, _amountSetToken); return amountEthReturn; } /** * Issues an exact amount of SetTokens using a given amount of ether. * The excess ether is returned back. * * @param _setToken Address of the SetToken being issued * @param _amountSetToken Amount of SetTokens to issue * * @return amountEthReturn Amount of ether returned to the caller */ function issueExactSetFromETH( ISetToken _setToken, uint256 _amountSetToken ) isSetToken(_setToken) external payable nonReentrant returns (uint256) { require(msg.value > 0 && _amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS"); IWETH(WETH).deposit{value: msg.value}(); uint256 amountEth = _issueExactSetFromWETH(_setToken, _amountSetToken, msg.value); uint256 amountEthReturn = msg.value.sub(amountEth); if (amountEthReturn > 0) { IWETH(WETH).withdraw(amountEthReturn); (payable(msg.sender)).sendValue(amountEthReturn); } emit Refund(msg.sender, amountEthReturn); emit ExchangeIssue(msg.sender, _setToken, IERC20(ETH_ADDRESS), amountEth, _amountSetToken); return amountEthReturn; } /** * Redeems an exact amount of SetTokens for an ERC20 token. * The SetToken must be approved by the sender to this contract. * * @param _setToken Address of the SetToken being redeemed * @param _outputToken Address of output token * @param _amountSetToken Amount SetTokens to redeem * @param _minOutputReceive Minimum amount of output token to receive * * @return outputAmount Amount of output tokens sent to the caller */ function redeemExactSetForToken( ISetToken _setToken, IERC20 _outputToken, uint256 _amountSetToken, uint256 _minOutputReceive ) isSetToken(_setToken) external nonReentrant returns (uint256) { require(_amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS"); address[] memory components = _setToken.getComponents(); ( uint256 totalEth, uint256[] memory amountComponents, Exchange[] memory exchanges ) = _getAmountETHForRedemption(_setToken, components, _amountSetToken); uint256 outputAmount; if (address(_outputToken) == WETH) { require(totalEth > _minOutputReceive, "ExchangeIssuance: INSUFFICIENT_OUTPUT_AMOUNT"); _redeemExactSet(_setToken, _amountSetToken); outputAmount = _liquidateComponentsForWETH(components, amountComponents, exchanges); } else { (uint256 totalOutput, Exchange outTokenExchange, ) = _getMaxTokenForExactToken(totalEth, address(WETH), address(_outputToken)); require(totalOutput > _minOutputReceive, "ExchangeIssuance: INSUFFICIENT_OUTPUT_AMOUNT"); _redeemExactSet(_setToken, _amountSetToken); uint256 outputEth = _liquidateComponentsForWETH(components, amountComponents, exchanges); outputAmount = _swapExactTokensForTokens(outTokenExchange, WETH, address(_outputToken), outputEth); } _outputToken.safeTransfer(msg.sender, outputAmount); emit ExchangeRedeem(msg.sender, _setToken, _outputToken, _amountSetToken, outputAmount); return outputAmount; } /** * Redeems an exact amount of SetTokens for ETH. * The SetToken must be approved by the sender to this contract. * * @param _setToken Address of the SetToken to be redeemed * @param _amountSetToken Amount of SetTokens to redeem * @param _minEthOut Minimum amount of ETH to receive * * @return amountEthOut Amount of ether sent to the caller */ function redeemExactSetForETH( ISetToken _setToken, uint256 _amountSetToken, uint256 _minEthOut ) isSetToken(_setToken) external nonReentrant returns (uint256) { require(_amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS"); address[] memory components = _setToken.getComponents(); ( uint256 totalEth, uint256[] memory amountComponents, Exchange[] memory exchanges ) = _getAmountETHForRedemption(_setToken, components, _amountSetToken); require(totalEth > _minEthOut, "ExchangeIssuance: INSUFFICIENT_OUTPUT_AMOUNT"); _redeemExactSet(_setToken, _amountSetToken); uint256 amountEthOut = _liquidateComponentsForWETH(components, amountComponents, exchanges); IWETH(WETH).withdraw(amountEthOut); (payable(msg.sender)).sendValue(amountEthOut); emit ExchangeRedeem(msg.sender, _setToken, IERC20(ETH_ADDRESS), _amountSetToken, amountEthOut); return amountEthOut; } /** * Returns an estimated amount of SetToken that can be issued given an amount of input ERC20 token. * * @param _setToken Address of the SetToken being issued * @param _amountInput Amount of the input token to spend * @param _inputToken Address of input token. * * @return Estimated amount of SetTokens that will be received */ function getEstimatedIssueSetAmount( ISetToken _setToken, IERC20 _inputToken, uint256 _amountInput ) isSetToken(_setToken) external view returns (uint256) { require(_amountInput > 0, "ExchangeIssuance: INVALID INPUTS"); uint256 amountEth; if (address(_inputToken) != WETH) { // get max amount of WETH for the `_amountInput` amount of input tokens (amountEth, , ) = _getMaxTokenForExactToken(_amountInput, address(_inputToken), WETH); } else { amountEth = _amountInput; } address[] memory components = _setToken.getComponents(); (uint256 setIssueAmount, , ) = _getSetIssueAmountForETH(_setToken, components, amountEth); return setIssueAmount; } /** * Returns the amount of input ERC20 tokens required to issue an exact amount of SetTokens. * * @param _setToken Address of the SetToken being issued * @param _amountSetToken Amount of SetTokens to issue * * @return Amount of tokens needed to issue specified amount of SetTokens */ function getAmountInToIssueExactSet( ISetToken _setToken, IERC20 _inputToken, uint256 _amountSetToken ) isSetToken(_setToken) external view returns(uint256) { require(_amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS"); address[] memory components = _setToken.getComponents(); (uint256 totalEth, , , , ) = _getAmountETHForIssuance(_setToken, components, _amountSetToken); if (address(_inputToken) == WETH) { return totalEth; } (uint256 tokenAmount, , ) = _getMinTokenForExactToken(totalEth, address(_inputToken), address(WETH)); return tokenAmount; } /** * Returns amount of output ERC20 tokens received upon redeeming a given amount of SetToken. * * @param _setToken Address of SetToken to be redeemed * @param _amountSetToken Amount of SetToken to be redeemed * @param _outputToken Address of output token * * @return Estimated amount of ether/erc20 that will be received */ function getAmountOutOnRedeemSet( ISetToken _setToken, address _outputToken, uint256 _amountSetToken ) isSetToken(_setToken) external view returns (uint256) { require(_amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS"); address[] memory components = _setToken.getComponents(); (uint256 totalEth, , ) = _getAmountETHForRedemption(_setToken, components, _amountSetToken); if (_outputToken == WETH) { return totalEth; } // get maximum amount of tokens for totalEth amount of ETH (uint256 tokenAmount, , ) = _getMaxTokenForExactToken(totalEth, WETH, _outputToken); return tokenAmount; } /* ============ Internal Functions ============ */ /** * Sets a max approval limit for an ERC20 token, provided the current allowance * is less than the required allownce. * * @param _token Token to approve * @param _spender Spender address to approve */ function _safeApprove(IERC20 _token, address _spender, uint256 _requiredAllowance) internal { uint256 allowance = _token.allowance(address(this), _spender); if (allowance < _requiredAllowance) { _token.safeIncreaseAllowance(_spender, MAX_UINT96 - allowance); } } /** * Issues SetTokens for an exact amount of input WETH. * * @param _setToken Address of the SetToken being issued * @param _minSetReceive Minimum amount of index to receive * @param _totalEthAmount Total amount of WETH to be used to purchase the SetToken components * * @return setTokenAmount Amount of SetTokens issued */ function _issueSetForExactWETH(ISetToken _setToken, uint256 _minSetReceive, uint256 _totalEthAmount) internal returns (uint256) { address[] memory components = _setToken.getComponents(); ( uint256 setIssueAmount, uint256[] memory amountEthIn, Exchange[] memory exchanges ) = _getSetIssueAmountForETH(_setToken, components, _totalEthAmount); require(setIssueAmount > _minSetReceive, "ExchangeIssuance: INSUFFICIENT_OUTPUT_AMOUNT"); for (uint256 i = 0; i < components.length; i++) { _swapExactTokensForTokens(exchanges[i], WETH, components[i], amountEthIn[i]); } basicIssuanceModule.issue(_setToken, setIssueAmount, msg.sender); return setIssueAmount; } /** * Issues an exact amount of SetTokens using WETH. * Acquires SetToken components at the best price accross uniswap and sushiswap. * Uses the acquired components to issue the SetTokens. * * @param _setToken Address of the SetToken being issued * @param _amountSetToken Amount of SetTokens to be issued * @param _maxEther Max amount of ether that can be used to acquire the SetToken components * * @return totalEth Total amount of ether used to acquire the SetToken components */ function _issueExactSetFromWETH(ISetToken _setToken, uint256 _amountSetToken, uint256 _maxEther) internal returns (uint256) { address[] memory components = _setToken.getComponents(); ( uint256 sumEth, , Exchange[] memory exchanges, uint256[] memory amountComponents, ) = _getAmountETHForIssuance(_setToken, components, _amountSetToken); require(sumEth <= _maxEther, "ExchangeIssuance: INSUFFICIENT_INPUT_AMOUNT"); uint256 totalEth = 0; for (uint256 i = 0; i < components.length; i++) { uint256 amountEth = _swapTokensForExactTokens(exchanges[i], WETH, components[i], amountComponents[i]); totalEth = totalEth.add(amountEth); } basicIssuanceModule.issue(_setToken, _amountSetToken, msg.sender); return totalEth; } /** * Redeems a given amount of SetToken. * * @param _setToken Address of the SetToken to be redeemed * @param _amount Amount of SetToken to be redeemed */ function _redeemExactSet(ISetToken _setToken, uint256 _amount) internal returns (uint256) { _setToken.safeTransferFrom(msg.sender, address(this), _amount); basicIssuanceModule.redeem(_setToken, _amount, address(this)); } /** * Liquidates a given list of SetToken components for WETH. * * @param _components An array containing the address of SetToken components * @param _amountComponents An array containing the amount of each SetToken component * @param _exchanges An array containing the exchange on which to liquidate the SetToken component * * @return Total amount of WETH received after liquidating all SetToken components */ function _liquidateComponentsForWETH(address[] memory _components, uint256[] memory _amountComponents, Exchange[] memory _exchanges) internal returns (uint256) { uint256 sumEth = 0; for (uint256 i = 0; i < _components.length; i++) { sumEth = _exchanges[i] == Exchange.None ? sumEth.add(_amountComponents[i]) : sumEth.add(_swapExactTokensForTokens(_exchanges[i], _components[i], WETH, _amountComponents[i])); } return sumEth; } /** * Gets the total amount of ether required for purchasing each component in a SetToken, * to enable the issuance of a given amount of SetTokens. * * @param _setToken Address of the SetToken to be issued * @param _components An array containing the addresses of the SetToken components * @param _amountSetToken Amount of SetToken to be issued * * @return sumEth The total amount of Ether reuired to issue the set * @return amountEthIn An array containing the amount of ether to purchase each component of the SetToken * @return exchanges An array containing the exchange on which to perform the purchase * @return amountComponents An array containing the amount of each SetToken component required for issuing the given * amount of SetToken * @return pairAddresses An array containing the pair addresses of ETH/component exchange pool */ function _getAmountETHForIssuance(ISetToken _setToken, address[] memory _components, uint256 _amountSetToken) internal view returns ( uint256 sumEth, uint256[] memory amountEthIn, Exchange[] memory exchanges, uint256[] memory amountComponents, address[] memory pairAddresses ) { sumEth = 0; amountEthIn = new uint256[](_components.length); amountComponents = new uint256[](_components.length); exchanges = new Exchange[](_components.length); pairAddresses = new address[](_components.length); for (uint256 i = 0; i < _components.length; i++) { // Check that the component does not have external positions require( _setToken.getExternalPositionModules(_components[i]).length == 0, "ExchangeIssuance: EXTERNAL_POSITIONS_NOT_ALLOWED" ); // Get minimum amount of ETH to be spent to acquire the required amount of SetToken component uint256 unit = uint256(_setToken.getDefaultPositionRealUnit(_components[i])); amountComponents[i] = uint256(unit).preciseMulCeil(_amountSetToken); (amountEthIn[i], exchanges[i], pairAddresses[i]) = _getMinTokenForExactToken(amountComponents[i], WETH, _components[i]); sumEth = sumEth.add(amountEthIn[i]); } return (sumEth, amountEthIn, exchanges, amountComponents, pairAddresses); } /** * Gets the total amount of ether returned from liquidating each component in a SetToken. * * @param _setToken Address of the SetToken to be redeemed * @param _components An array containing the addresses of the SetToken components * @param _amountSetToken Amount of SetToken to be redeemed * * @return sumEth The total amount of Ether that would be obtained from liquidating the SetTokens * @return amountComponents An array containing the amount of SetToken component to be liquidated * @return exchanges An array containing the exchange on which to liquidate the SetToken components */ function _getAmountETHForRedemption(ISetToken _setToken, address[] memory _components, uint256 _amountSetToken) internal view returns (uint256, uint256[] memory, Exchange[] memory) { uint256 sumEth = 0; uint256 amountEth = 0; uint256[] memory amountComponents = new uint256[](_components.length); Exchange[] memory exchanges = new Exchange[](_components.length); for (uint256 i = 0; i < _components.length; i++) { // Check that the component does not have external positions require( _setToken.getExternalPositionModules(_components[i]).length == 0, "ExchangeIssuance: EXTERNAL_POSITIONS_NOT_ALLOWED" ); uint256 unit = uint256(_setToken.getDefaultPositionRealUnit(_components[i])); amountComponents[i] = unit.preciseMul(_amountSetToken); // get maximum amount of ETH received for a given amount of SetToken component (amountEth, exchanges[i], ) = _getMaxTokenForExactToken(amountComponents[i], _components[i], WETH); sumEth = sumEth.add(amountEth); } return (sumEth, amountComponents, exchanges); } /** * Returns an estimated amount of SetToken that can be issued given an amount of input ERC20 token. * * @param _setToken Address of the SetToken to be issued * @param _components An array containing the addresses of the SetToken components * @param _amountEth Total amount of ether available for the purchase of SetToken components * * @return setIssueAmount The max amount of SetTokens that can be issued * @return amountEthIn An array containing the amount ether required to purchase each SetToken component * @return exchanges An array containing the exchange on which to purchase the SetToken components */ function _getSetIssueAmountForETH(ISetToken _setToken, address[] memory _components, uint256 _amountEth) internal view returns (uint256 setIssueAmount, uint256[] memory amountEthIn, Exchange[] memory exchanges) { uint256 sumEth; uint256[] memory unitAmountEthIn; uint256[] memory unitAmountComponents; address[] memory pairAddresses; ( sumEth, unitAmountEthIn, exchanges, unitAmountComponents, pairAddresses ) = _getAmountETHForIssuance(_setToken, _components, PreciseUnitMath.preciseUnit()); setIssueAmount = PreciseUnitMath.maxUint256(); amountEthIn = new uint256[](_components.length); for (uint256 i = 0; i < _components.length; i++) { amountEthIn[i] = unitAmountEthIn[i].mul(_amountEth).div(sumEth); uint256 amountComponent; if (exchanges[i] == Exchange.None) { amountComponent = amountEthIn[i]; } else { (uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(pairAddresses[i], WETH, _components[i]); amountComponent = UniSushiV2Library.getAmountOut(amountEthIn[i], reserveIn, reserveOut); } setIssueAmount = Math.min(amountComponent.preciseDiv(unitAmountComponents[i]), setIssueAmount); } return (setIssueAmount, amountEthIn, exchanges); } /** * Swaps a given amount of an ERC20 token for WETH for the best price on Uniswap/Sushiswap. * * @param _token Address of the ERC20 token to be swapped for WETH * @param _amount Amount of ERC20 token to be swapped * * @return Amount of WETH received after the swap */ function _swapTokenForWETH(IERC20 _token, uint256 _amount) internal returns (uint256) { (, Exchange exchange, ) = _getMaxTokenForExactToken(_amount, address(_token), WETH); IUniswapV2Router02 router = _getRouter(exchange); _safeApprove(_token, address(router), _amount); return _swapExactTokensForTokens(exchange, address(_token), WETH, _amount); } /** * Swap exact tokens for another token on a given DEX. * * @param _exchange The exchange on which to peform the swap * @param _tokenIn The address of the input token * @param _tokenOut The address of the output token * @param _amountIn The amount of input token to be spent * * @return The amount of output tokens */ function _swapExactTokensForTokens(Exchange _exchange, address _tokenIn, address _tokenOut, uint256 _amountIn) internal returns (uint256) { if (_tokenIn == _tokenOut) { return _amountIn; } address[] memory path = new address[](2); path[0] = _tokenIn; path[1] = _tokenOut; return _getRouter(_exchange).swapExactTokensForTokens(_amountIn, 0, path, address(this), block.timestamp)[1]; } /** * Swap tokens for exact amount of output tokens on a given DEX. * * @param _exchange The exchange on which to peform the swap * @param _tokenIn The address of the input token * @param _tokenOut The address of the output token * @param _amountOut The amount of output token required * * @return The amount of input tokens spent */ function _swapTokensForExactTokens(Exchange _exchange, address _tokenIn, address _tokenOut, uint256 _amountOut) internal returns (uint256) { if (_tokenIn == _tokenOut) { return _amountOut; } address[] memory path = new address[](2); path[0] = _tokenIn; path[1] = _tokenOut; return _getRouter(_exchange).swapTokensForExactTokens(_amountOut, PreciseUnitMath.maxUint256(), path, address(this), block.timestamp)[0]; } /** * Compares the amount of token required for an exact amount of another token across both exchanges, * and returns the min amount. * * @param _amountOut The amount of output token * @param _tokenA The address of tokenA * @param _tokenB The address of tokenB * * @return The min amount of tokenA required across both exchanges * @return The Exchange on which minimum amount of tokenA is required * @return The pair address of the uniswap/sushiswap pool containing _tokenA and _tokenB */ function _getMinTokenForExactToken(uint256 _amountOut, address _tokenA, address _tokenB) internal view returns (uint256, Exchange, address) { if (_tokenA == _tokenB) { return (_amountOut, Exchange.None, ETH_ADDRESS); } uint256 maxIn = PreciseUnitMath.maxUint256() ; uint256 uniTokenIn = maxIn; uint256 sushiTokenIn = maxIn; address uniswapPair = _getPair(uniFactory, _tokenA, _tokenB); if (uniswapPair != address(0)) { (uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(uniswapPair, _tokenA, _tokenB); // Prevent subtraction overflow by making sure pool reserves are greater than swap amount if (reserveOut > _amountOut) { uniTokenIn = UniSushiV2Library.getAmountIn(_amountOut, reserveIn, reserveOut); } } address sushiswapPair = _getPair(sushiFactory, _tokenA, _tokenB); if (sushiswapPair != address(0)) { (uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(sushiswapPair, _tokenA, _tokenB); // Prevent subtraction overflow by making sure pool reserves are greater than swap amount if (reserveOut > _amountOut) { sushiTokenIn = UniSushiV2Library.getAmountIn(_amountOut, reserveIn, reserveOut); } } // Fails if both the values are maxIn require(!(uniTokenIn == maxIn && sushiTokenIn == maxIn), "ExchangeIssuance: ILLIQUID_SET_COMPONENT"); return (uniTokenIn <= sushiTokenIn) ? (uniTokenIn, Exchange.Uniswap, uniswapPair) : (sushiTokenIn, Exchange.Sushiswap, sushiswapPair); } /** * Compares the amount of token received for an exact amount of another token across both exchanges, * and returns the max amount. * * @param _amountIn The amount of input token * @param _tokenA The address of tokenA * @param _tokenB The address of tokenB * * @return The max amount of tokens that can be received across both exchanges * @return The Exchange on which maximum amount of token can be received * @return The pair address of the uniswap/sushiswap pool containing _tokenA and _tokenB */ function _getMaxTokenForExactToken(uint256 _amountIn, address _tokenA, address _tokenB) internal view returns (uint256, Exchange, address) { if (_tokenA == _tokenB) { return (_amountIn, Exchange.None, ETH_ADDRESS); } uint256 uniTokenOut = 0; uint256 sushiTokenOut = 0; address uniswapPair = _getPair(uniFactory, _tokenA, _tokenB); if(uniswapPair != address(0)) { (uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(uniswapPair, _tokenA, _tokenB); uniTokenOut = UniSushiV2Library.getAmountOut(_amountIn, reserveIn, reserveOut); } address sushiswapPair = _getPair(sushiFactory, _tokenA, _tokenB); if(sushiswapPair != address(0)) { (uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(sushiswapPair, _tokenA, _tokenB); sushiTokenOut = UniSushiV2Library.getAmountOut(_amountIn, reserveIn, reserveOut); } // Fails if both the values are 0 require(!(uniTokenOut == 0 && sushiTokenOut == 0), "ExchangeIssuance: ILLIQUID_SET_COMPONENT"); return (uniTokenOut >= sushiTokenOut) ? (uniTokenOut, Exchange.Uniswap, uniswapPair) : (sushiTokenOut, Exchange.Sushiswap, sushiswapPair); } /** * Returns the pair address for on a given DEX. * * @param _factory The factory to address * @param _tokenA The address of tokenA * @param _tokenB The address of tokenB * * @return The pair address (Note: address(0) is returned by default if the pair is not available on that DEX) */ function _getPair(address _factory, address _tokenA, address _tokenB) internal view returns (address) { return IUniswapV2Factory(_factory).getPair(_tokenA, _tokenB); } /** * Returns the router address of a given exchange. * * @param _exchange The Exchange whose router address is needed * * @return IUniswapV2Router02 router of the given exchange */ function _getRouter(Exchange _exchange) internal view returns(IUniswapV2Router02) { return (_exchange == Exchange.Uniswap) ? uniRouter : sushiRouter; } }
============ Constants ============= */ ============ State Variables ============ */ ============ Events ============ */ ============ Modifiers ============ */
modifier isSetToken(ISetToken _setToken) { require(setController.isSet(address(_setToken)), "ExchangeIssuance: INVALID SET"); _; } constructor( address _weth, address _uniFactory, IUniswapV2Router02 _uniRouter, address _sushiFactory, IUniswapV2Router02 _sushiRouter, IController _setController, IBasicIssuanceModule _basicIssuanceModule ) public
2,571,857
[ 1, 14468, 5245, 422, 1432, 12275, 342, 422, 1432, 631, 3287, 23536, 422, 1432, 631, 342, 422, 1432, 631, 9043, 422, 1432, 631, 342, 422, 1432, 631, 3431, 3383, 422, 1432, 631, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 9606, 13532, 1345, 12, 45, 694, 1345, 389, 542, 1345, 13, 288, 203, 540, 2583, 12, 542, 2933, 18, 291, 694, 12, 2867, 24899, 542, 1345, 13, 3631, 315, 11688, 7568, 89, 1359, 30, 10071, 7855, 8863, 203, 540, 389, 31, 203, 565, 289, 203, 377, 203, 565, 3885, 12, 203, 3639, 1758, 389, 91, 546, 16, 203, 3639, 1758, 389, 318, 77, 1733, 16, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 77, 8259, 16, 7010, 3639, 1758, 389, 87, 1218, 77, 1733, 16, 7010, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 87, 1218, 77, 8259, 16, 7010, 3639, 467, 2933, 389, 542, 2933, 16, 203, 3639, 467, 8252, 7568, 89, 1359, 3120, 389, 13240, 7568, 89, 1359, 3120, 203, 565, 262, 203, 3639, 1071, 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 ]
./full_match/7700/0xd5609cD0e1675331E4Fb1d43207C8d9D83AAb17C/sources/contracts/bridge/SynapseBridge.sol
BRIDGE FUNCTIONS TO HANDLE DIFF ADDRESSES* @notice Relays to nodes that (typically) a wrapped synAsset ERC20 token has been burned and the underlying needs to be redeeemed on the native chain @param to address on other chain to redeem underlying assets to @param chainId which underlying chain to bridge assets onto @param token ERC20 compatible token to deposit into the bridge @param amount Amount in native token decimals to transfer cross-chain pre-fees/
function redeemV2( bytes32 to, uint256 chainId, ERC20Burnable token, uint256 amount ) external nonReentrant whenNotPaused { emit TokenRedeemV2(to, chainId, token, amount); token.burnFrom(msg.sender, amount); }
4,656,271
[ 1, 7192, 734, 7113, 13690, 55, 8493, 24166, 900, 3690, 2246, 11689, 7031, 1090, 55, 225, 4275, 8271, 358, 2199, 716, 261, 12846, 6478, 13, 279, 5805, 6194, 6672, 4232, 39, 3462, 1147, 711, 2118, 18305, 329, 471, 326, 6808, 4260, 358, 506, 283, 20953, 351, 329, 603, 326, 6448, 2687, 225, 358, 1758, 603, 1308, 2687, 358, 283, 24903, 6808, 7176, 358, 225, 2687, 548, 1492, 6808, 2687, 358, 10105, 7176, 10170, 225, 1147, 4232, 39, 3462, 7318, 1147, 358, 443, 1724, 1368, 326, 10105, 225, 3844, 16811, 316, 6448, 1147, 15105, 358, 7412, 6828, 17, 5639, 675, 17, 3030, 281, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 283, 24903, 58, 22, 12, 203, 3639, 1731, 1578, 358, 16, 203, 3639, 2254, 5034, 2687, 548, 16, 203, 3639, 4232, 39, 3462, 38, 321, 429, 1147, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 3903, 1661, 426, 8230, 970, 1347, 1248, 28590, 288, 203, 3639, 3626, 3155, 426, 24903, 58, 22, 12, 869, 16, 2687, 548, 16, 1147, 16, 3844, 1769, 203, 3639, 1147, 18, 70, 321, 1265, 12, 3576, 18, 15330, 16, 3844, 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 ]
./partial_match/1/0xd4845cBc79acE2cc6E48C8671a5860FfAB920bC2/sources/UniSageV2.sol
test address public umiTokenAddr=0x81362c8c5dd5CEC3131657E7E859AAC41acC2172;
UmiTokenInterface public umiToken = UmiTokenInterface(umiTokenAddr);
9,337,479
[ 1, 3813, 1758, 1071, 9570, 77, 1345, 3178, 33, 20, 92, 28, 3437, 8898, 71, 28, 71, 25, 449, 25, 1441, 39, 23, 3437, 2313, 10321, 41, 27, 41, 28, 6162, 37, 2226, 9803, 1077, 39, 22, 28406, 31, 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, 565, 587, 9197, 1345, 1358, 1071, 9570, 77, 1345, 273, 587, 9197, 1345, 1358, 12, 30865, 1345, 3178, 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, -100 ]
./full_match/1/0xEdDb480143c51f87A4fB3b6bf290FD231c63017c/sources/contracts/JellyPoolBearVersus.sol
* @notice ERC721 BaseURI for computing tokenURI @return IPFS uri to the current state (Guilty / Not Guilty) of the tokens/
function _baseURI() internal pure override returns (string memory) { return }
17,040,087
[ 1, 654, 39, 27, 5340, 3360, 3098, 364, 20303, 1147, 3098, 327, 2971, 4931, 2003, 358, 326, 783, 919, 261, 6099, 330, 4098, 342, 2288, 6467, 330, 4098, 13, 434, 326, 2430, 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, 225, 445, 389, 1969, 3098, 1435, 2713, 16618, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 565, 327, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; /* Adapted from strings.sol created by Nick Johnson <[email protected]> * Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> */ 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); } function memcpy(uint dest, uint src, uint len) private pure { // 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)) } } function concat(slice self, slice other) internal returns (string) { var ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice self, slice needle) internal returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 68 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) let end := add(selfptr, sub(selflen, needlelen)) ptr := selfptr loop: jumpi(exit, eq(and(mload(ptr), mask), needledata)) ptr := add(ptr, 1) jumpi(loop, lt(sub(ptr, 1), end)) ptr := add(selfptr, selflen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr; for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice self, slice needle, slice token) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice self, slice needle) internal returns (slice token) { split(self, needle, token); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice self) internal pure returns (string) { var ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } } /* Helper String Functions for Game Manager Contract * @title String Healpers * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract StringHelpers { using strings for *; function stringToBytes32(string memory source) internal returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function bytes32ToString(bytes32 x) constant internal returns (string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <[email protected]> (https://github.com/dete) contract ERC721 { // Required methods function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) public view returns (address owner); function approve(address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; function transferFrom(address _from, address _to, uint256 _tokenId) public; function implementsERC721() public pure returns (bool); function takeOwnership(uint256 _tokenId) public; function totalSupply() public view returns (uint256 total); event Transfer(address indexed from, address indexed to, uint256 tokenId); event Approval(address indexed owner, address indexed approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId); // function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } /* Controls state and access rights for contract functions * @title Operational Control * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) * Inspired and adapted from contract created by OpenZeppelin * Ref: https://github.com/OpenZeppelin/zeppelin-solidity/ */ contract OperationalControl { // Facilitates access & control for the game. // Roles: // -The Managers (Primary/Secondary): Has universal control of all elements (No ability to withdraw) // -The Banker: The Bank can withdraw funds and adjust fees / prices. /// @dev Emited when contract is upgraded event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public managerPrimary; address public managerSecondary; address public bankManager; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; // @dev Keeps track whether the contract erroredOut. When that is true, most actions are blocked & refund can be claimed bool public error = false; /// @dev Operation modifiers for limiting access modifier onlyManager() { require(msg.sender == managerPrimary || msg.sender == managerSecondary); _; } modifier onlyBanker() { require(msg.sender == bankManager); _; } modifier anyOperator() { require( msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager ); _; } /// @dev Assigns a new address to act as the Primary Manager. function setPrimaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerPrimary = _newGM; } /// @dev Assigns a new address to act as the Secondary Manager. function setSecondaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerSecondary = _newGM; } /// @dev Assigns a new address to act as the Banker. function setBanker(address _newBK) external onlyManager { require(_newBK != address(0)); bankManager = _newBK; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Modifier to allow actions only when the contract has Error modifier whenError { require(error); _; } /// @dev Called by any Operator role to pause the contract. /// Used only if a bug or exploit is discovered (Here to limit losses / damage) function pause() external onlyManager whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function unpause() public onlyManager whenPaused { // can't unpause if contract was upgraded paused = false; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function hasError() public onlyManager whenPaused { error = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function noError() public onlyManager whenPaused { error = false; } } contract CSCPreSaleItemBase is ERC721, OperationalControl, StringHelpers { /*** EVENTS ***/ /// @dev The Created event is fired whenever a new collectible comes into existence. event CollectibleCreated(address owner, uint256 globalId, uint256 collectibleType, uint256 collectibleClass, uint256 sequenceId, bytes32 collectibleName); /*** CONSTANTS ***/ /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant NAME = "CSCPreSaleFactory"; string public constant SYMBOL = "CSCPF"; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); /// @dev CSC Pre Sale Struct, having details of the collectible struct CSCPreSaleItem { /// @dev sequence ID i..e Local Index uint256 sequenceId; /// @dev name of the collectible stored in bytes bytes32 collectibleName; /// @dev Collectible Type uint256 collectibleType; /// @dev Collectible Class uint256 collectibleClass; /// @dev owner address address owner; /// @dev redeemed flag (to help whether it got redeemed or not) bool isRedeemed; } /// @dev array of CSCPreSaleItem type holding information on the Collectibles Created CSCPreSaleItem[] allPreSaleItems; /// @dev Max Count for preSaleItem type -> preSaleItem class -> max. limit mapping(uint256 => mapping(uint256 => uint256)) public preSaleItemTypeToClassToMaxLimit; /// @dev Map from preSaleItem type -> preSaleItem class -> max. limit set (bool) mapping(uint256 => mapping(uint256 => bool)) public preSaleItemTypeToClassToMaxLimitSet; /// @dev Map from preSaleItem type -> preSaleItem class -> Name (string / bytes32) mapping(uint256 => mapping(uint256 => bytes32)) public preSaleItemTypeToClassToName; // @dev mapping which holds all the possible addresses which are allowed to interact with the contract mapping (address => bool) approvedAddressList; // @dev mapping holds the preSaleItem -> owner details mapping (uint256 => address) public preSaleItemIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) private ownershipTokenCount; /// @dev A mapping from preSaleItem to an address that has been approved to call /// transferFrom(). Each Collectible can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public preSaleItemIndexToApproved; /// @dev A mapping of preSaleItem Type to Type Sequence Number to Collectible mapping (uint256 => mapping (uint256 => mapping ( uint256 => uint256 ) ) ) public preSaleItemTypeToSequenceIdToCollectible; /// @dev A mapping from Pre Sale Item Type IDs to the Sequqence Number . mapping (uint256 => mapping ( uint256 => uint256 ) ) public preSaleItemTypeToCollectibleCount; /// @dev Token Starting Index taking into account the old presaleContract total assets that can be generated uint256 public STARTING_ASSET_BASE = 3000; /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } function setMaxLimit(string _collectibleName, uint256 _collectibleType, uint256 _collectibleClass, uint256 _maxLimit) external onlyManager whenNotPaused { require(_maxLimit > 0); require(_collectibleType >= 0 && _collectibleClass >= 0); require(stringToBytes32(_collectibleName) != stringToBytes32("")); require(!preSaleItemTypeToClassToMaxLimitSet[_collectibleType][_collectibleClass]); preSaleItemTypeToClassToMaxLimit[_collectibleType][_collectibleClass] = _maxLimit; preSaleItemTypeToClassToMaxLimitSet[_collectibleType][_collectibleClass] = true; preSaleItemTypeToClassToName[_collectibleType][_collectibleClass] = stringToBytes32(_collectibleName); } /// @dev Method to fetch collectible details function getCollectibleDetails(uint256 _tokenId) external view returns(uint256 assetId, uint256 sequenceId, uint256 collectibleType, uint256 collectibleClass, string collectibleName, bool isRedeemed, address owner) { require (_tokenId > STARTING_ASSET_BASE); uint256 generatedCollectibleId = _tokenId - STARTING_ASSET_BASE; CSCPreSaleItem memory _Obj = allPreSaleItems[generatedCollectibleId]; assetId = _tokenId; sequenceId = _Obj.sequenceId; collectibleType = _Obj.collectibleType; collectibleClass = _Obj.collectibleClass; collectibleName = bytes32ToString(_Obj.collectibleName); owner = _Obj.owner; isRedeemed = _Obj.isRedeemed; } /*** PUBLIC FUNCTIONS ***/ /// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve(address _to, uint256 _tokenId) public { // Caller must own token. require (_tokenId > STARTING_ASSET_BASE); require(_owns(msg.sender, _tokenId)); preSaleItemIndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } /// For querying balance of a particular account /// @param _owner The address for balance query /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } function implementsERC721() public pure returns (bool) { return true; } /// For querying owner of token /// @param _tokenId The tokenID for owner inquiry /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { require (_tokenId > STARTING_ASSET_BASE); owner = preSaleItemIndexToOwner[_tokenId]; require(owner != address(0)); } /// @dev Required for ERC-721 compliance. function symbol() public pure returns (string) { return SYMBOL; } /// @notice Allow pre-approved user to take ownership of a token /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _tokenId) public { require (_tokenId > STARTING_ASSET_BASE); address newOwner = msg.sender; address oldOwner = preSaleItemIndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } /// @param _owner The owner whose collectibles tokens we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire CSCPreSaleItem array looking for collectibles belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalCount = totalSupply() + 1 + STARTING_ASSET_BASE; uint256 resultIndex = 0; // We count on the fact that all LS PreSaleItems have IDs starting at 0 and increasing // sequentially up to the total count. uint256 _tokenId; for (_tokenId = STARTING_ASSET_BASE; _tokenId < totalCount; _tokenId++) { if (preSaleItemIndexToOwner[_tokenId] == _owner) { result[resultIndex] = _tokenId; resultIndex++; } } return result; } } /// For querying totalSupply of token /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256 total) { return allPreSaleItems.length - 1; //Removed 0 index } /// Owner initates the transfer of the token to another account /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transfer(address _to, uint256 _tokenId) public { require (_tokenId > STARTING_ASSET_BASE); require(_addressNotNull(_to)); require(_owns(msg.sender, _tokenId)); _transfer(msg.sender, _to, _tokenId); } /// Third-party initiates transfer of token from address _from to address _to /// @param _from The address for the token to be transferred from. /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transferFrom(address _from, address _to, uint256 _tokenId) public { require (_tokenId > STARTING_ASSET_BASE); require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } /*** PRIVATE FUNCTIONS ***/ /// @dev Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) internal pure returns (bool) { return _to != address(0); } /// @dev For checking approval of transfer for address _to function _approved(address _to, uint256 _tokenId) internal view returns (bool) { return preSaleItemIndexToApproved[_tokenId] == _to; } /// @dev For creating CSC Collectible function _createCollectible(bytes32 _collectibleName, uint256 _collectibleType, uint256 _collectibleClass) internal returns(uint256) { uint256 _sequenceId = uint256(preSaleItemTypeToCollectibleCount[_collectibleType][_collectibleClass]) + 1; // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. require(_sequenceId == uint256(uint32(_sequenceId))); CSCPreSaleItem memory _collectibleObj = CSCPreSaleItem( _sequenceId, _collectibleName, _collectibleType, _collectibleClass, address(0), false ); uint256 generatedCollectibleId = allPreSaleItems.push(_collectibleObj) - 1; uint256 collectibleIndex = generatedCollectibleId + STARTING_ASSET_BASE; preSaleItemTypeToSequenceIdToCollectible[_collectibleType][_collectibleClass][_sequenceId] = collectibleIndex; preSaleItemTypeToCollectibleCount[_collectibleType][_collectibleClass] = _sequenceId; // emit Created event // CollectibleCreated(address owner, uint256 globalId, uint256 collectibleType, uint256 collectibleClass, uint256 sequenceId, bytes32 collectibleName); CollectibleCreated(address(this), collectibleIndex, _collectibleType, _collectibleClass, _sequenceId, _collectibleObj.collectibleName); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), address(this), collectibleIndex); return collectibleIndex; } /// @dev Check for token ownership function _owns(address claimant, uint256 _tokenId) internal view returns (bool) { return claimant == preSaleItemIndexToOwner[_tokenId]; } /// @dev Assigns ownership of a specific preSaleItem to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { uint256 generatedCollectibleId = _tokenId - STARTING_ASSET_BASE; // Updating the owner details of the collectible CSCPreSaleItem memory _Obj = allPreSaleItems[generatedCollectibleId]; _Obj.owner = _to; allPreSaleItems[generatedCollectibleId] = _Obj; // Since the number of preSaleItem is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; //transfer ownership preSaleItemIndexToOwner[_tokenId] = _to; // When creating new collectibles _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete preSaleItemIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } /// @dev Checks if a given address currently has transferApproval for a particular CSCPreSaleItem. /// 0 is a valid value as it will be the starter function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { require(_tokenId > STARTING_ASSET_BASE); return preSaleItemIndexToApproved[_tokenId] == _claimant; } } /* Lucid Sight, Inc. ERC-721 Collectibles Manager. * @title LSPreSaleManager - Lucid Sight, Inc. Non-Fungible Token * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract CSCPreSaleManager is CSCPreSaleItemBase { event RefundClaimed(address owner, uint256 refundValue); /// @dev defines if preSaleItem type -> preSaleItem class -> Vending Machine to set limit (bool) mapping(uint256 => mapping(uint256 => bool)) public preSaleItemTypeToClassToCanBeVendingMachine; /// @dev defines if preSaleItem type -> preSaleItem class -> Vending Machine Fee mapping(uint256 => mapping(uint256 => uint256)) public preSaleItemTypeToClassToVendingFee; /// @dev Mapping created store the amount of value a wallet address used to buy assets mapping(address => uint256) public addressToValue; bool CSCPreSaleInit = false; /// @dev Constructor creates a reference to the NFT (ERC721) ownership contract function CSCPreSaleManager() public { require(msg.sender != address(0)); paused = true; error = false; managerPrimary = msg.sender; } /// @dev allows the contract to accept ETH function() external payable { } /// @dev Function to add approved address to the /// approved address list function addToApprovedAddress (address _newAddr) onlyManager whenNotPaused { require(_newAddr != address(0)); require(!approvedAddressList[_newAddr]); approvedAddressList[_newAddr] = true; } /// @dev Function to remove an approved address from the /// approved address list function removeFromApprovedAddress (address _newAddr) onlyManager whenNotPaused { require(_newAddr != address(0)); require(approvedAddressList[_newAddr]); approvedAddressList[_newAddr] = false; } /// @dev Function toggle vending for collectible function toggleVending (uint256 _collectibleType, uint256 _collectibleClass) external onlyManager { if(preSaleItemTypeToClassToCanBeVendingMachine[_collectibleType][_collectibleClass] == false) { preSaleItemTypeToClassToCanBeVendingMachine[_collectibleType][_collectibleClass] = true; } else { preSaleItemTypeToClassToCanBeVendingMachine[_collectibleType][_collectibleClass] = false; } } /// @dev Function toggle vending for collectible function setVendingFee (uint256 _collectibleType, uint256 _collectibleClass, uint fee) external onlyManager { preSaleItemTypeToClassToVendingFee[_collectibleType][_collectibleClass] = fee; } /// @dev This helps in creating a collectible and then /// transfer it _toAddress function createCollectible(uint256 _collectibleType, uint256 _collectibleClass, address _toAddress) onlyManager external whenNotPaused { require(msg.sender != address(0)); require(msg.sender != address(this)); require(_toAddress != address(0)); require(_toAddress != address(this)); require(preSaleItemTypeToClassToMaxLimitSet[_collectibleType][_collectibleClass]); require(preSaleItemTypeToCollectibleCount[_collectibleType][_collectibleClass] < preSaleItemTypeToClassToMaxLimit[_collectibleType][_collectibleClass]); uint256 _tokenId = _createCollectible(preSaleItemTypeToClassToName[_collectibleType][_collectibleClass], _collectibleType, _collectibleClass); _transfer(address(this), _toAddress, _tokenId); } /// @dev This helps in creating a collectible and then /// transfer it _toAddress function vendingCreateCollectible(uint256 _collectibleType, uint256 _collectibleClass, address _toAddress) payable external whenNotPaused { //Only if Vending is Allowed for this Asset require(preSaleItemTypeToClassToCanBeVendingMachine[_collectibleType][_collectibleClass]); require(msg.value >= preSaleItemTypeToClassToVendingFee[_collectibleType][_collectibleClass]); require(msg.sender != address(0)); require(msg.sender != address(this)); require(_toAddress != address(0)); require(_toAddress != address(this)); require(preSaleItemTypeToClassToMaxLimitSet[_collectibleType][_collectibleClass]); require(preSaleItemTypeToCollectibleCount[_collectibleType][_collectibleClass] < preSaleItemTypeToClassToMaxLimit[_collectibleType][_collectibleClass]); uint256 _tokenId = _createCollectible(preSaleItemTypeToClassToName[_collectibleType][_collectibleClass], _collectibleType, _collectibleClass); uint256 excessBid = msg.value - preSaleItemTypeToClassToVendingFee[_collectibleType][_collectibleClass]; if(excessBid > 0) { msg.sender.transfer(excessBid); } addressToValue[msg.sender] += preSaleItemTypeToClassToVendingFee[_collectibleType][_collectibleClass]; _transfer(address(this), _toAddress, _tokenId); } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyManager whenPaused { // Actually unpause the contract. super.unpause(); } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function hasError() public onlyManager whenPaused { // Actually error out the contract. super.hasError(); } /// @dev Function does the init step and thus allow /// to create a Dummy 0th colelctible function preSaleInit() onlyManager { require(!CSCPreSaleInit); require(allPreSaleItems.length == 0); CSCPreSaleInit = true; //Fill in index 0 to null requests CSCPreSaleItem memory _Obj = CSCPreSaleItem(0, stringToBytes32("DummyAsset"), 0, 0, address(this), true); allPreSaleItems.push(_Obj); } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT (ERC721) contract, but can be called either by /// the owner or the NFT (ERC721) contract. function withdrawBalance() onlyBanker { // We are using this boolean method to make sure that even if one fails it will still work bankManager.transfer(this.balance); } // @dev a function to claim refund if and only if theres an error in the contract function claimRefund(address _ownerAddress) whenError { uint256 refundValue = addressToValue[_ownerAddress]; require (refundValue > 0); addressToValue[_ownerAddress] = 0; _ownerAddress.transfer(refundValue); RefundClaimed(_ownerAddress, refundValue); } /// @dev Function used to set the flag isRedeemed to true /// can be called by addresses in the approvedAddressList function isRedeemed(uint256 _tokenId) { require(approvedAddressList[msg.sender]); require(_tokenId > STARTING_ASSET_BASE); uint256 generatedCollectibleId = _tokenId - STARTING_ASSET_BASE; CSCPreSaleItem memory _Obj = allPreSaleItems[generatedCollectibleId]; _Obj.isRedeemed = true; allPreSaleItems[generatedCollectibleId] = _Obj; } }
@dev For creating CSC Collectible These requires are not strictly necessary, our calling code should make sure that these conditions are never broken. emit Created event CollectibleCreated(address owner, uint256 globalId, uint256 collectibleType, uint256 collectibleClass, uint256 sequenceId, bytes32 collectibleName); This will assign ownership, and also emit the Transfer event as per ERC721 draft
function _createCollectible(bytes32 _collectibleName, uint256 _collectibleType, uint256 _collectibleClass) internal returns(uint256) { uint256 _sequenceId = uint256(preSaleItemTypeToCollectibleCount[_collectibleType][_collectibleClass]) + 1; require(_sequenceId == uint256(uint32(_sequenceId))); CSCPreSaleItem memory _collectibleObj = CSCPreSaleItem( _sequenceId, _collectibleName, _collectibleType, _collectibleClass, address(0), false ); uint256 generatedCollectibleId = allPreSaleItems.push(_collectibleObj) - 1; uint256 collectibleIndex = generatedCollectibleId + STARTING_ASSET_BASE; preSaleItemTypeToSequenceIdToCollectible[_collectibleType][_collectibleClass][_sequenceId] = collectibleIndex; preSaleItemTypeToCollectibleCount[_collectibleType][_collectibleClass] = _sequenceId; CollectibleCreated(address(this), collectibleIndex, _collectibleType, _collectibleClass, _sequenceId, _collectibleObj.collectibleName); _transfer(address(0), address(this), collectibleIndex); return collectibleIndex; }
12,867,099
[ 1, 1290, 4979, 385, 2312, 9302, 1523, 8646, 4991, 854, 486, 23457, 4573, 16, 3134, 4440, 981, 1410, 1221, 3071, 716, 4259, 4636, 854, 5903, 12933, 18, 3626, 12953, 871, 9302, 1523, 6119, 12, 2867, 3410, 16, 2254, 5034, 2552, 548, 16, 2254, 5034, 3274, 1523, 559, 16, 2254, 5034, 3274, 1523, 797, 16, 2254, 5034, 3102, 548, 16, 1731, 1578, 3274, 1523, 461, 1769, 1220, 903, 2683, 23178, 16, 471, 2546, 3626, 326, 12279, 871, 487, 1534, 4232, 39, 27, 5340, 12246, 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, 389, 2640, 10808, 1523, 12, 3890, 1578, 389, 14676, 1523, 461, 16, 2254, 5034, 389, 14676, 1523, 559, 16, 2254, 5034, 389, 14676, 1523, 797, 13, 2713, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 389, 6178, 548, 273, 2254, 5034, 12, 1484, 30746, 22580, 774, 10808, 1523, 1380, 63, 67, 14676, 1523, 559, 6362, 67, 14676, 1523, 797, 5717, 397, 404, 31, 203, 540, 203, 3639, 2583, 24899, 6178, 548, 422, 2254, 5034, 12, 11890, 1578, 24899, 6178, 548, 3719, 1769, 203, 540, 203, 3639, 385, 2312, 1386, 30746, 1180, 3778, 389, 14676, 1523, 2675, 273, 385, 2312, 1386, 30746, 1180, 12, 203, 1850, 389, 6178, 548, 16, 203, 1850, 389, 14676, 1523, 461, 16, 203, 1850, 389, 14676, 1523, 559, 16, 203, 1850, 389, 14676, 1523, 797, 16, 203, 1850, 1758, 12, 20, 3631, 203, 1850, 629, 203, 3639, 11272, 203, 540, 203, 3639, 2254, 5034, 4374, 10808, 1523, 548, 273, 777, 1386, 30746, 3126, 18, 6206, 24899, 14676, 1523, 2675, 13, 300, 404, 31, 203, 3639, 2254, 5034, 3274, 1523, 1016, 273, 4374, 10808, 1523, 548, 397, 10485, 1360, 67, 3033, 4043, 67, 8369, 31, 203, 540, 203, 3639, 675, 30746, 22580, 774, 4021, 28803, 10808, 1523, 63, 67, 14676, 1523, 559, 6362, 67, 14676, 1523, 797, 6362, 67, 6178, 548, 65, 273, 3274, 1523, 1016, 31, 203, 3639, 675, 30746, 22580, 774, 10808, 1523, 1380, 63, 67, 14676, 1523, 559, 6362, 67, 14676, 1523, 797, 65, 273, 389, 6178, 548, 31, 203, 540, 203, 3639, 9302, 2 ]
// File: node_modules\@openzeppelin\contracts\token\ERC20\IERC20.sol // SPDX-License-Identifier: MIT 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); } // File: node_modules\@openzeppelin\contracts\math\SafeMath.sol 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) { 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; } } // File: node_modules\@openzeppelin\contracts\utils\Address.sol 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"); } /** * @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); } } } } pragma solidity ^0.6.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 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"); } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol 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)); } } // File: node_modules\@openzeppelin\contracts\GSN\Context.sol pragma solidity ^0.6.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\access\Ownable.sol pragma solidity ^0.6.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. */ 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 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: @openzeppelin\contracts\token\ERC20\ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This 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 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts_flat\CafeToken.sol pragma solidity 0.6.12; // CafeToken with Governance. contract CafeToken is ERC20("CafeToken", "CAFE"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (Barista). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 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 The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "CAFE::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "CAFE::delegateBySig: invalid nonce"); require(now <= expiry, "CAFE::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @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 (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @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, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "CAFE::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; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying CAFEs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "CAFE::_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 DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } interface IMigratorChief { // Perform LP token migration from legacy UniswapV2 to Cafe. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // Cafe must mint EXACTLY the same amount of Cafe LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // Barista is running the Cafe. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CAFE is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract Barista is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of CAFEs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCafePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCafePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CAFEs to distribute per block. uint256 lastRewardBlock; // Last block number that CAFEs distribution occurs. uint256 accCafePerShare; // Accumulated CAFEs per share, times 1e12. See below. } // The CAFE TOKEN! CafeToken public cafe; // Dev address. address public devaddr; // Dev2 address. address public devaddr2; // Dev3 address. address public devaddr3; // Dev4 address. address public devaddr4; // Block number when bonus CAFE period ends. uint256 public bonusEndBlock; // CAFE tokens created per block. uint256 public cafePerBlock; // Bonus muliplier for early cafe makers. uint256 public constant BONUS_MULTIPLIER = 10; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChief public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CAFE mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CafeToken _cafe, address _devaddr, address _devaddr2, address _devaddr3, address _devaddr4, uint256 _cafePerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { cafe = _cafe; devaddr = _devaddr; devaddr2 = _devaddr2; devaddr3 = _devaddr3; devaddr4 = _devaddr4; cafePerBlock = _cafePerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCafePerShare: 0 })); } // Update the given pool's CAFE allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChief _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CAFEs on frontend. function pendingCafe(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCafePerShare = pool.accCafePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cafeReward = multiplier.mul(cafePerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCafePerShare = accCafePerShare.add(cafeReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCafePerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cafeReward = multiplier.mul(cafePerBlock).mul(pool.allocPoint).div(totalAllocPoint); cafe.mint(devaddr, cafeReward.div(50)); cafe.mint(devaddr2, cafeReward.div(50)); cafe.mint(devaddr3, cafeReward.div(100)); cafe.mint(devaddr4, cafeReward.div(100)); cafe.mint(address(this), cafeReward); pool.accCafePerShare = pool.accCafePerShare.add(cafeReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to Barista for CAFE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCafePerShare).div(1e12).sub(user.rewardDebt); safeCafeTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCafePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from Barista. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCafePerShare).div(1e12).sub(user.rewardDebt); safeCafeTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accCafePerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe CAFE transfer function, just in case if rounding error causes pool to not have enough CAFEs. function safeCafeTransfer(address _to, uint256 _amount) internal { uint256 cafeBal = cafe.balanceOf(address(this)); if (_amount > cafeBal) { cafe.transfer(_to, cafeBal); } else { cafe.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "not dev!"); devaddr = _devaddr; } // Update dev address by the previous dev. function dev2(address _devaddr2) public { require(msg.sender == devaddr2, "not dev2!"); devaddr2 = _devaddr2; } // Update dev address by the previous dev. function dev3(address _devaddr3) public { require(msg.sender == devaddr3, "not dev3!"); devaddr3 = _devaddr3; } // Update dev address by the previous dev. function dev4(address _devaddr4) public { require(msg.sender == devaddr4, "not dev4!"); devaddr4 = _devaddr4; } }
Update dev address by the previous dev.
function dev(address _devaddr) public { require(msg.sender == devaddr, "not dev!"); devaddr = _devaddr; }
13,816,090
[ 1, 1891, 4461, 1758, 635, 326, 2416, 4461, 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, 565, 445, 4461, 12, 2867, 389, 5206, 4793, 13, 1071, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 4461, 4793, 16, 315, 902, 4461, 4442, 1769, 203, 3639, 4461, 4793, 273, 389, 5206, 4793, 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, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/Context.sol 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; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <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 () 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/access/Operator.sol pragma solidity >=0.7.0 <0.8.0; abstract contract Operator is Context, Ownable { address private _operator; event OperatorTransferred( address indexed previousOperator, address indexed newOperator ); constructor() { _operator = _msgSender(); emit OperatorTransferred(address(0), _operator); } function operator() public view returns (address) { return _operator; } modifier onlyOperator() { require( _operator == _msgSender(), 'operator: caller is not the operator' ); _; } function isOperator() public view returns (bool) { return _msgSender() == _operator; } function transferOperator(address newOperator_) public onlyOwner { _transferOperator(newOperator_); } function _transferOperator(address newOperator_) internal { require( newOperator_ != address(0), 'operator: zero address given for new operator' ); emit OperatorTransferred(address(0), newOperator_); _operator = newOperator_; } } // File: @openzeppelin/contracts/math/Math.sol pragma solidity >=0.6.0 <0.8.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); } } // File: @openzeppelin/contracts/utils/Address.sol 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); } } } } // File: @openzeppelin/contracts/math/SafeMath.sol 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; } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity >=0.6.0 <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 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"); } } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity >=0.6.0 <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 `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); } // File: contracts/distribution/PoolStore.sol pragma solidity >=0.7.0 <0.8.0; interface IPoolStore { /* ================= EVENTS ================= */ event Deposit( address indexed operator, address indexed owner, uint256 indexed pid, uint256 amount ); event Withdraw( address indexed operator, address indexed owner, uint256 indexed pid, uint256 amount ); /* ================= CALLS ================= */ // common function totalWeight() external view returns (uint256); function poolLength() external view returns (uint256); // index function poolIdsOf(address _token) external view returns (uint256[] memory); // pool info function nameOf(uint256 _pid) external view returns (string memory); function tokenOf(uint256 _pid) external view returns (address); function weightOf(uint256 _pid) external view returns (uint256); function totalSupply(uint256 _pid) external view returns (uint256); function balanceOf(uint256 _pid, address _owner) external view returns (uint256); /* ================= TXNS ================= */ function deposit( uint256 _pid, address _owner, uint256 _amount ) external; function withdraw( uint256 _pid, address _owner, uint256 _amount ) external; function emergencyWithdraw(uint256 _pid) external; } interface IPoolStoreGov { /* ================= EVENTS ================= */ event EmergencyReported(address indexed reporter); event EmergencyResolved(address indexed resolver); event WeightFeederChanged( address indexed operator, address indexed oldFeeder, address indexed newFeeder ); event PoolAdded( address indexed operator, uint256 indexed pid, string name, address token, uint256 weight ); event PoolWeightChanged( address indexed operator, uint256 indexed pid, uint256 from, uint256 to ); event PoolNameChanged( address indexed operator, uint256 indexed pid, string from, string to ); /* ================= TXNS ================= */ // emergency function reportEmergency() external; function resolveEmergency() external; // feeder function setWeightFeeder(address _newFeeder) external; // pool setting function addPool( string memory _name, IERC20 _token, uint256 _weight ) external; function setPool(uint256 _pid, uint256 _weight) external; function setPool(uint256 _pid, string memory _name) external; } contract PoolStore is IPoolStore, IPoolStoreGov, Operator { using SafeMath for uint256; using SafeERC20 for IERC20; /* ================= DATA STRUCTURE ================= */ struct Pool { string name; IERC20 token; uint256 weight; uint256 totalSupply; } /* ================= STATES ================= */ uint256 public override totalWeight = 0; Pool[] public pools; mapping(uint256 => mapping(address => uint256)) balances; mapping(address => uint256[]) public indexByToken; bool public emergency = false; address public weightFeeder; constructor() Operator() { weightFeeder = _msgSender(); } /* ================= GOV - OWNER ONLY ================= */ /** * @dev CAUTION: DO NOT USE IN NORMAL SITUATION * @notice Enable emergency withdraw */ function reportEmergency() public override onlyOwner { emergency = true; emit EmergencyReported(_msgSender()); } /** * @dev CAUTION: DO NOT USE IN NORMAL SITUATION * @notice Disable emergency withdraw */ function resolveEmergency() public override onlyOwner { emergency = false; emit EmergencyResolved(_msgSender()); } /* * @param _newFeeder weight feeder address to change */ function setWeightFeeder(address _newFeeder) public override onlyOwner { address oldFeeder = weightFeeder; weightFeeder = _newFeeder; emit WeightFeederChanged(_msgSender(), oldFeeder, _newFeeder); } /** * @param _token pool token * @param _weight pool weight */ function addPool( string memory _name, IERC20 _token, uint256 _weight ) public override onlyOwner { totalWeight = totalWeight.add(_weight); uint256 index = pools.length; indexByToken[address(_token)].push(index); pools.push( Pool({name: _name, token: _token, weight: _weight, totalSupply: 0}) ); emit PoolAdded(_msgSender(), index, _name, address(_token), _weight); } /** * @param _pid pool id * @param _weight target pool weight */ function setPool(uint256 _pid, uint256 _weight) public override onlyWeightFeeder checkPoolId(_pid) { Pool memory pool = pools[_pid]; uint256 oldWeight = pool.weight; totalWeight = totalWeight.add(_weight).sub(pool.weight); pool.weight = _weight; pools[_pid] = pool; emit PoolWeightChanged(_msgSender(), _pid, oldWeight, _weight); } /** * @param _pid pool id * @param _name name of pool */ function setPool(uint256 _pid, string memory _name) public override checkPoolId(_pid) onlyOwner { string memory oldName = pools[_pid].name; pools[_pid].name = _name; emit PoolNameChanged(_msgSender(), _pid, oldName, _name); } /* ================= MODIFIER ================= */ modifier onlyWeightFeeder { require(_msgSender() == weightFeeder, 'PoolStore: unauthorized'); _; } modifier checkPoolId(uint256 _pid) { require(_pid <= pools.length, 'PoolStore: invalid pid'); _; } /* ================= CALLS - ANYONE ================= */ /** * @return total pool length */ function poolLength() public view override returns (uint256) { return pools.length; } /** * @param _token pool token address * @return pool id */ function poolIdsOf(address _token) public view override returns (uint256[] memory) { return indexByToken[_token]; } /** * @param _pid pool id * @return name of pool */ function nameOf(uint256 _pid) public view override checkPoolId(_pid) returns (string memory) { return pools[_pid].name; } /** * @param _pid pool id * @return pool token */ function tokenOf(uint256 _pid) public view override checkPoolId(_pid) returns (address) { return address(pools[_pid].token); } /** * @param _pid pool id * @return pool weight */ function weightOf(uint256 _pid) public view override checkPoolId(_pid) returns (uint256) { return pools[_pid].weight; } /** * @param _pid pool id * @return total staked token amount */ function totalSupply(uint256 _pid) public view override checkPoolId(_pid) returns (uint256) { return pools[_pid].totalSupply; } /** * @param _pid pool id * @param _sender staker address * @return staked amount of user */ function balanceOf(uint256 _pid, address _sender) public view override checkPoolId(_pid) returns (uint256) { return balances[_pid][_sender]; } /* ================= TXNS - OPERATOR ONLY ================= */ /** * @param _pid pool id * @param _owner stake address * @param _amount stake amount */ function deposit( uint256 _pid, address _owner, uint256 _amount ) public override checkPoolId(_pid) onlyOperator { pools[_pid].totalSupply = pools[_pid].totalSupply.add(_amount); balances[_pid][_owner] = balances[_pid][_owner].add(_amount); IERC20(tokenOf(_pid)).safeTransferFrom( _msgSender(), address(this), _amount ); emit Deposit(_msgSender(), _owner, _pid, _amount); } function _withdraw( uint256 _pid, address _owner, uint256 _amount ) internal { pools[_pid].totalSupply = pools[_pid].totalSupply.sub(_amount); balances[_pid][_owner] = balances[_pid][_owner].sub(_amount); IERC20(tokenOf(_pid)).safeTransfer(_msgSender(), _amount); emit Withdraw(_msgSender(), _owner, _pid, _amount); } /** * @param _pid pool id * @param _owner stake address * @param _amount stake amount */ function withdraw( uint256 _pid, address _owner, uint256 _amount ) public override checkPoolId(_pid) onlyOperator { _withdraw(_pid, _owner, _amount); } /** * @notice Anyone can withdraw its balance even if is not the operator * @param _pid pool id */ function emergencyWithdraw(uint256 _pid) public override checkPoolId(_pid) { require(emergency, 'PoolStore: not in emergency'); _withdraw(_pid, msg.sender, balanceOf(_pid, _msgSender())); } } // File: contracts/distribution/PoolStoreWrapper.sol pragma solidity >=0.7.0 <0.8.0; abstract contract PoolStoreWrapper is Context { using SafeERC20 for IERC20; IPoolStore public store; function deposit(uint256 _pid, uint256 _amount) public virtual { IERC20(store.tokenOf(_pid)).safeTransferFrom( _msgSender(), address(this), _amount ); store.deposit(_pid, _msgSender(), _amount); } function withdraw(uint256 _pid, uint256 _amount) public virtual { store.withdraw(_pid, _msgSender(), _amount); IERC20(store.tokenOf(_pid)).safeTransfer(_msgSender(), _amount); } } // File: contracts/distribution/IPool.sol pragma solidity >=0.7.0 <0.8.0; interface IPool { /* ================= EVENTS ================= */ event DepositToken( address indexed owner, uint256 indexed pid, uint256 amount ); event WithdrawToken( address indexed owner, uint256 indexed pid, uint256 amount ); event RewardClaimed( address indexed owner, uint256 indexed pid, uint256 amount ); /* ================= CALLS ================= */ function tokenOf(uint256 _pid) external view returns (address); function poolIdsOf(address _token) external view returns (uint256[] memory); function totalSupply(uint256 _pid) external view returns (uint256); function balanceOf(uint256 _pid, address _owner) external view returns (uint256); function rewardRatePerPool(uint256 _pid) external view returns (uint256); function rewardPerToken(uint256 _pid) external view returns (uint256); function rewardEarned(uint256 _pid, address _target) external view returns (uint256); /* ================= TXNS ================= */ function massUpdate(uint256[] memory _pids) external; function update(uint256 _pid) external; function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function claimReward(uint256 _pid) external; function exit(uint256 _pid) external; } interface IPoolGov { /* ================= EVENTS ================= */ event RewardNotified( address indexed operator, uint256 amount, uint256 period ); /* ================= TXNS ================= */ function setPeriod(uint256 _startTime, uint256 _period) external; function setReward(uint256 _amount) external; function setExtraRewardRate(uint256 _extra) external; function stop() external; function migrate(address _newPool, uint256 _amount) external; } // File: contracts/distribution/DistributionV2.sol pragma solidity >=0.7.0 <0.8.0; contract DistributionV2 is IPool, IPoolGov, PoolStoreWrapper, Operator { using SafeMath for uint256; using SafeERC20 for IERC20; /* ================= DATA STRUCTURE ================= */ struct User { uint256 amount; uint256 reward; uint256 rewardPerTokenPaid; } struct Pool { bool initialized; uint256 rewardRate; uint256 lastUpdateTime; uint256 rewardPerTokenStored; } /* ================= STATE VARIABLES ================= */ // share address public share; mapping(address => bool) public approvals; // poolId => Pool mapping(uint256 => Pool) public pools; // poolId => sender => User mapping(uint256 => mapping(address => User)) public users; // poolId => sender => bool mapping(uint256 => mapping(address => bool)) public oldPoolClaimed; address oldPool; bool public stopped = false; uint256 public rewardRate = 0; uint256 public rewardRateExtra = 0; // halving uint256 public rewardRateBeforeHalve = 0; // year2=>4%, year3=>3.5%, year4=>3% uint256[] public inflationRate = [0, 0, 400, 350, 300]; uint256 public year = 1; uint256 public startSupply = 860210511822372000000000; // control uint256 public period = 0; uint256 public periodFinish = 0; uint256 public startTime = 0; /* ================= CONSTRUCTOR ================= */ constructor(address _share, address _poolStore) Ownable() { share = _share; store = IPoolStore(_poolStore); } /* ================= GOV - OWNER ONLY ================= */ /** * @param _startTime starting time to distribute * @param _period distribution period */ function setPeriod(uint256 _startTime, uint256 _period) public override onlyOperator { // re-calc if (startTime <= block.timestamp && block.timestamp < periodFinish) { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = leftover.div(_period); } period = _period; startTime = _startTime; periodFinish = _startTime.add(_period); } /** * @param _amount token amount to distribute */ function setReward(uint256 _amount) public override onlyOperator { require(block.timestamp < periodFinish, 'BACPool: already finished'); if (startTime <= block.timestamp) { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = _amount.add(leftover).div( periodFinish.sub(block.timestamp) ); } else { rewardRate = rewardRate.add( _amount.div(periodFinish.sub(startTime)) ); } } function setExtraRewardRate(uint256 _extra) public override onlyOwner { rewardRateExtra = _extra; } function setOldPool(address _oldPool) public onlyOwner { oldPool = _oldPool; } /** * @dev STOP DISTRIBUTION */ function stop() public override onlyOwner { periodFinish = block.timestamp; stopped = true; } /** * @dev MUST UPDATE ALL POOL REWARD BEFORE MIGRATION!!!!! * @param _newPool new pool address to migrate */ function migrate(address _newPool, uint256 _amount) public override onlyOwner { require(stopped, 'BACPool: not stopped'); IERC20(share).safeTransfer(_newPool, _amount); uint256 remaining = startTime.add(period).sub(periodFinish); uint256 leftover = remaining.mul(rewardRate); IPoolGov(_newPool).setPeriod(block.timestamp.add(1), remaining); IPoolGov(_newPool).setReward(leftover); } /* ================= MODIFIER ================= */ /** * @param _pid pool id * @param _target update target. if is empty, skip individual update. */ modifier updateReward(uint256 _pid, address _target) { if (!approvals[store.tokenOf(_pid)]) { IERC20(store.tokenOf(_pid)).safeApprove( address(store), type(uint256).max ); approvals[store.tokenOf(_pid)] = true; } if (block.timestamp >= startTime) { if (!pools[_pid].initialized) { pools[_pid] = Pool({ initialized: true, rewardRate: rewardRate, lastUpdateTime: startTime, rewardPerTokenStored: 0 }); } // halve if (!stopped && block.timestamp >= periodFinish) { // 11% weekly decrease reward rate if (block.timestamp < 1638144000) { // 2021-11-29 00:00:00 UTC rewardRateBeforeHalve = rewardRate; rewardRate = rewardRate.mul(89).div(100); } else { period = 365 days; year += 1; uint256 periodAll = startSupply.mul(inflationRate[year]).div(10000); rewardRate = periodAll.div(31536000); rewardRateBeforeHalve = rewardRate; startSupply += periodAll; // 2% for the year5 and beyond inflationRate.push(200); } // set period startTime = block.timestamp; periodFinish = block.timestamp.add(period); } Pool memory pool = pools[_pid]; pool.rewardPerTokenStored = rewardPerToken(_pid); if (pool.rewardRate == rewardRateBeforeHalve) { pool.rewardRate = rewardRate; } pool.lastUpdateTime = applicableRewardTime(); pools[_pid] = pool; if (_target != address(0x0)) { User memory user = users[_pid][_target]; user.reward = rewardEarned(_pid, _target); if (!oldPoolClaimed[_pid][_target]) { oldPoolClaimed[_pid][_target] = true; } user.rewardPerTokenPaid = pool.rewardPerTokenStored; users[_pid][_target] = user; } } _; } /* ================= CALLS - ANYONE ================= */ /** * @param _pid pool id * @return pool token address */ function tokenOf(uint256 _pid) external view override returns (address) { return store.tokenOf(_pid); } /** * @param _token pool token address * @return pool id */ function poolIdsOf(address _token) external view override returns (uint256[] memory) { return store.poolIdsOf(_token); } /** * @param _pid pool id * @return pool's total staked amount */ function totalSupply(uint256 _pid) external view override returns (uint256) { return store.totalSupply(_pid); } /** * @param _owner staker address * @return staker balance */ function balanceOf(uint256 _pid, address _owner) external view override returns (uint256) { return store.balanceOf(_pid, _owner); } /** * @return applicable reward time */ function applicableRewardTime() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } /** * @param _pid pool id * @param _crit reward rate */ function _rewardRatePerPool(uint256 _pid, uint256 _crit) internal view returns (uint256) { return _crit.mul(store.weightOf(_pid)).div(store.totalWeight()); } /** * @param _pid pool id * @return calculated reward rate per pool */ function rewardRatePerPool(uint256 _pid) public view override returns (uint256) { return _rewardRatePerPool(_pid, rewardRate.add(rewardRateExtra)); } /** * @param _pid pool id * @return RPT per pool */ function rewardPerToken(uint256 _pid) public view override returns (uint256) { Pool memory pool = pools[_pid]; if (store.totalSupply(_pid) == 0 || block.timestamp < startTime) { return pool.rewardPerTokenStored; } if (pool.rewardRate != 0 && pool.rewardRate == rewardRateBeforeHalve) { uint256 beforeHalve = startTime .sub(pool.lastUpdateTime) .mul(_rewardRatePerPool(_pid, rewardRateBeforeHalve)) .mul(1e18) .div(store.totalSupply(_pid)); uint256 afterHalve = applicableRewardTime() .sub(startTime) .mul(rewardRatePerPool(_pid)) .mul(1e18) .div(store.totalSupply(_pid)); return pool.rewardPerTokenStored.add(beforeHalve).add(afterHalve); } else { return pool.rewardPerTokenStored.add( applicableRewardTime() .sub(pool.lastUpdateTime) .mul(rewardRatePerPool(_pid)) .mul(1e18) .div(store.totalSupply(_pid)) ); } } /** * @param _pid pool id * @param _target target address * @return reward amount per pool */ function rewardEarned(uint256 _pid, address _target) public view override returns (uint256) { User memory user = users[_pid][_target]; uint256 oldUnclaim = 0; if (oldPool != address(0x0) && !oldPoolClaimed[_pid][_target]) { oldUnclaim += IPool(oldPool).rewardEarned(_pid, _target); } return store .balanceOf(_pid, _target) .mul(rewardPerToken(_pid).sub(user.rewardPerTokenPaid)) .div(1e18) .add(user.reward) .add(oldUnclaim); } /* ================= TXNS - ANYONE ================= */ /** * @param _pids array of pool ids */ function massUpdate(uint256[] memory _pids) public override { for (uint256 i = 0; i < _pids.length; i++) { update(_pids[i]); } } /** * @param _pid pool id */ function update(uint256 _pid) public override updateReward(_pid, address(0x0)) {} /** * @param _pid pool id * @param _amount deposit amount */ function deposit(uint256 _pid, uint256 _amount) public override(IPool, PoolStoreWrapper) updateReward(_pid, _msgSender()) { require(!stopped, 'BASPool: stopped'); super.deposit(_pid, _amount); emit DepositToken(_msgSender(), _pid, _amount); } /** * @param _pid pool id * @param _amount withdraw amount */ function withdraw(uint256 _pid, uint256 _amount) public override(IPool, PoolStoreWrapper) updateReward(_pid, _msgSender()) { require(!stopped, 'BASPool: stopped'); super.withdraw(_pid, _amount); emit WithdrawToken(_msgSender(), _pid, _amount); } /** * @param _pid pool id */ function claimReward(uint256 _pid) public override updateReward(_pid, _msgSender()) { claimReward(_pid, _msgSender()); } /** * @param _pid pool id * @param _owner claim for owner */ function claimReward(uint256 _pid, address _owner) public updateReward(_pid, _owner) { uint256 reward = users[_pid][_owner].reward; if (reward > 0) { users[_pid][_owner].reward = 0; IERC20(share).safeTransfer(_owner, reward); emit RewardClaimed(_owner, _pid, reward); } } /** * @dev withdraw + claim * @param _pid pool id */ function exit(uint256 _pid) external override { withdraw(_pid, store.balanceOf(_pid, _msgSender())); claimReward(_pid); } }
* @param _pid pool id @param _amount withdraw amount/
function withdraw(uint256 _pid, uint256 _amount) public override(IPool, PoolStoreWrapper) updateReward(_pid, _msgSender()) { require(!stopped, 'BASPool: stopped'); super.withdraw(_pid, _amount); emit WithdrawToken(_msgSender(), _pid, _amount); }
6,233,881
[ 1, 67, 6610, 2845, 612, 225, 389, 8949, 598, 9446, 3844, 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 ]
[ 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, 598, 9446, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 203, 3639, 1071, 203, 3639, 3849, 12, 2579, 1371, 16, 8828, 2257, 3611, 13, 203, 3639, 1089, 17631, 1060, 24899, 6610, 16, 389, 3576, 12021, 10756, 203, 565, 288, 203, 3639, 2583, 12, 5, 24228, 16, 296, 38, 3033, 2864, 30, 9627, 8284, 203, 3639, 2240, 18, 1918, 9446, 24899, 6610, 16, 389, 8949, 1769, 203, 3639, 3626, 3423, 9446, 1345, 24899, 3576, 12021, 9334, 389, 6610, 16, 389, 8949, 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 ]
./partial_match/56/0x1F362E4084d8c078F27FAb351cbFc561E931d856/sources/MasterChef.sol
OxswapToken with Governance.
contract OxswapToken is BEP20('OxswapToken', 'OXT') { function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } mapping (address => address) internal _delegates; struct Checkpoint { uint32 fromBlock; uint256 votes; } mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; mapping (address => uint32) public numCheckpoints; bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); mapping (address => uint) public nonces; event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "OXT::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "OXT::delegateBySig: invalid nonce"); require(now <= expiry, "OXT::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "OXT::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "OXT::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "OXT::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "OXT::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "OXT::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "OXT::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } } else if (cp.fromBlock < blockNumber) { } else { function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "OXT::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "OXT::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } } else { function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; return chainId; } assembly { chainId := chainid() } }
11,057,889
[ 1, 51, 92, 22270, 1345, 598, 611, 1643, 82, 1359, 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, 16351, 531, 92, 22270, 1345, 353, 9722, 52, 3462, 2668, 51, 92, 22270, 1345, 2187, 296, 51, 3983, 6134, 288, 203, 565, 445, 312, 474, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 81, 474, 24899, 869, 16, 389, 8949, 1769, 203, 3639, 389, 8501, 15608, 815, 12, 2867, 12, 20, 3631, 389, 3771, 1332, 815, 63, 67, 869, 6487, 389, 8949, 1769, 203, 565, 289, 203, 203, 27699, 565, 2874, 261, 2867, 516, 1758, 13, 2713, 389, 3771, 1332, 815, 31, 203, 203, 203, 565, 1958, 25569, 288, 203, 3639, 2254, 1578, 628, 1768, 31, 203, 3639, 2254, 5034, 19588, 31, 203, 565, 289, 203, 203, 203, 203, 203, 203, 203, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 11890, 1578, 516, 25569, 3719, 1071, 26402, 31, 203, 565, 2874, 261, 2867, 516, 2254, 1578, 13, 1071, 818, 1564, 4139, 31, 203, 565, 1731, 1578, 1071, 5381, 27025, 67, 2399, 15920, 273, 417, 24410, 581, 5034, 2932, 41, 2579, 27, 2138, 3748, 12, 1080, 508, 16, 11890, 5034, 2687, 548, 16, 2867, 3929, 310, 8924, 2225, 1769, 203, 565, 1731, 1578, 1071, 5381, 2030, 19384, 2689, 67, 2399, 15920, 273, 417, 24410, 581, 5034, 2932, 26945, 12, 2867, 7152, 73, 16, 11890, 5034, 7448, 16, 11890, 5034, 10839, 2225, 1769, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 1661, 764, 31, 203, 565, 871, 27687, 5033, 12, 2867, 8808, 11158, 639, 16, 1758, 8808, 628, 9586, 16, 1758, 8808, 358, 9586, 1769, 2 ]
./partial_match/80001/0x6fa9CF4755C180bDddd74847BA1c95587701516A/sources/FakeStrategy.sol
Withdraw partial funds, normally used with a vault withdrawal
function withdraw(uint _amount) external { require(msg.sender == controller, "!controller"); uint _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount - _balance); _amount = _amount + _balance; } address _vault = Controller(controller).vaults(address(want)); IERC20(want).transfer(_vault, _amount); }
8,823,767
[ 1, 1190, 9446, 4702, 284, 19156, 16, 15849, 1399, 598, 279, 9229, 598, 9446, 287, 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, 565, 445, 598, 9446, 12, 11890, 389, 8949, 13, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 2596, 16, 17528, 5723, 8863, 203, 3639, 2254, 389, 12296, 273, 467, 654, 39, 3462, 12, 17369, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 67, 12296, 411, 389, 8949, 13, 288, 203, 5411, 389, 8949, 273, 389, 1918, 9446, 17358, 24899, 8949, 300, 389, 12296, 1769, 203, 5411, 389, 8949, 273, 389, 8949, 397, 389, 12296, 31, 203, 3639, 289, 203, 540, 203, 3639, 1758, 389, 26983, 273, 6629, 12, 5723, 2934, 26983, 87, 12, 2867, 12, 17369, 10019, 203, 3639, 467, 654, 39, 3462, 12, 17369, 2934, 13866, 24899, 26983, 16, 389, 8949, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.0; 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; } } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } 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; } } contract Ownable is Context { address private _owner; address private _admin; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event AdminSelected(address indexed previousAdmin, address indexed newAdmin); /** * @dev Initializes the contract setting the deployer as the initial owner and admin to adress(0). */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); _admin = address(0); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Returns the address of the current admin. */ function admin() public view returns (address) { return _admin; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Throws if called by any account other than the admin. */ modifier onlyAdmin() { require(_admin == _msgSender(), "Ownable: caller is not the admin"); _; } /** * @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 Cancels the role of admin. It will not be possible to call * 'onlyAdmin' functions until new admin is selected by the owner. */ function rejectAdmin() public virtual onlyAdmin { emit AdminSelected(_admin, address(0)); _admin = address(0); } /** * @dev Only owner can appoint a new admin. */ function selectAdmin(address newAdmin) public virtual onlyOwner { emit AdminSelected(_admin, newAdmin); _admin = newAdmin; } /** * @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; } } 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); } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This 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 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 Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } contract Pausable is Context { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } abstract contract ERC20Pausable is Ownable, Pausable, ERC20 { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } /** * @dev Owner function to pause all token transfer. * * Requirements: * * - the contract must not be paused. */ function pause() public virtual onlyAdmin { _pause(); } /** * @dev Owner function to unpause all token transfer. * * Requirements: * * - the contract must be paused. */ function unpause() public virtual onlyAdmin { _unpause(); } } abstract contract ERC20Burnable is Ownable, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(address from, uint256 amount) public virtual onlyAdmin { _burn(from, amount); } } contract Freezable { mapping (address => bool) private _freezelist; event Freeze(address user); event Unfreeze(address user); /** * @dev Function to 'freeze' an address, preventing access * to basic ERC20 functionality. * * Requirements: * * - the user must not be freezed */ function _freeze(address user) internal virtual { require(_freezelist[user] == false, "User already freezed"); _freezelist[user] = true; emit Freeze(user); } /** * @dev Function to 'unfreeze' an address, re-enabling access * to basic ERC20 functionality. * * Requirements: * * - the user must be freezed. */ function _unfreeze(address user) internal virtual { require(_freezelist[user] == true, "User already freezed"); _freezelist[user] = false; emit Unfreeze(user); } /** * @dev Returns the 'freezed' state of the user. */ function freezed(address user) public view returns (bool) { return _freezelist[user]; } } abstract contract ERC20Freezable is Ownable, Freezable, ERC20 { /** * @dev Admin function to freeze an address. * * See {Freezable-_freeze} */ function freeze(address user) public virtual onlyAdmin { _freeze(user); } /** * @dev Admin function to unfreeze an address. * * See {Freezable-_unfreeze} */ function unfreeze(address user) public virtual onlyAdmin { _unfreeze(user); } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the sender or the receiver must not be freezed. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!freezed(from), "ERC20Freezable: sender freezed"); require(!freezed(to), "ERC20Freezable: receiver freezed"); } } contract ELISToken is Ownable, ERC20Pausable, ERC20Burnable, ERC20Freezable { /** * @dev Returns the address of the current owner. */ constructor(string memory name, string memory symbol) public ERC20(name, symbol){ _mint(0x48d7815da83a88064E0c672Cd9b80D464aB98E00, 100000000 ether / 1 wei); } /** * @dev Admin function to mint tokens to an address. * * See {ERC20-_mint} */ function mint(address to, uint256 amount) public onlyAdmin { _mint(to, amount); } /** * @dev See {ERC20-_beforeTokenTransfer}. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20, ERC20Pausable, ERC20Freezable) { super._beforeTokenTransfer(from, to, amount); } fallback() external { revert(); } }
* @dev Function to 'unfreeze' an address, re-enabling access to basic ERC20 functionality. Requirements: - the user must be freezed./
function _unfreeze(address user) internal virtual { require(_freezelist[user] == true, "User already freezed"); _freezelist[user] = false; emit Unfreeze(user); }
2,433,425
[ 1, 2083, 358, 296, 318, 29631, 11, 392, 1758, 16, 283, 17, 275, 17912, 2006, 358, 5337, 4232, 39, 3462, 14176, 18, 29076, 30, 300, 326, 729, 1297, 506, 4843, 94, 329, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 389, 318, 29631, 12, 2867, 729, 13, 2713, 5024, 288, 203, 3639, 2583, 24899, 9156, 94, 5449, 63, 1355, 65, 422, 638, 16, 315, 1299, 1818, 4843, 94, 329, 8863, 203, 3639, 389, 9156, 94, 5449, 63, 1355, 65, 273, 629, 31, 203, 3639, 3626, 1351, 29631, 12, 1355, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.20; contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public 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 pure { uint capacity = _capacity; 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(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if(a > b) { return a; } return b; } /** * @dev Appends a byte array to the end of the buffer. Resizes 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 pure 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. Resizes 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 pure { 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. Resizes 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 pure 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 encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure { if(value <= 23) { buf.append(uint8((major << 5) | value)); } else if(value <= 0xFF) { buf.append(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.append(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.append(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.append(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure { buf.append(uint8((major << 5) | 31)); } function encodeUInt(Buffer.buffer memory buf, uint value) internal pure { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(Buffer.buffer memory buf, int value) internal pure { 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 pure { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeString(Buffer.buffer memory buf, string value) internal pure { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory buf) internal pure { 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_Ledger = 0x30; byte constant proofType_Android = 0x40; 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()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() 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) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } 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_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 pure 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 pure 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 pure 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 pure 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 pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure 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 pure 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 pure returns (bytes) { safeMemoryCleaner(); 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 pure returns (bytes) { safeMemoryCleaner(); 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 view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); // 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) // the following variables can be relaxed // check relaxed random contract under ethereum-examples repo // for an idea on how to override and replace comit hash vars 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, keccak256(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(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(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] = byte(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 &#39;LP\x01&#39; (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match &#39;LP\x01&#39; (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 pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); 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 (!(keccak256(keyhash) == keccak256(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 &#39;result&#39; is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(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] == keccak256(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&#39;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 pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // 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&#39;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&#39;t update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can&#39;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 // &#39;mload&#39; will pad with zeroes if we overread. // There is no &#39;mload8&#39; to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // &#39;byte&#39; is not working due to the Solidity parser, so lets // use the second best option, &#39;and&#39; // 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); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } ////////////////////////////////////////////////////////////////////////////////////////////////////// // // // SAFE MATH LIBRARY // // // ////////////////////////////////////////////////////////////////////////////////////////////////////// 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; } } ////////////////////////////////////////////////////////////////////////////////////////////////////// // // // ERC20 INTERFACE // // // ////////////////////////////////////////////////////////////////////////////////////////////////////// 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); } ////////////////////////////////////////////////////////////////////////////////////////////////////// // // // GAME EVENT INTERFACE // // // ////////////////////////////////////////////////////////////////////////////////////////////////////// contract GameEventInterface { event BuyTickets(address game, address to, uint amount); event Winner(address game, address to, uint prize, uint random_number, uint buyer_who_won); event Jackpot(address game, address to, uint jackpot); } ////////////////////////////////////////////////////////////////////////////////////////////////////// // // // AWARD TOKEN INTERFACE // // // ////////////////////////////////////////////////////////////////////////////////////////////////////// contract AwardsTokensInterface { function awardToken(address toAddress, uint amount) public; function receiveFromGame() public payable; function addGame(address gameAddress, uint amount) public; } ////////////////////////////////////////////////////////////////////////////////////////////////////// // // // LOTTERY CONTRACT // // // ////////////////////////////////////////////////////////////////////////////////////////////////////// contract GAME is GameEventInterface, usingOraclize { using SafeMath for uint; /////////////////////////----- VARIABLES -----//////////////////////////////////// // address public owner; //Owner of contract // uint public ticketPool; //tickets available // uint public ticketsBought; //total tickets bought // uint public buyerNumber; //index of buyer // uint public ticketPrice; //single ticket price // uint public winnerPrize; //How much does winner get // uint public jackpot; //Jackpot // uint public jackpotFactor; //How many percent of the jackpot // uint public jackpotCut; //How much to take to jackpot // uint public jackpotChance; //Chance to win the jackpot // uint public tokenCut; //How much to send to token address // AwardsTokensInterface public token; //Instance of token contract // AwardsTokensInterface public bank; //Instance of bank contract // AwardsTokensInterface public bonus; //Instance of BNS contract // mapping(uint => address) buyers; //buyers address // mapping(uint => uint) amounts; //buyers amount of tickets bought // // uint public ledgerCount = 0; // // //Modifier // modifier onlyOwner() { // require(msg.sender == owner); // _; // } // ////////////////////////////////////////////////////////////////////////////////// /////////////////////////----- CONSTRUCTOR -----////////////////////////////////// // function GAME( // uint _ticketPool, // uint _ticketPrice, // uint _winnerPrize, // uint _jackpotFactor, // uint _jackpotCut, // uint _tokenCut, // uint _jackpotChance, // address _ICO, // address _BONUS // ) public { // require(1000000%_ticketPool == 0); // require(_ICO != address(0)); // require(_BONUS != address(0)); // require(_ticketPool.mul(_ticketPrice) > _winnerPrize.add(_jackpotCut).add(_tokenCut)); // ticketPool = _ticketPool; // ticketPrice = _ticketPrice.mul(1000000000000); // winnerPrize = _winnerPrize.mul(1000000000000); // jackpotFactor = _jackpotFactor; // jackpotCut = _jackpotCut.mul(1000000000000); // tokenCut = _tokenCut.mul(1000000000000); // jackpotChance = _jackpotChance; // jackpot = 0; // ticketsBought = 0; // buyerNumber = 0; // bank = AwardsTokensInterface(_ICO); // bonus = AwardsTokensInterface(_BONUS); // token = AwardsTokensInterface(_BONUS); // owner = msg.sender; // // // oraclize_setProof(proofType_Ledger); // * queueFunds = 0; // * queueIndex = 0; // * queueLength = 0; // * } // ////////////////////////////////////////////////////////////////////////////////// /////////////////////////////// FILL FROM QUEUE ////////////////////////////// // uint public queueIndex; // uint public queueLength; // mapping(uint => uint) queueAmount; // mapping(uint => address) queueAddress; // uint public queueFunds; // // function fillFromQueue() internal { // uint openTicketsLeft = ticketPool.sub(ticketsBought); // // //pool can handle all tickets the buyer requests // if(queueAmount[queueIndex] > 0){ // if(queueAmount[queueIndex] <= openTicketsLeft){ // ticketsBought = ticketsBought.add(queueAmount[queueIndex]);// buyers[buyerNumber] = queueAddress[queueIndex]; // amounts[buyerNumber] = queueAmount[queueIndex]; // // queueFunds = queueFunds.sub(ticketPrice.mul(queueAmount[queueIndex])); // BuyTickets(address(this), queueAddress[queueIndex], queueAmount[queueIndex]); token.awardToken(queueAddress[queueIndex], queueAmount[queueIndex]);// // if(ticketsBought >= ticketPool){ // token.awardToken(queueAddress[queueIndex], 1); // } // // queueAmount[queueIndex] = 0; // buyerNumber++; // queueIndex++; // } // //THE BUYERS HAS MORE TICKETS THAN AVAILABLE // else{ // ticketsBought = 25; // buyers[buyerNumber] = queueAddress[queueIndex]; // amounts[buyerNumber] = openTicketsLeft; // queueAmount[queueIndex] = queueAmount[queueIndex].sub(openTicketsLeft); // queueFunds = queueFunds.sub(ticketPrice.mul(openTicketsLeft)); // // BuyTickets(address(this), queueAddress[queueIndex], openTicketsLeft); token.awardToken(queueAddress[queueIndex], openTicketsLeft); // // if(ticketsBought >= ticketPool){ // token.awardToken(queueAddress[queueIndex], 1); // } // // buyerNumber++; // } // // if(ticketsBought >= ticketPool){ // jackpot = jackpot.add(jackpotCut); // // ledgerCount = 0; // getRandom(); // } // else{ // if(queueAmount[queueIndex] > 0){ // fillFromQueue(); // } // } // } // } // // ////////////////////////////////////////////////////////////////////////////////// /////////////////////////----- BUY TICKETS -----////////////////////////////////// // function buyTicket(uint in_amount) public payable { // //Allow to buy remaining if there less left than requested // * uint amount = in_amount; // * if(in_amount > ticketPool.sub(ticketsBought)){ // * amount = ticketPool.sub(ticketsBought); // * queueAmount[queueLength] = in_amount.sub(amount); // * queueAddress[queueLength] = msg.sender; // * queueFunds = queueFunds.add((in_amount.sub(amount)).mul(ticketPrice)); // * queueLength = queueLength.add(1); // * } // * // require(msg.value == (ticketPrice.mul(in_amount))); // require(amount <= ticketPool.sub(ticketsBought)); // require(in_amount > 0); // // if(amount > 0){ // //update state // ticketsBought = ticketsBought.add(amount); // buyers[buyerNumber] = msg.sender; // amounts[buyerNumber] = amount; // buyerNumber++; // // //store event // BuyTickets(address(this), msg.sender, amount); // // //Check if a winner should be found // if(ticketsBought >= ticketPool){ // jackpot = jackpot.add(jackpotCut); // token.awardToken(msg.sender, 1); // // ledgerCount = 0; // // getRandom(); // } // token.awardToken(msg.sender, amount); // } // } // ////////////////////////////////////////////////////////////////////////////////// /////////////////////////----- LEDGER RANDOM -----/////////////////////////////// event LedgerFailed(string status); // // function __callback(bytes32 _queryId, string _result, bytes _proof) public { // require (msg.sender == oraclize_cbAddress()); // // if(oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) == 0){ uint randomNumber = uint(keccak256(_result)); // startRaffle((randomNumber % 1000000)+1); // } // else if (ledgerCount <= 2){ // LedgerFailed("Requesting new"); // ledgerCount = ledgerCount.add(1); // getRandom(); // } // else { // LedgerFailed("Stopping"); // } // // } // // function getRandom() internal { // uint N = 7; // uint delay = 0; // uint callbackGas = 250000; // // if(queueAmount[queueIndex] > 0){ // callbackGas = 500000; // } // // bytes32 queryId = oraclize_newRandomDSQuery(delay, N, callbackGas); // } // // ////////////////////////////////////////////////////////////////////////////////// /////////////////////////----- FIND WINNER -----////////////////////////////////// // // function startRaffle(uint random) internal { // require(ticketsBought == ticketPool); // //Variables to find winner // address winner = owner; // uint tempSum = amounts[0]; // uint count = 0; // uint windex = (random % ticketPool).add(1); // // //Loop throught ticket-buyers to find winner // while(tempSum < windex){ // count++; // tempSum = tempSum.add(amounts[count]); // } // //store winners address // winner = buyers[count]; // // //Reset // buyerNumber = 0; // ticketsBought = 0; // // //Send jackpot to winner if the game has a jackpot and jackpot is relased // if (random <= ((jackpotChance.mul(1000000)).div(100)) && jackpotFactor > 0){// Winner(address(this), winner, winnerPrize, random, count); // Jackpot(address(this), winner, (jackpot.mul(jackpotFactor)).div(100)); // winner.transfer(winnerPrize.add((jackpot.mul(jackpotFactor)).div(100)));// jackpot = jackpot.sub((jackpot.mul(jackpotFactor)).div(100)); // } // else { // Winner(address(this), winner, winnerPrize, random, count); // winner.transfer(winnerPrize); // } // // //Send prize to winner and cut to contracts // bank.receiveFromGame.value(address(this).balance.sub((jackpot.add(tokenCut.add(queueFunds)))))(); bonus.receiveFromGame.value(tokenCut)(); // // if(queueAmount[queueIndex] > 0){ // * fillFromQueue(); // * } // * } // ////////////////////////////////////////////////////////////////////////////////// ///////////////////////----- CONTROL FUNCTION -----/////////////////////////////// // //in case oraclize doesn&#39;t answer, force a roll // function forceRoll() public onlyOwner { // getRandom(); // } // // //Fail safe // function takeAll() public onlyOwner { // msg.sender.transfer(address(this).balance); // } // ////////////////////////////////////////////////////////////////////////////////// function() public payable { msg.sender.transfer(msg.value); } }
Chance to win the jackpot
uint public jackpotChance;
7,616,899
[ 1, 782, 1359, 358, 5657, 326, 525, 484, 13130, 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, 565, 2254, 565, 1071, 525, 484, 13130, 782, 1359, 31, 7734, 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 ]
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0; import "../../interfaces/IWhiteListManager.sol"; /// @notice Trident franchised pool ERC-20 with EIP-2612 extension. /// @author Adapted from RariCapital, https://github.com/Rari-Capital/solmate/blob/main/src/erc20/ERC20.sol, /// License-Identifier: AGPL-3.0-only. abstract contract TridentFranchisedERC20 { event Approval(address indexed owner, address indexed spender, uint256 amount); event Transfer(address indexed sender, address indexed recipient, uint256 amount); string public constant name = "Sushi Franchised LP Token"; string public constant symbol = "SLP"; uint8 public constant decimals = 18; address public whiteListManager; address public operator; bool public level2; uint256 public totalSupply; /// @notice owner -> balance mapping. mapping(address => uint256) public balanceOf; /// @notice owner -> spender -> allowance mapping. mapping(address => mapping(address => uint256)) public allowance; /// @notice The EIP-712 typehash for this contract's {permit} struct. bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /// @notice The EIP-712 typehash for this contract's domain. bytes32 public immutable DOMAIN_SEPARATOR; /// @notice owner -> nonce mapping used in {permit}. mapping(address => uint256) public nonces; constructor() { DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes("1")), block.chainid, address(this) ) ); } /// @dev Initializes whitelist settings from pool. function initialize( address _whiteListManager, address _operator, bool _level2 ) internal { whiteListManager = _whiteListManager; operator = _operator; if (_level2) level2 = true; } /// @notice Approves `amount` from `msg.sender` to be spent by `spender`. /// @param spender Address of the party that can pull tokens from `msg.sender`'s account. /// @param amount The maximum collective `amount` that `spender` can pull. /// @return (bool) Returns 'true' if succeeded. function approve(address spender, uint256 amount) external returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /// @notice Transfers `amount` tokens from `msg.sender` to `recipient`. /// @param recipient The address to move tokens to. /// @param amount The token `amount` to move. /// @return (bool) Returns 'true' if succeeded. function transfer(address recipient, uint256 amount) external returns (bool) { if (level2) _checkWhiteList(recipient); balanceOf[msg.sender] -= amount; // @dev This is safe from overflow - the sum of all user // balances can't exceed 'type(uint256).max'. unchecked { balanceOf[recipient] += amount; } emit Transfer(msg.sender, recipient, amount); return true; } /// @notice Transfers `amount` tokens from `sender` to `recipient`. Caller needs approval from `from`. /// @param sender Address to pull tokens `from`. /// @param recipient The address to move tokens to. /// @param amount The token `amount` to move. /// @return (bool) Returns 'true' if succeeded. function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool) { if (level2) _checkWhiteList(recipient); if (allowance[sender][msg.sender] != type(uint256).max) { allowance[sender][msg.sender] -= amount; } balanceOf[sender] -= amount; // @dev This is safe from overflow - the sum of all user // balances can't exceed 'type(uint256).max'. unchecked { balanceOf[recipient] += amount; } emit Transfer(sender, recipient, amount); return true; } /// @notice Triggers an approval from `owner` to `spender`. /// @param owner The address to approve from. /// @param spender The address to be approved. /// @param amount The number of tokens that are approved (2^256-1 means infinite). /// @param deadline The time at which to expire the signature. /// @param v The recovery byte of the signature. /// @param r Half of the ECDSA signature pair. /// @param s Half of the ECDSA signature pair. function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_PERMIT_SIGNATURE"); allowance[recoveredAddress][spender] = amount; emit Approval(owner, spender, amount); } function _mint(address recipient, uint256 amount) internal { totalSupply += amount; // @dev This is safe from overflow - the sum of all user // balances can't exceed 'type(uint256).max'. unchecked { balanceOf[recipient] += amount; } emit Transfer(address(0), recipient, amount); } function _burn(address sender, uint256 amount) internal { balanceOf[sender] -= amount; // @dev This is safe from underflow - users won't ever // have a balance larger than `totalSupply`. unchecked { totalSupply -= amount; } emit Transfer(sender, address(0), amount); } /// @dev Checks `whiteListManager` for pool `operator` and given user `account`. function _checkWhiteList(address account) internal view { (, bytes memory _whitelisted) = whiteListManager.staticcall( abi.encodeWithSelector(IWhiteListManager.whitelistedAccounts.selector, operator, account) ); bool whitelisted = abi.decode(_whitelisted, (bool)); require(whitelisted, "NOT_WHITELISTED"); } }
@notice Transfers `amount` tokens from `sender` to `recipient`. Caller needs approval from `from`. @param sender Address to pull tokens `from`. @param recipient The address to move tokens to. @param amount The token `amount` to move. @return (bool) Returns 'true' if succeeded. @dev This is safe from overflow - the sum of all user balances can't exceed 'type(uint256).max'.
function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool) { if (level2) _checkWhiteList(recipient); if (allowance[sender][msg.sender] != type(uint256).max) { allowance[sender][msg.sender] -= amount; } balanceOf[sender] -= amount; unchecked { balanceOf[recipient] += amount; } emit Transfer(sender, recipient, amount); return true; }
1,032,028
[ 1, 1429, 18881, 1375, 8949, 68, 2430, 628, 1375, 15330, 68, 358, 1375, 20367, 8338, 20646, 4260, 23556, 628, 1375, 2080, 8338, 225, 5793, 5267, 358, 6892, 2430, 1375, 2080, 8338, 225, 8027, 1021, 1758, 358, 3635, 2430, 358, 18, 225, 3844, 1021, 1147, 1375, 8949, 68, 358, 3635, 18, 327, 261, 6430, 13, 2860, 296, 3767, 11, 309, 15784, 18, 225, 1220, 353, 4183, 628, 9391, 300, 326, 2142, 434, 777, 729, 324, 26488, 848, 1404, 9943, 296, 723, 12, 11890, 5034, 2934, 1896, 10332, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 7412, 1265, 12, 203, 3639, 1758, 5793, 16, 203, 3639, 1758, 8027, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 3903, 1135, 261, 6430, 13, 288, 203, 3639, 309, 261, 2815, 22, 13, 389, 1893, 13407, 682, 12, 20367, 1769, 203, 3639, 309, 261, 5965, 1359, 63, 15330, 6362, 3576, 18, 15330, 65, 480, 618, 12, 11890, 5034, 2934, 1896, 13, 288, 203, 5411, 1699, 1359, 63, 15330, 6362, 3576, 18, 15330, 65, 3947, 3844, 31, 203, 3639, 289, 203, 3639, 11013, 951, 63, 15330, 65, 3947, 3844, 31, 203, 3639, 22893, 288, 203, 5411, 11013, 951, 63, 20367, 65, 1011, 3844, 31, 203, 3639, 289, 203, 3639, 3626, 12279, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 3639, 327, 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 ]
./full_match/1/0x8808bFcAA404bDf41248f1181a2C128a3a697170/sources/contracts/BartyVerse.sol
if paused don't excute remainder of mint func
require(!paused);
3,862,052
[ 1, 430, 17781, 2727, 1404, 3533, 624, 10022, 434, 312, 474, 1326, 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, 2583, 12, 5, 8774, 3668, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0x000e7385A87A0F6a0D8C12b8ef1224C35486f263/sources/BPool.sol
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` call, or as part of the Solidity `fallback` or `receive` functions. If overriden should call `super._beforeFallback()`./
function _beforeFallback() internal { }
8,907,754
[ 1, 5394, 716, 353, 2566, 1865, 31678, 1473, 358, 326, 4471, 18, 4480, 5865, 487, 1087, 434, 279, 11297, 1375, 67, 16471, 68, 745, 16, 578, 487, 1087, 434, 326, 348, 7953, 560, 1375, 16471, 68, 578, 1375, 18149, 68, 4186, 18, 971, 31736, 1410, 745, 1375, 9565, 6315, 5771, 12355, 1435, 8338, 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, 445, 389, 5771, 12355, 1435, 2713, 288, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * @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 SafeMath * @dev Math operations with safety checks that throw on error */ 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; } } /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } /** * @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 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) public balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); 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]; } /** * 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) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } 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 Mintable token * @dev Simple ERC20 Token example, with mintable token creation */ contract MintableToken is StandardToken, Ownable { uint256 public hardCap; event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @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) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); 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; MintFinished(); return true; } } /** * @title CABoxToken * @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator. * Note they can later distribute these tokens as they wish using `transfer` and other * `StandardToken` functions. */ contract CABoxToken is MintableToken, Destructible { string public constant name = "CABox"; string public constant symbol = "CAB"; uint8 public constant decimals = 18; /** * @dev Constructor that gives msg.sender all of existing tokens. */ function CABoxToken() public { hardCap = 500 * 1000000 * (10 ** uint256(decimals)); } /** * @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) onlyOwner canMint public returns (bool) { require(totalSupply.add(_amount) <= hardCap); return super.mint(_to, _amount); } } /** * @title CABoxCrowdsale * @dev CABoxCrowdsale is a completed contract for managing a token crowdsale. * CABoxCrowdsale have a start and end timestamps, where investors can make * token purchases and the CABoxCrowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract CABoxCrowdsale is Ownable{ using SafeMath for uint256; // The token being sold CABoxToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // address where development funds are collected address public devWallet; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event TokenContractUpdated(bool state); event WalletAddressUpdated(bool state); function CABoxCrowdsale() public { token = createTokenContract(); startTime = 1535155200; endTime = 1540771200; wallet = 0x9BeAbD0aeB08d18612d41210aFEafD08fb84E9E8; devWallet = 0x13dF1d8F51324a237552E87cebC3f501baE2e972; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (CABoxToken) { return new CABoxToken(); } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 bonusRate = getBonusRate(); uint256 tokens = weiAmount.mul(bonusRate); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } function getBonusRate() internal view returns (uint256) { uint64[5] memory tokenRates = [uint64(24000),uint64(20000),uint64(16000),uint64(12000),uint64(8000)]; // apply bonus for time uint64[5] memory timeStartsBoundaries = [uint64(1535155200),uint64(1538352000),uint64(1538956800),uint64(1539561600),uint64(1540166400)]; uint64[5] memory timeEndsBoundaries = [uint64(1538352000),uint64(1538956800),uint64(1539561600),uint64(1540166400),uint64(1540771200)]; uint[5] memory timeRates = [uint(500),uint(250),uint(200),uint(150),uint(100)]; uint256 bonusRate = tokenRates[0]; for (uint i = 0; i < 5; i++) { bool timeInBound = (timeStartsBoundaries[i] <= now) && (now < timeEndsBoundaries[i]); if (timeInBound) { bonusRate = tokenRates[i] + tokenRates[i] * timeRates[i] / 1000; } } return bonusRate; } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value * 750 / 1000); devWallet.transfer(msg.value * 250 / 1000); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool nonZeroPurchase = msg.value != 0; bool withinPeriod = now >= startTime && now <= endTime; return nonZeroPurchase && withinPeriod; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { bool timeEnded = now > endTime; return timeEnded; } // update token contract function updateCABoxToken(address _tokenAddress) onlyOwner{ require(_tokenAddress != address(0)); token.transferOwnership(_tokenAddress); TokenContractUpdated(true); } }
creates the token to be sold. override this method to have crowdsale of a specific mintable token.
function createTokenContract() internal returns (CABoxToken) { return new CABoxToken(); }
47,334
[ 1, 19787, 326, 1147, 358, 506, 272, 1673, 18, 3849, 333, 707, 358, 1240, 276, 492, 2377, 5349, 434, 279, 2923, 312, 474, 429, 1147, 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 ]
[ 1, 1, 1, 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, 225, 445, 752, 1345, 8924, 1435, 2713, 1135, 261, 39, 2090, 2409, 1345, 13, 288, 203, 565, 327, 394, 385, 2090, 2409, 1345, 5621, 203, 225, 289, 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, -100 ]
/* =============================================== * Flattened with Solidifier by Coinage * * https://solidifier.coina.ge * =============================================== */ pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, 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 numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts 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 Subtracts two numbers, 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 numbers, 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 numbers 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 INFORMATION ----------------------------------------------------------------- file: SafeDecimalMath.sol version: 2.0 author: Kevin Brown Gavin Conway date: 2018-10-18 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A library providing safe mathematical operations for division and multiplication with the capability to round or truncate the results to the nearest increment. Operations can return a standard precision or high precision decimal. High precision decimals are useful for example when attempting to calculate percentages or fractions accurately. ----------------------------------------------------------------- */ /** * @title Safely manipulate unsigned fixed-point decimals at a given precision level. * @dev Functions accepting uints in this contract and derived contracts * are taken to be such fixed point decimals of a specified precision (either standard * or high). */ library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Owned.sol version: 1.1 author: Anton Jurisevic Dominic Romanowski date: 2018-2-26 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- An Owned contract, to be inherited by other contracts. Requires its owner to be explicitly set in the constructor. Provides an onlyOwner access modifier. To change owner, the current owner must nominate the next owner, who then has to accept the nomination. The nomination can be cancelled before it is accepted by the new owner by having the previous owner change the nomination (setting it to 0). ----------------------------------------------------------------- */ /** * @title A contract with an owner. * @notice Contract ownership can be transferred by first nominating the new owner, * who must then accept the ownership, which prevents accidental incorrect ownership transfers. */ contract Owned { address public owner; address public nominatedOwner; /** * @dev Owned Constructor */ constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } /** * @notice Nominate a new owner of this contract. * @dev Only the current owner may nominate a new owner. */ function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } /** * @notice Accept the nomination to be owner. */ function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } contract IFeePool { address public FEE_ADDRESS; function amountReceivedFromExchange(uint value) external view returns (uint); function amountReceivedFromTransfer(uint value) external view returns (uint); function feePaid(bytes4 currencyKey, uint amount) external; function appendAccountIssuanceRecord(address account, uint lockedAmount, uint debtEntryIndex) external; function rewardsMinted(uint amount) external; function transferFeeIncurred(uint value) public view returns (uint); } contract ISynthetixState { // A struct for handing values associated with an individual user's debt position struct IssuanceData { // Percentage of the total debt owned at the time // of issuance. This number is modified by the global debt // delta array. You can figure out a user's exit price and // collateralisation ratio using a combination of their initial // debt and the slice of global debt delta which applies to them. uint initialDebtOwnership; // This lets us know when (in relative terms) the user entered // the debt pool so we can calculate their exit price and // collateralistion ratio uint debtEntryIndex; } uint[] public debtLedger; uint public issuanceRatio; mapping(address => IssuanceData) public issuanceData; function debtLedgerLength() external view returns (uint); function hasIssued(address account) external view returns (bool); function incrementTotalIssuerCount() external; function decrementTotalIssuerCount() external; function setCurrentIssuanceData(address account, uint initialDebtOwnership) external; function lastDebtLedgerEntry() external view returns (uint); function appendDebtLedgerValue(uint value) external; function clearIssuanceData(address account) external; } interface ISynth { function burn(address account, uint amount) external; function issue(address account, uint amount) external; function transfer(address to, uint value) public returns (bool); function triggerTokenFallbackIfNeeded(address sender, address recipient, uint amount) external; function transferFrom(address from, address to, uint value) public returns (bool); } /** * @title SynthetixEscrow interface */ interface ISynthetixEscrow { function balanceOf(address account) public view returns (uint); function appendVestingEntry(address account, uint quantity) public; } /** * @title ExchangeRates interface */ interface IExchangeRates { function effectiveValue(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey) public view returns (uint); function rateForCurrency(bytes4 currencyKey) public view returns (uint); function anyRateIsStale(bytes4[] currencyKeys) external view returns (bool); function rateIsStale(bytes4 currencyKey) external view returns (bool); } /** * @title Synthetix interface contract * @dev pseudo interface, actually declared as contract to hold the public getters */ contract ISynthetix { // ========== PUBLIC STATE VARIABLES ========== IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ISynthetixState public synthetixState; IExchangeRates public exchangeRates; // ========== PUBLIC FUNCTIONS ========== function balanceOf(address account) public view returns (uint); function transfer(address to, uint value) public returns (bool); function effectiveValue(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey) public view returns (uint); function synthInitiatedFeePayment(address from, bytes4 sourceCurrencyKey, uint sourceAmount) external returns (bool); function synthInitiatedExchange( address from, bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress) external returns (bool); function collateralisationRatio(address issuer) public view returns (uint); function totalIssuedSynths(bytes4 currencyKey) public view returns (uint); function getSynth(bytes4 currencyKey) public view returns (ISynth); function debtBalanceOf(address issuer, bytes4 currencyKey) public view returns (uint); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: RewardEscrow.sol version: 1.0 author: Jackson Chan Clinton Ennis date: 2019-03-01 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Escrows the SNX rewards from the inflationary supply awarded to users for staking their SNX and maintaining the c-rationn target. SNW rewards are escrowed for 1 year from the claim date and users can call vest in 12 months time. ----------------------------------------------------------------- */ /** * @title A contract to hold escrowed SNX and free them at given schedules. */ contract RewardEscrow is Owned { using SafeMath for uint; /* The corresponding Synthetix contract. */ ISynthetix public synthetix; IFeePool public feePool; /* Lists of (timestamp, quantity) pairs per account, sorted in ascending time order. * These are the times at which each given quantity of SNX vests. */ mapping(address => uint[2][]) public vestingSchedules; /* An account's total escrowed synthetix balance to save recomputing this for fee extraction purposes. */ mapping(address => uint) public totalEscrowedAccountBalance; /* An account's total vested reward synthetix. */ mapping(address => uint) public totalVestedAccountBalance; /* The total remaining escrowed balance, for verifying the actual synthetix balance of this contract against. */ uint public totalEscrowedBalance; uint constant TIME_INDEX = 0; uint constant QUANTITY_INDEX = 1; /* Limit vesting entries to disallow unbounded iteration over vesting schedules. * There are 5 years of the supply scedule */ uint constant public MAX_VESTING_ENTRIES = 52*5; /* ========== CONSTRUCTOR ========== */ constructor(address _owner, ISynthetix _synthetix, IFeePool _feePool) Owned(_owner) public { synthetix = _synthetix; feePool = _feePool; } /* ========== SETTERS ========== */ /** * @notice set the synthetix contract address as we need to transfer SNX when the user vests */ function setSynthetix(ISynthetix _synthetix) external onlyOwner { synthetix = _synthetix; emit SynthetixUpdated(_synthetix); } /** * @notice set the FeePool contract as it is the only authority to be able to call * appendVestingEntry with the onlyFeePool modifer */ function setFeePool(IFeePool _feePool) external onlyOwner { feePool = _feePool; emit FeePoolUpdated(_feePool); } /* ========== VIEW FUNCTIONS ========== */ /** * @notice A simple alias to totalEscrowedAccountBalance: provides ERC20 balance integration. */ function balanceOf(address account) public view returns (uint) { return totalEscrowedAccountBalance[account]; } /** * @notice The number of vesting dates in an account's schedule. */ function numVestingEntries(address account) public view returns (uint) { return vestingSchedules[account].length; } /** * @notice Get a particular schedule entry for an account. * @return A pair of uints: (timestamp, synthetix quantity). */ function getVestingScheduleEntry(address account, uint index) public view returns (uint[2]) { return vestingSchedules[account][index]; } /** * @notice Get the time at which a given schedule entry will vest. */ function getVestingTime(address account, uint index) public view returns (uint) { return getVestingScheduleEntry(account,index)[TIME_INDEX]; } /** * @notice Get the quantity of SNX associated with a given schedule entry. */ function getVestingQuantity(address account, uint index) public view returns (uint) { return getVestingScheduleEntry(account,index)[QUANTITY_INDEX]; } /** * @notice Obtain the index of the next schedule entry that will vest for a given user. */ function getNextVestingIndex(address account) public view returns (uint) { uint len = numVestingEntries(account); for (uint i = 0; i < len; i++) { if (getVestingTime(account, i) != 0) { return i; } } return len; } /** * @notice Obtain the next schedule entry that will vest for a given user. * @return A pair of uints: (timestamp, synthetix quantity). */ function getNextVestingEntry(address account) public view returns (uint[2]) { uint index = getNextVestingIndex(account); if (index == numVestingEntries(account)) { return [uint(0), 0]; } return getVestingScheduleEntry(account, index); } /** * @notice Obtain the time at which the next schedule entry will vest for a given user. */ function getNextVestingTime(address account) external view returns (uint) { return getNextVestingEntry(account)[TIME_INDEX]; } /** * @notice Obtain the quantity which the next schedule entry will vest for a given user. */ function getNextVestingQuantity(address account) external view returns (uint) { return getNextVestingEntry(account)[QUANTITY_INDEX]; } /** * @notice return the full vesting schedule entries vest for a given user. */ function checkAccountSchedule(address account) public view returns (uint[520]) { uint[520] memory _result; uint schedules = numVestingEntries(account); for (uint i = 0; i < schedules; i++) { uint[2] memory pair = getVestingScheduleEntry(account, i); _result[i*2] = pair[0]; _result[i*2 + 1] = pair[1]; } return _result; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Add a new vesting entry at a given time and quantity to an account's schedule. * @dev A call to this should accompany a previous successfull call to synthetix.transfer(tewardEscrow, amount), * to ensure that when the funds are withdrawn, there is enough balance. * Note; although this function could technically be used to produce unbounded * arrays, it's only withinn the 4 year period of the weekly inflation schedule. * @param account The account to append a new vesting entry to. * @param quantity The quantity of SNX that will be escrowed. */ function appendVestingEntry(address account, uint quantity) public onlyFeePool { /* No empty or already-passed vesting entries allowed. */ require(quantity != 0, "Quantity cannot be zero"); /* There must be enough balance in the contract to provide for the vesting entry. */ totalEscrowedBalance = totalEscrowedBalance.add(quantity); require(totalEscrowedBalance <= synthetix.balanceOf(this), "Must be enough balance in the contract to provide for the vesting entry"); /* Disallow arbitrarily long vesting schedules in light of the gas limit. */ uint scheduleLength = vestingSchedules[account].length; require(scheduleLength <= MAX_VESTING_ENTRIES, "Vesting schedule is too long"); /* Escrow the tokens for 1 year. */ uint time = now + 52 weeks; if (scheduleLength == 0) { totalEscrowedAccountBalance[account] = quantity; } else { /* Disallow adding new vested SNX earlier than the last one. * Since entries are only appended, this means that no vesting date can be repeated. */ require(getVestingTime(account, numVestingEntries(account) - 1) < time, "Cannot add new vested entries earlier than the last one"); totalEscrowedAccountBalance[account] = totalEscrowedAccountBalance[account].add(quantity); } vestingSchedules[account].push([time, quantity]); emit VestingEntryCreated(account, now, quantity); } /** * @notice Allow a user to withdraw any SNX in their schedule that have vested. */ function vest() external { uint numEntries = numVestingEntries(msg.sender); uint total; for (uint i = 0; i < numEntries; i++) { uint time = getVestingTime(msg.sender, i); /* The list is sorted; when we reach the first future time, bail out. */ if (time > now) { break; } uint qty = getVestingQuantity(msg.sender, i); if (qty == 0) { continue; } vestingSchedules[msg.sender][i] = [0, 0]; total = total.add(qty); } if (total != 0) { totalEscrowedBalance = totalEscrowedBalance.sub(total); totalEscrowedAccountBalance[msg.sender] = totalEscrowedAccountBalance[msg.sender].sub(total); totalVestedAccountBalance[msg.sender] = totalVestedAccountBalance[msg.sender].add(total); synthetix.transfer(msg.sender, total); emit Vested(msg.sender, now, total); } } /* ========== MODIFIERS ========== */ modifier onlyFeePool() { bool isFeePool = msg.sender == address(feePool); require(isFeePool, "Only the FeePool contracts can perform this action"); _; } /* ========== EVENTS ========== */ event SynthetixUpdated(address newSynthetix); event FeePoolUpdated(address newFeePool); event Vested(address indexed beneficiary, uint time, uint value); event VestingEntryCreated(address indexed beneficiary, uint time, uint value); }
* @title A contract with an owner. @notice Contract ownership can be transferred by first nominating the new owner, who must then accept the ownership, which prevents accidental incorrect ownership transfers./
contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public ----------------------------------------------------------------- { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); }
1,027,968
[ 1, 37, 6835, 598, 392, 3410, 18, 225, 13456, 23178, 848, 506, 906, 4193, 635, 1122, 12457, 267, 1776, 326, 394, 3410, 16, 10354, 1297, 1508, 2791, 326, 23178, 16, 1492, 17793, 25961, 287, 11332, 23178, 29375, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 16351, 14223, 11748, 288, 203, 565, 1758, 1071, 3410, 31, 203, 565, 1758, 1071, 12457, 7458, 5541, 31, 203, 203, 565, 3885, 12, 2867, 389, 8443, 13, 203, 3639, 1071, 203, 5802, 17, 203, 203, 565, 288, 203, 3639, 2583, 24899, 8443, 480, 1758, 12, 20, 3631, 315, 5541, 1758, 2780, 506, 374, 8863, 203, 3639, 3410, 273, 389, 8443, 31, 203, 3639, 3626, 16837, 5033, 12, 2867, 12, 20, 3631, 389, 8443, 1769, 203, 565, 289, 203, 203, 565, 445, 12457, 3322, 1908, 5541, 12, 2867, 389, 8443, 13, 203, 3639, 3903, 203, 3639, 1338, 5541, 203, 565, 288, 203, 3639, 12457, 7458, 5541, 273, 389, 8443, 31, 203, 3639, 3626, 16837, 26685, 7458, 24899, 8443, 1769, 203, 565, 289, 203, 203, 565, 445, 2791, 5460, 12565, 1435, 203, 3639, 3903, 203, 565, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 12457, 7458, 5541, 16, 315, 6225, 1297, 506, 12457, 7458, 1865, 1846, 848, 2791, 23178, 8863, 203, 3639, 3626, 16837, 5033, 12, 8443, 16, 12457, 7458, 5541, 1769, 203, 3639, 3410, 273, 12457, 7458, 5541, 31, 203, 3639, 12457, 7458, 5541, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 203, 565, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 16, 315, 3386, 326, 6835, 3410, 2026, 3073, 333, 1301, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 871, 16837, 26685, 7458, 12, 2867, 394, 5541, 1769, 203, 565, 871, 16837, 5033, 12, 2867, 1592, 5541, 16, 1758, 394, 5541, 1769, 2 ]
./full_match/1/0x567c09B55294998d7a6F2A3A948e8fD331531B88/sources/contracts/UMA/common/implementation/FixedPoint.sol
* @notice Whether `a` is less than `b`. @param a a FixedPoint. @param b a FixedPoint. @return True if `a < b`, or False./
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; }
9,749,016
[ 1, 18247, 1375, 69, 68, 353, 5242, 2353, 1375, 70, 8338, 225, 279, 279, 15038, 2148, 18, 225, 324, 279, 15038, 2148, 18, 327, 1053, 309, 1375, 69, 411, 324, 9191, 578, 1083, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 353, 30899, 12, 13290, 3778, 279, 16, 1351, 5679, 3778, 324, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 279, 18, 1899, 620, 411, 324, 18, 1899, 620, 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 ]
/* Copyright 2019 ZeroEx Intl. 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. */ // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.3; pragma experimental ABIEncoderV2; import "./LibFixedMath.sol"; library LibCobbDouglas { /// @dev The cobb-douglas function used to compute fee-based rewards for /// staking pools in a given epoch. This function does not perform /// bounds checking on the inputs, but the following conditions /// need to be true: /// 0 <= fees / totalFees <= 1 /// 0 <= stake / totalStake <= 1 /// 0 <= alphaNumerator / alphaDenominator <= 1 /// @param totalRewards collected over an epoch. /// @param fees Fees attributed to the the staking pool. /// @param totalFees Total fees collected across all pools that earned rewards. /// @param stake Stake attributed to the staking pool. /// @param totalStake Total stake across all pools that earned rewards. /// @param alphaNumerator Numerator of `alpha` in the cobb-douglas function. /// @param alphaDenominator Denominator of `alpha` in the cobb-douglas /// function. /// @return rewards Rewards owed to the staking pool. function cobbDouglas( uint256 totalRewards, uint256 fees, uint256 totalFees, uint256 stake, uint256 totalStake, uint32 alphaNumerator, uint32 alphaDenominator ) public pure returns (uint256 rewards) { int256 feeRatio = LibFixedMath.toFixed(fees, totalFees); int256 stakeRatio = LibFixedMath.toFixed(stake, totalStake); if (feeRatio == 0 || stakeRatio == 0) { return rewards = 0; } // The cobb-doublas function has the form: // `totalRewards * feeRatio ^ alpha * stakeRatio ^ (1-alpha)` // This is equivalent to: // `totalRewards * stakeRatio * e^(alpha * (ln(feeRatio / stakeRatio)))` // However, because `ln(x)` has the domain of `0 < x < 1` // and `exp(x)` has the domain of `x < 0`, // and fixed-point math easily overflows with multiplication, // we will choose the following if `stakeRatio > feeRatio`: // `totalRewards * stakeRatio / e^(alpha * (ln(stakeRatio / feeRatio)))` // Compute // `e^(alpha * ln(feeRatio/stakeRatio))` if feeRatio <= stakeRatio // or // `e^(alpa * ln(stakeRatio/feeRatio))` if feeRatio > stakeRatio int256 n = feeRatio <= stakeRatio ? LibFixedMath.div(feeRatio, stakeRatio) : LibFixedMath.div(stakeRatio, feeRatio); n = LibFixedMath.exp( LibFixedMath.mulDiv( LibFixedMath.ln(n), int256(alphaNumerator), int256(alphaDenominator) ) ); // Compute // `totalRewards * n` if feeRatio <= stakeRatio // or // `totalRewards / n` if stakeRatio > feeRatio // depending on the choice we made earlier. n = feeRatio <= stakeRatio ? LibFixedMath.mul(stakeRatio, n) : LibFixedMath.div(stakeRatio, n); // Multiply the above with totalRewards. rewards = LibFixedMath.uintMul(n, totalRewards); } } /* Copyright 2017 Bprotocol Foundation, 2019 ZeroEx Intl. 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. */ // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.3; // solhint-disable indent /// @dev Signed, fixed-point, 127-bit precision math library. library LibFixedMath { // 1 int256 private constant FIXED_1 = int256( 0x0000000000000000000000000000000080000000000000000000000000000000 ); // 2**255 int256 private constant MIN_FIXED_VAL = int256( 0x8000000000000000000000000000000000000000000000000000000000000000 ); // 1^2 (in fixed-point) int256 private constant FIXED_1_SQUARED = int256( 0x4000000000000000000000000000000000000000000000000000000000000000 ); // 1 int256 private constant LN_MAX_VAL = FIXED_1; // e ^ -63.875 int256 private constant LN_MIN_VAL = int256( 0x0000000000000000000000000000000000000000000000000000000733048c5a ); // 0 int256 private constant EXP_MAX_VAL = 0; // -63.875 int256 private constant EXP_MIN_VAL = -int256( 0x0000000000000000000000000000001ff0000000000000000000000000000000 ); /// @dev Get one as a fixed-point number. function one() internal pure returns (int256 f) { f = FIXED_1; } /// @dev Returns the addition of two fixed point numbers, reverting on overflow. function add(int256 a, int256 b) internal pure returns (int256 c) { c = _add(a, b); } /// @dev Returns the addition of two fixed point numbers, reverting on overflow. function sub(int256 a, int256 b) internal pure returns (int256 c) { if (b == MIN_FIXED_VAL) { revert("out-of-bounds"); } c = _add(a, -b); } /// @dev Returns the multiplication of two fixed point numbers, reverting on overflow. function mul(int256 a, int256 b) internal pure returns (int256 c) { c = _mul(a, b) / FIXED_1; } /// @dev Returns the division of two fixed point numbers. function div(int256 a, int256 b) internal pure returns (int256 c) { c = _div(_mul(a, FIXED_1), b); } /// @dev Performs (a * n) / d, without scaling for precision. function mulDiv( int256 a, int256 n, int256 d ) internal pure returns (int256 c) { c = _div(_mul(a, n), d); } /// @dev Returns the unsigned integer result of multiplying a fixed-point /// number with an integer, reverting if the multiplication overflows. /// Negative results are clamped to zero. function uintMul(int256 f, uint256 u) internal pure returns (uint256) { if (int256(u) < int256(0)) { revert("out-of-bounds"); } int256 c = _mul(f, int256(u)); if (c <= 0) { return 0; } return uint256(uint256(c) >> 127); } /// @dev Returns the absolute value of a fixed point number. function abs(int256 f) internal pure returns (int256 c) { if (f == MIN_FIXED_VAL) { revert("out-of-bounds"); } if (f >= 0) { c = f; } else { c = -f; } } /// @dev Returns 1 / `x`, where `x` is a fixed-point number. function invert(int256 f) internal pure returns (int256 c) { c = _div(FIXED_1_SQUARED, f); } /// @dev Convert signed `n` / 1 to a fixed-point number. function toFixed(int256 n) internal pure returns (int256 f) { f = _mul(n, FIXED_1); } /// @dev Convert signed `n` / `d` to a fixed-point number. function toFixed(int256 n, int256 d) internal pure returns (int256 f) { f = _div(_mul(n, FIXED_1), d); } /// @dev Convert unsigned `n` / 1 to a fixed-point number. /// Reverts if `n` is too large to fit in a fixed-point number. function toFixed(uint256 n) internal pure returns (int256 f) { if (int256(n) < int256(0)) { revert("out-of-bounds"); } f = _mul(int256(n), FIXED_1); } /// @dev Convert unsigned `n` / `d` to a fixed-point number. /// Reverts if `n` / `d` is too large to fit in a fixed-point number. function toFixed(uint256 n, uint256 d) internal pure returns (int256 f) { if (int256(n) < int256(0)) { revert("out-of-bounds"); } if (int256(d) < int256(0)) { revert("out-of-bounds"); } f = _div(_mul(int256(n), FIXED_1), int256(d)); } /// @dev Convert a fixed-point number to an integer. function toInteger(int256 f) internal pure returns (int256 n) { return f / FIXED_1; } /// @dev Get the natural logarithm of a fixed-point number 0 < `x` <= LN_MAX_VAL function ln(int256 x) internal pure returns (int256 r) { if (x > LN_MAX_VAL) { revert("out-of-bounds"); } if (x <= 0) { revert("too-small"); } if (x == FIXED_1) { return 0; } if (x <= LN_MIN_VAL) { return EXP_MIN_VAL; } int256 y; int256 z; int256 w; // Rewrite the input as a quotient of negative natural exponents and a single residual q, such that 1 < q < 2 // For example: log(0.3) = log(e^-1 * e^-0.25 * 1.0471028872385522) // = 1 - 0.25 - log(1 + 0.0471028872385522) // e ^ -32 if (x <= int256(0x00000000000000000000000000000000000000000001c8464f76164760000000)) { r -= int256(0x0000000000000000000000000000001000000000000000000000000000000000); // - 32 x = (x * FIXED_1) / int256(0x00000000000000000000000000000000000000000001c8464f76164760000000); // / e ^ -32 } // e ^ -16 if (x <= int256(0x00000000000000000000000000000000000000f1aaddd7742e90000000000000)) { r -= int256(0x0000000000000000000000000000000800000000000000000000000000000000); // - 16 x = (x * FIXED_1) / int256(0x00000000000000000000000000000000000000f1aaddd7742e90000000000000); // / e ^ -16 } // e ^ -8 if (x <= int256(0x00000000000000000000000000000000000afe10820813d78000000000000000)) { r -= int256(0x0000000000000000000000000000000400000000000000000000000000000000); // - 8 x = (x * FIXED_1) / int256(0x00000000000000000000000000000000000afe10820813d78000000000000000); // / e ^ -8 } // e ^ -4 if (x <= int256(0x0000000000000000000000000000000002582ab704279ec00000000000000000)) { r -= int256(0x0000000000000000000000000000000200000000000000000000000000000000); // - 4 x = (x * FIXED_1) / int256(0x0000000000000000000000000000000002582ab704279ec00000000000000000); // / e ^ -4 } // e ^ -2 if (x <= int256(0x000000000000000000000000000000001152aaa3bf81cc000000000000000000)) { r -= int256(0x0000000000000000000000000000000100000000000000000000000000000000); // - 2 x = (x * FIXED_1) / int256(0x000000000000000000000000000000001152aaa3bf81cc000000000000000000); // / e ^ -2 } // e ^ -1 if (x <= int256(0x000000000000000000000000000000002f16ac6c59de70000000000000000000)) { r -= int256(0x0000000000000000000000000000000080000000000000000000000000000000); // - 1 x = (x * FIXED_1) / int256(0x000000000000000000000000000000002f16ac6c59de70000000000000000000); // / e ^ -1 } // e ^ -0.5 if (x <= int256(0x000000000000000000000000000000004da2cbf1be5828000000000000000000)) { r -= int256(0x0000000000000000000000000000000040000000000000000000000000000000); // - 0.5 x = (x * FIXED_1) / int256(0x000000000000000000000000000000004da2cbf1be5828000000000000000000); // / e ^ -0.5 } // e ^ -0.25 if (x <= int256(0x0000000000000000000000000000000063afbe7ab2082c000000000000000000)) { r -= int256(0x0000000000000000000000000000000020000000000000000000000000000000); // - 0.25 x = (x * FIXED_1) / int256(0x0000000000000000000000000000000063afbe7ab2082c000000000000000000); // / e ^ -0.25 } // e ^ -0.125 if (x <= int256(0x0000000000000000000000000000000070f5a893b608861e1f58934f97aea57d)) { r -= int256(0x0000000000000000000000000000000010000000000000000000000000000000); // - 0.125 x = (x * FIXED_1) / int256(0x0000000000000000000000000000000070f5a893b608861e1f58934f97aea57d); // / e ^ -0.125 } // `x` is now our residual in the range of 1 <= x <= 2 (or close enough). // Add the taylor series for log(1 + z), where z = x - 1 z = y = x - FIXED_1; w = (y * y) / FIXED_1; r += (z * (0x100000000000000000000000000000000 - y)) / 0x100000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^01 / 01 - y^02 / 02 r += (z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y)) / 0x200000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^03 / 03 - y^04 / 04 r += (z * (0x099999999999999999999999999999999 - y)) / 0x300000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^05 / 05 - y^06 / 06 r += (z * (0x092492492492492492492492492492492 - y)) / 0x400000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^07 / 07 - y^08 / 08 r += (z * (0x08e38e38e38e38e38e38e38e38e38e38e - y)) / 0x500000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^09 / 09 - y^10 / 10 r += (z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y)) / 0x600000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^11 / 11 - y^12 / 12 r += (z * (0x089d89d89d89d89d89d89d89d89d89d89 - y)) / 0x700000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^13 / 13 - y^14 / 14 r += (z * (0x088888888888888888888888888888888 - y)) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16 } /// @dev Compute the natural exponent for a fixed-point number EXP_MIN_VAL <= `x` <= 1 function exp(int256 x) internal pure returns (int256 r) { if (x < EXP_MIN_VAL) { // Saturate to zero below EXP_MIN_VAL. return 0; } if (x == 0) { return FIXED_1; } if (x > EXP_MAX_VAL) { revert("out-of-bounds"); } // Rewrite the input as a product of natural exponents and a // single residual q, where q is a number of small magnitude. // For example: e^-34.419 = e^(-32 - 2 - 0.25 - 0.125 - 0.044) // = e^-32 * e^-2 * e^-0.25 * e^-0.125 * e^-0.044 // -> q = -0.044 // Multiply with the taylor series for e^q int256 y; int256 z; // q = x % 0.125 (the residual) z = y = x % 0x0000000000000000000000000000000010000000000000000000000000000000; z = (z * y) / FIXED_1; r += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = (z * y) / FIXED_1; r += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = (z * y) / FIXED_1; r += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = (z * y) / FIXED_1; r += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = (z * y) / FIXED_1; r += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = (z * y) / FIXED_1; r += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = (z * y) / FIXED_1; r += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = (z * y) / FIXED_1; r += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = (z * y) / FIXED_1; r += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = (z * y) / FIXED_1; r += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = (z * y) / FIXED_1; r += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = (z * y) / FIXED_1; r += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = (z * y) / FIXED_1; r += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = (z * y) / FIXED_1; r += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = (z * y) / FIXED_1; r += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = (z * y) / FIXED_1; r += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = (z * y) / FIXED_1; r += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = (z * y) / FIXED_1; r += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = (z * y) / FIXED_1; r += z * 0x0000000000000001; // add y^20 * (20! / 20!) r = r / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! // Multiply with the non-residual terms. x = -x; // e ^ -32 if ((x & int256(0x0000000000000000000000000000001000000000000000000000000000000000)) != 0) { r = (r * int256(0x00000000000000000000000000000000000000f1aaddd7742e56d32fb9f99744)) / int256(0x0000000000000000000000000043cbaf42a000812488fc5c220ad7b97bf6e99e); // * e ^ -32 } // e ^ -16 if ((x & int256(0x0000000000000000000000000000000800000000000000000000000000000000)) != 0) { r = (r * int256(0x00000000000000000000000000000000000afe10820813d65dfe6a33c07f738f)) / int256(0x000000000000000000000000000005d27a9f51c31b7c2f8038212a0574779991); // * e ^ -16 } // e ^ -8 if ((x & int256(0x0000000000000000000000000000000400000000000000000000000000000000)) != 0) { r = (r * int256(0x0000000000000000000000000000000002582ab704279e8efd15e0265855c47a)) / int256(0x0000000000000000000000000000001b4c902e273a58678d6d3bfdb93db96d02); // * e ^ -8 } // e ^ -4 if ((x & int256(0x0000000000000000000000000000000200000000000000000000000000000000)) != 0) { r = (r * int256(0x000000000000000000000000000000001152aaa3bf81cb9fdb76eae12d029571)) / int256(0x00000000000000000000000000000003b1cc971a9bb5b9867477440d6d157750); // * e ^ -4 } // e ^ -2 if ((x & int256(0x0000000000000000000000000000000100000000000000000000000000000000)) != 0) { r = (r * int256(0x000000000000000000000000000000002f16ac6c59de6f8d5d6f63c1482a7c86)) / int256(0x000000000000000000000000000000015bf0a8b1457695355fb8ac404e7a79e3); // * e ^ -2 } // e ^ -1 if ((x & int256(0x0000000000000000000000000000000080000000000000000000000000000000)) != 0) { r = (r * int256(0x000000000000000000000000000000004da2cbf1be5827f9eb3ad1aa9866ebb3)) / int256(0x00000000000000000000000000000000d3094c70f034de4b96ff7d5b6f99fcd8); // * e ^ -1 } // e ^ -0.5 if ((x & int256(0x0000000000000000000000000000000040000000000000000000000000000000)) != 0) { r = (r * int256(0x0000000000000000000000000000000063afbe7ab2082ba1a0ae5e4eb1b479dc)) / int256(0x00000000000000000000000000000000a45af1e1f40c333b3de1db4dd55f29a7); // * e ^ -0.5 } // e ^ -0.25 if ((x & int256(0x0000000000000000000000000000000020000000000000000000000000000000)) != 0) { r = (r * int256(0x0000000000000000000000000000000070f5a893b608861e1f58934f97aea57d)) / int256(0x00000000000000000000000000000000910b022db7ae67ce76b441c27035c6a1); // * e ^ -0.25 } // e ^ -0.125 if ((x & int256(0x0000000000000000000000000000000010000000000000000000000000000000)) != 0) { r = (r * int256(0x00000000000000000000000000000000783eafef1c0a8f3978c7f81824d62ebf)) / int256(0x0000000000000000000000000000000088415abbe9a76bead8d00cf112e4d4a8); // * e ^ -0.125 } } /// @dev Returns the multiplication two numbers, reverting on overflow. function _mul(int256 a, int256 b) private pure returns (int256 c) { if (a == 0) { return 0; } c = a * b; if (c / a != b || c / b != a) { revert("overflow"); } } /// @dev Returns the division of two numbers, reverting on division by zero. function _div(int256 a, int256 b) private pure returns (int256 c) { if (b == 0) { revert("overflow"); } if (a == MIN_FIXED_VAL && b == -1) { revert("overflow"); } c = a / b; } /// @dev Adds two numbers, reverting on overflow. function _add(int256 a, int256 b) private pure returns (int256 c) { c = a + b; if ((a < 0 && b < 0 && c > a) || (a > 0 && b > 0 && c < a)) { revert("overflow"); } } }
@dev Returns the multiplication two numbers, reverting on overflow.
function _mul(int256 a, int256 b) private pure returns (int256 c) { if (a == 0) { return 0; } c = a * b; if (c / a != b || c / b != a) { revert("overflow"); } }
573,599
[ 1, 1356, 326, 23066, 2795, 5600, 16, 15226, 310, 603, 9391, 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 ]
[ 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, 389, 16411, 12, 474, 5034, 279, 16, 509, 5034, 324, 13, 3238, 16618, 1135, 261, 474, 5034, 276, 13, 288, 203, 3639, 309, 261, 69, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 3639, 276, 273, 279, 380, 324, 31, 203, 3639, 309, 261, 71, 342, 279, 480, 324, 747, 276, 342, 324, 480, 279, 13, 288, 203, 5411, 15226, 2932, 11512, 8863, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x3c1164531d5857029ae5412E49999306547834d8/sources/contracts/implementations/abstract/RMRKAbstractEquippableMP.sol
* @inheritdoc RMRKRoyalties/
function updateRoyaltyRecipient( address newRoyaltyRecipient ) public virtual override onlyOwner { _setRoyaltyRecipient(newRoyaltyRecipient); }
9,657,864
[ 1, 36, 10093, 534, 23464, 47, 54, 13372, 2390, 606, 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, 1089, 54, 13372, 15006, 18241, 12, 203, 3639, 1758, 394, 54, 13372, 15006, 18241, 203, 565, 262, 1071, 5024, 3849, 1338, 5541, 288, 203, 3639, 389, 542, 54, 13372, 15006, 18241, 12, 2704, 54, 13372, 15006, 18241, 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 ]
./partial_match/3/0x82077fA81900A0be19C18D1e0BA5f011E7C0bAe4/sources/testEventonRegister.sol
This is the constructor whose code is run only when the contract is created.
{ address payable public Owner; event onRegister( uint date, address indexed From, address indexed To, uint256 amount, string InputData ); constructor() public payable { Owner = msg.sender; } function GetOwner() public view returns(address) { return Owner; } function Register(string memory InputData) public payable { emit onRegister(now,msg.sender,Owner,msg.value,InputData); } }
5,271,497
[ 1, 2503, 353, 326, 3885, 8272, 981, 353, 1086, 1338, 1347, 326, 6835, 353, 2522, 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, 95, 203, 565, 1758, 8843, 429, 1071, 16837, 31, 203, 377, 203, 565, 871, 603, 3996, 12, 203, 3639, 2254, 1509, 16, 203, 3639, 1758, 8808, 6338, 16, 203, 3639, 1758, 8808, 2974, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 4202, 533, 2741, 751, 203, 565, 11272, 203, 377, 203, 565, 3885, 1435, 1071, 8843, 429, 288, 203, 3639, 16837, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 377, 203, 565, 445, 968, 5541, 1435, 1071, 1476, 1135, 12, 2867, 13, 203, 565, 288, 203, 3639, 327, 16837, 31, 203, 565, 289, 203, 377, 203, 377, 203, 565, 445, 5433, 12, 1080, 3778, 2741, 751, 13, 1071, 8843, 429, 7010, 565, 288, 203, 3639, 3626, 603, 3996, 12, 3338, 16, 3576, 18, 15330, 16, 5541, 16, 3576, 18, 1132, 16, 1210, 751, 1769, 203, 565, 289, 203, 377, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; // import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ReentrancyGuard.sol"; // PolkaBridgeFarm is the master of PolkaBridge. He can make PolkaBridge and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once PBR is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract PolkaBridgeFarm is Ownable, ReentrancyGuard { using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of PBRs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accPBRPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accPBRPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 lpAmount; // LP token amount in the pool. uint256 allocPoint; // How many allocation points assigned to this pool. PBRs to distribute per block. uint256 lastRewardBlock; // Last block number that PBRs distribution occurs. uint256 accPBRPerShare; // Accumulated PBRs per share, times 1e18. See below. } // The PBR TOKEN! address public polkaBridge; // PBR tokens created per block. uint256 public PBRPerBlock; // Bonus muliplier for early polkaBridge makers. uint256 public constant BONUS_MULTIPLIER = 1; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when PBR mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, bool withUpdate); event LogSetPool(uint256 indexed pid, uint256 allocPoint, bool withUpdate); event LogUpdatePool(uint256 indexed pid, uint256 lastRewardBlock, uint256 lpSupply, uint256 accPBRPerShare); constructor( address _polkaBridge, uint256 _PBRPerBlock, uint256 _startBlock ) { polkaBridge = _polkaBridge; PBRPerBlock = _PBRPerBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } function changePBRBlock(uint256 _PBRPerBlock) external onlyOwner { PBRPerBlock = _PBRPerBlock; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + _allocPoint; poolInfo.push( PoolInfo({ lpToken: _lpToken, lpAmount: 0, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accPBRPerShare: 0 }) ); emit LogPoolAddition(poolInfo.length - 1, _allocPoint, _lpToken, _withUpdate); } // Update the given pool's PBR allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { if(_withUpdate) { massUpdatePools(); } else { updatePool(_pid); } totalAllocPoint = totalAllocPoint - poolInfo[_pid].allocPoint + _allocPoint; poolInfo[_pid].allocPoint = _allocPoint; emit LogSetPool(_pid, _allocPoint, _withUpdate); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { return _to - _from * BONUS_MULTIPLIER; } // View function to see pending PBRs on frontend. function pendingPBR(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accPBRPerShare = pool.accPBRPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 PBRReward = multiplier * PBRPerBlock * pool.allocPoint / totalAllocPoint; accPBRPerShare = accPBRPerShare + PBRReward * 1e18 / lpSupply; } return user.amount * accPBRPerShare / 1e18 - user.rewardDebt; } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 PBRReward = multiplier * PBRPerBlock * pool.allocPoint / totalAllocPoint; pool.accPBRPerShare = pool.accPBRPerShare + PBRReward * 1e18 / lpSupply; pool.lastRewardBlock = block.number; emit LogUpdatePool(_pid, pool.lastRewardBlock, lpSupply, pool.accPBRPerShare); } // Harvest function harvest(uint256 _pid) external nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount * pool.accPBRPerShare / 1e18 - user.rewardDebt; IERC20(polkaBridge).safeTransfer(msg.sender, pending); } // pool.lpToken.safeTransferFrom( // address(msg.sender), // address(this), // _amount // ); // user.amount = user.amount + _amount; user.rewardDebt = user.amount * pool.accPBRPerShare / 1e18; // emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to PolkaBridgeFarm for PBR allocation. function deposit(uint256 _pid, uint256 _amount) external nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount * pool.accPBRPerShare / 1e18 - user.rewardDebt; IERC20(polkaBridge).safeTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount + _amount; pool.lpAmount = pool.lpAmount + _amount; user.rewardDebt = user.amount * pool.accPBRPerShare / 1e18; emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from PolkaBridgeFarm. function withdraw(uint256 _pid, uint256 _amount) external nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount * pool.accPBRPerShare / 1e18 - user.rewardDebt; IERC20(polkaBridge).safeTransfer(msg.sender, pending); user.amount = user.amount - _amount; pool.lpAmount = pool.lpAmount - _amount; user.rewardDebt = user.amount * pool.accPBRPerShare / 1e18; pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); pool.lpAmount = pool.lpAmount - user.amount; user.amount = 0; user.rewardDebt = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; abstract contract ReentrancyGuard { 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 make 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; } } // SPDX-License-Identifier: MIT 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; } } // SPDX-License-Identifier: MIT pragma solidity ^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; 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"); (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); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.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"); } } } // SPDX-License-Identifier: MIT 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 `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: MIT pragma solidity ^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() { _setOwner(_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 { _setOwner(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"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
Withdraw LP tokens from PolkaBridgeFarm.
function withdraw(uint256 _pid, uint256 _amount) external nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount * pool.accPBRPerShare / 1e18 - user.rewardDebt; IERC20(polkaBridge).safeTransfer(msg.sender, pending); user.amount = user.amount - _amount; pool.lpAmount = pool.lpAmount - _amount; user.rewardDebt = user.amount * pool.accPBRPerShare / 1e18; pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); }
1,146,461
[ 1, 1190, 9446, 511, 52, 2430, 628, 6730, 7282, 13691, 42, 4610, 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 ]
[ 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, 598, 9446, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 3903, 1661, 426, 8230, 970, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 3576, 18, 15330, 15533, 203, 3639, 2583, 12, 1355, 18, 8949, 1545, 389, 8949, 16, 315, 1918, 9446, 30, 486, 7494, 8863, 203, 3639, 1089, 2864, 24899, 6610, 1769, 203, 3639, 2254, 5034, 4634, 273, 729, 18, 8949, 380, 2845, 18, 8981, 52, 7192, 2173, 9535, 342, 404, 73, 2643, 300, 729, 18, 266, 2913, 758, 23602, 31, 203, 3639, 467, 654, 39, 3462, 12, 3915, 7282, 13691, 2934, 4626, 5912, 12, 3576, 18, 15330, 16, 4634, 1769, 203, 3639, 729, 18, 8949, 273, 729, 18, 8949, 300, 389, 8949, 31, 203, 3639, 2845, 18, 9953, 6275, 273, 2845, 18, 9953, 6275, 300, 389, 8949, 31, 203, 3639, 729, 18, 266, 2913, 758, 23602, 273, 729, 18, 8949, 380, 2845, 18, 8981, 52, 7192, 2173, 9535, 342, 404, 73, 2643, 31, 203, 3639, 2845, 18, 9953, 1345, 18, 4626, 5912, 12, 2867, 12, 3576, 18, 15330, 3631, 389, 8949, 1769, 203, 3639, 3626, 3423, 9446, 12, 3576, 18, 15330, 16, 389, 6610, 16, 389, 8949, 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 ]
pragma solidity ^0.4.24; 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&#39;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 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(); } } contract BattleBase is Ownable { using SafeMath for uint256; /***********************************************************************************/ /* EVENTS /***********************************************************************************/ /** * History sequence will be represented by uint256, in other words the max round is 256 (rounds more than this will decide on hp left or draw) * 1 is challenger attack * 2 is defender attack * 3 is challenger attack with critical * 4 is defender attack with critical */ event BattleHistory( uint256 historyId, uint8 winner, // 0 - challenger; 1 - defender; 2 - draw; uint64 battleTime, uint256 sequence, uint256 blockNumber, uint256 tokensGained); event BattleHistoryChallenger( uint256 historyId, uint256 cardId, uint8 element, uint16 level, uint32 attack, uint32 defense, uint32 hp, uint32 speed, uint32 criticalRate, uint256 rank); event BattleHistoryDefender( uint256 historyId, uint256 cardId, uint8 element, uint16 level, uint32 attack, uint32 defense, uint32 hp, uint32 speed, uint16 criticalRate, uint256 rank); event RejectChallenge( uint256 challengerId, uint256 defenderId, uint256 defenderRank, uint8 rejectCode, uint256 blockNumber); event HashUpdated( uint256 cardId, uint256 cardHash); event LevelUp(uint256 cardId); event CardCreated(address owner, uint256 cardId); /***********************************************************************************/ /* CONST DATA /***********************************************************************************/ uint32[] expToNextLevelArr = [0,103,103,207,207,207,414,414,414,414,724,724,724,828,828,931,931,1035,1035,1138,1138,1242,1242,1345,1345,1449,1449,1552,1552,1656,1656,1759,1759,1863,1863,1966,1966,2070,2070,2173,2173,2173,2277,2277,2380,2380,2484,2484,2587,2587,2691,2691,2794,2794,2898,2898,3001,3001,3105,3105,3208,3208,3312,3312,3415,3415,3519,3519,3622,3622,3622,3726,3726,3829,3829,3933,3933,4036,4036,4140,4140,4243,4243,4347,4347,4450,4450,4554,4554,4657,4657,4761,4761,4864,4864,4968,4968,5071,5071,5175]; uint32[] activeWinExp = [10,11,14,19,26,35,46,59,74,91,100,103,108,116,125,135,146,158,171,185,200,215,231,248,265,283,302,321,341,361,382]; /***********************************************************************************/ /* DATA VARIABLES /***********************************************************************************/ //Card structure that holds all information for battle struct Card { uint8 element; // 1 - fire; 2 - water; 3 - wood; 8 - light; 9 - dark; uint16 level; //"unlimited" level bound to uint16 Max level is 65535 uint32 attack; uint32 defense; uint32 hp; uint32 speed; uint16 criticalRate; //max 8000 uint32 flexiGems; uint256 cardHash; uint32 currentExp; uint32 expToNextLevel; uint64 createdDatetime; uint256 rank; //rank is n-1 (need to add 1 for display); //uint8 passiveSkill; //TBC } // Mapping from tokenId to Card Struct mapping (uint256 => Card) public cards; uint256[] ranking; //stores the token id according to array position starts from 0 (rank 1) // Mapping from rank to amount held in that rank (challenge tokens) mapping (uint256 => uint256) public rankTokens; uint8 public currentElement = 0; //start with 0 as +1 will become fire uint256 public historyId = 0; /***********************************************************************************/ /* CONFIGURATIONS /***********************************************************************************/ /// @dev The address of the HogSmashToken HogSmashToken public hogsmashToken; /// @dev The address of the Marketplace Marketplace public marketplace; // Challenge fee changes on ranking difference uint256 public challengeFee; // Upgrade fee uint256 public upgradeFee; // Avatar fee uint256 public avatarFee; // Referrer fee in % (x10000) uint256 public referrerFee; // Developer Cut in % (x10000) uint256 public developerCut; uint256 internal totalDeveloperCut; // Price for each card draw (in wei) uint256 public cardDrawPrice; // Gems provided for upgrade every level up uint8 public upgradeGems; // // Gems provided for upgrade every 10 level up uint8 public upgradeGemsSpecial; // 1 Gem to attack conversion uint16 public gemAttackConversion; // 1 Gem to defense conversion uint16 public gemDefenseConversion; // 1 Gem to hp conversion uint16 public gemHpConversion; // 1 Gem to speed conversion uint16 public gemSpeedConversion; // 1 Gem to critical rate conversion divided by 100, eg 25 = 0.25 uint16 public gemCriticalRateConversion; //% to get a gold card, 0 to 100 uint8 public goldPercentage; //% to get a silver card, 0 to 100 uint8 public silverPercentage; //Range of event card number 1-99999999 uint32 public eventCardRangeMin; //Range of event card number 1-99999999 uint32 public eventCardRangeMax; // Maximum rounds of battle, cannot exceed 128 uint8 public maxBattleRounds; // // Record how much tokens are held as rank tokens uint256 internal totalRankTokens; // Flag for start fighting bool internal battleStart; //Flag for starter pack sale bool internal starterPackOnSale; uint256 public starterPackPrice; //price of starter pack uint16 public starterPackCardLevel; //card level from starter pack /***********************************************************************************/ /* ADMIN FUNCTIONS FOR SETTING CONFIGS /***********************************************************************************/ /// @dev Sets the reference to the marketplace. /// @param _address - Address of marketplace. function setMarketplaceAddress(address _address) external onlyOwner { Marketplace candidateContract = Marketplace(_address); require(candidateContract.isMarketplace(),"needs to be marketplace"); // Set the new contract address marketplace = candidateContract; } /** * @dev set upgrade gems for each level up and each 10 level up * @param _upgradeGems upgrade gems for normal levels * @param _upgradeGemsSpecial upgrade gems for every n levels * @param _gemAttackConversion gem to attack conversion * @param _gemDefenseConversion gem to defense conversion * @param _gemHpConversion gem to hp conversion * @param _gemSpeedConversion gem to speed conversion * @param _gemCriticalRateConversion gem to critical rate conversion * @param _goldPercentage percentage to get gold card * @param _silverPercentage percentage to get silver card * @param _eventCardRangeMin event card hash range start (inclusive) * @param _eventCardRangeMax event card hash range end (inclusive) * @param _newMaxBattleRounds maximum battle rounds */ function setSettingValues( uint8 _upgradeGems, uint8 _upgradeGemsSpecial, uint16 _gemAttackConversion, uint16 _gemDefenseConversion, uint16 _gemHpConversion, uint16 _gemSpeedConversion, uint16 _gemCriticalRateConversion, uint8 _goldPercentage, uint8 _silverPercentage, uint32 _eventCardRangeMin, uint32 _eventCardRangeMax, uint8 _newMaxBattleRounds) external onlyOwner { require(_eventCardRangeMax >= _eventCardRangeMin, "range max must be larger or equals range min" ); require(_eventCardRangeMax<100000000, "range max cannot exceed 99999999"); require((_newMaxBattleRounds <= 128) && (_newMaxBattleRounds >0), "battle rounds must be between 0 and 128"); upgradeGems = _upgradeGems; upgradeGemsSpecial = _upgradeGemsSpecial; gemAttackConversion = _gemAttackConversion; gemDefenseConversion = _gemDefenseConversion; gemHpConversion = _gemHpConversion; gemSpeedConversion = _gemSpeedConversion; gemCriticalRateConversion = _gemCriticalRateConversion; goldPercentage = _goldPercentage; silverPercentage = _silverPercentage; eventCardRangeMin = _eventCardRangeMin; eventCardRangeMax = _eventCardRangeMax; maxBattleRounds = _newMaxBattleRounds; } // @dev function to allow contract owner to change the price (in wei) per card draw function setStarterPack(uint256 _newStarterPackPrice, uint16 _newStarterPackCardLevel) external onlyOwner { require(_newStarterPackCardLevel<=20, "starter pack level cannot exceed 20"); //starter pack level cannot exceed 20 starterPackPrice = _newStarterPackPrice; starterPackCardLevel = _newStarterPackCardLevel; } // @dev function to allow contract owner to enable/disable starter pack sale function setStarterPackOnSale(bool _newStarterPackOnSale) external onlyOwner { starterPackOnSale = _newStarterPackOnSale; } // @dev function to allow contract owner to start/stop the battle function setBattleStart(bool _newBattleStart) external onlyOwner { battleStart = _newBattleStart; } // @dev function to allow contract owner to change the price (in wei) per card draw function setCardDrawPrice(uint256 _newCardDrawPrice) external onlyOwner { cardDrawPrice = _newCardDrawPrice; } // @dev function to allow contract owner to change the referrer fee (in %, eg 3.75% is 375) function setReferrerFee(uint256 _newReferrerFee) external onlyOwner { referrerFee = _newReferrerFee; } // @dev function to allow contract owner to change the challenge fee (in wei) function setChallengeFee(uint256 _newChallengeFee) external onlyOwner { challengeFee = _newChallengeFee; } // @dev function to allow contract owner to change the upgrade fee (in wei) function setUpgradeFee(uint256 _newUpgradeFee) external onlyOwner { upgradeFee = _newUpgradeFee; } // @dev function to allow contract owner to change the avatar fee (in wei) function setAvatarFee(uint256 _newAvatarFee) external onlyOwner { avatarFee = _newAvatarFee; } // @dev function to allow contract owner to change the developer cut (%) divide by 100 function setDeveloperCut(uint256 _newDeveloperCut) external onlyOwner { developerCut = _newDeveloperCut; } function getTotalDeveloperCut() external view onlyOwner returns (uint256) { return totalDeveloperCut; } function getTotalRankTokens() external view returns (uint256) { return totalRankTokens; } /***********************************************************************************/ /* GET SETTINGS FUNCTION /***********************************************************************************/ /** * @dev get upgrade gems and conversion ratios of each field * @return _upgradeGems upgrade gems for normal levels * @return _upgradeGemsSpecial upgrade gems for every n levels * @return _gemAttackConversion gem to attack conversion * @return _gemDefenseConversion gem to defense conversion * @return _gemHpConversion gem to hp conversion * @return _gemSpeedConversion gem to speed conversion * @return _gemCriticalRateConversion gem to critical rate conversion */ function getSettingValues() external view returns( uint8 _upgradeGems, uint8 _upgradeGemsSpecial, uint16 _gemAttackConversion, uint16 _gemDefenseConversion, uint16 _gemHpConversion, uint16 _gemSpeedConversion, uint16 _gemCriticalRateConversion, uint8 _maxBattleRounds) { _upgradeGems = uint8(upgradeGems); _upgradeGemsSpecial = uint8(upgradeGemsSpecial); _gemAttackConversion = uint16(gemAttackConversion); _gemDefenseConversion = uint16(gemDefenseConversion); _gemHpConversion = uint16(gemHpConversion); _gemSpeedConversion = uint16(gemSpeedConversion); _gemCriticalRateConversion = uint16(gemCriticalRateConversion); _maxBattleRounds = uint8(maxBattleRounds); } } /***********************************************************************************/ /* RANDOM GENERATOR /***********************************************************************************/ contract Random { uint private pSeed = block.number; function getRandom() internal returns(uint256) { return (pSeed = uint(keccak256(abi.encodePacked(pSeed, blockhash(block.number - 1), blockhash(block.number - 3), blockhash(block.number - 5), blockhash(block.number - 7)) ))); } } /***********************************************************************************/ /* CORE BATTLE CONTRACT /***********************************************************************************/ /** * Omits fallback to prevent accidentally sending ether to this contract */ contract Battle is BattleBase, Random, Pausable { /***********************************************************************************/ /* CONSTRUCTOR /***********************************************************************************/ // @dev Contructor for Battle Contract constructor(address _tokenAddress) public { HogSmashToken candidateContract = HogSmashToken(_tokenAddress); // Set the new contract address hogsmashToken = candidateContract; starterPackPrice = 30000000000000000; starterPackCardLevel = 5; starterPackOnSale = true; // start by selling starter pack challengeFee = 10000000000000000; upgradeFee = 10000000000000000; avatarFee = 50000000000000000; developerCut = 375; referrerFee = 2000; cardDrawPrice = 15000000000000000; battleStart = true; paused = false; //default contract paused totalDeveloperCut = 0; //init to 0 } /***********************************************************************************/ /* MODIFIER /***********************************************************************************/ /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(hogsmashToken.ownerOf(_tokenId) == msg.sender, "must be owner of token"); _; } /***********************************************************************************/ /* GAME FUNCTIONS /***********************************************************************************/ /** * @dev External function for getting info of card * @param _id card id of target query card * @return information of the card */ function getCard(uint256 _id) external view returns ( uint256 cardId, address owner, uint8 element, uint16 level, uint32[] stats, uint32 currentExp, uint32 expToNextLevel, uint256 cardHash, uint64 createdDatetime, uint256 rank ) { cardId = _id; owner = hogsmashToken.ownerOf(_id); Card storage card = cards[_id]; uint32[] memory tempStats = new uint32[](6); element = uint8(card.element); level = uint16(card.level); tempStats[0] = uint32(card.attack); tempStats[1] = uint32(card.defense); tempStats[2] = uint32(card.hp); tempStats[3] = uint32(card.speed); tempStats[4] = uint16(card.criticalRate); tempStats[5] = uint32(card.flexiGems); stats = tempStats; currentExp = uint32(card.currentExp); expToNextLevel = uint32(card.expToNextLevel); cardHash = uint256(card.cardHash); createdDatetime = uint64(card.createdDatetime); rank = uint256(card.rank); } /** * @dev External function for querying card Id at rank (zero based) * @param _rank zero based rank of the card * @return id of the card at the rank */ function getCardIdByRank(uint256 _rank) external view returns(uint256 cardId) { return ranking[_rank]; } /** * @dev External function for drafting new card * @return uint of cardId */ function draftNewCard() external payable whenNotPaused returns (uint256) { require(msg.value == cardDrawPrice, "fee must be equal to draw price"); //make sure the fee is enough for drafting a new card` require(address(marketplace) != address(0), "marketplace not set"); //need to set up marketplace before drafting new cards is allowed hogsmashToken.setApprovalForAllByContract(msg.sender, marketplace, true); //let marketplace have approval for escrow if the card goes on sale totalDeveloperCut = totalDeveloperCut.add(cardDrawPrice); return _createCard(msg.sender, 1); //level 1 cards } /** * @dev External function for drafting new card * @return uint of cardId */ function draftNewCardWithReferrer(address referrer) external payable whenNotPaused returns (uint256 cardId) { require(msg.value == cardDrawPrice, "fee must be equal to draw price"); //make sure the fee is enough for drafting a new card` require(address(marketplace) != address(0), "marketplace not set"); //need to set up marketplace before drafting new cards is allowed hogsmashToken.setApprovalForAllByContract(msg.sender, marketplace, true); //let marketplace have approval for escrow if the card goes on sale cardId = _createCard(msg.sender, 1); //level 1 cards if ((referrer != address(0)) && (referrerFee!=0) && (referrer!=msg.sender) && (hogsmashToken.balanceOf(referrer)>0)) { uint256 referrerCut = msg.value.mul(referrerFee)/10000; require(referrerCut<=msg.value, "referre cut cannot be larger than fee"); referrer.transfer(referrerCut); totalDeveloperCut = totalDeveloperCut.add(cardDrawPrice.sub(referrerCut)); } else { totalDeveloperCut = totalDeveloperCut.add(cardDrawPrice); } } /** * @dev External function for leveling up * @param _id card id of target query card * @param _attackLevelUp gems allocated to each attribute for upgrade * @param _defenseLevelUp gems allocated to each attribute for upgrade * @param _hpLevelUp gems allocated to each attribute for upgrade * @param _speedLevelUp gems allocated to each attribute for upgrade * @param _criticalRateLevelUp gems allocated to each attribute for upgrade * @param _flexiGemsLevelUp are gems allocated to each attribute for upgrade */ function levelUp( uint256 _id, uint16 _attackLevelUp, uint16 _defenseLevelUp, uint16 _hpLevelUp, uint16 _speedLevelUp, uint16 _criticalRateLevelUp, uint16 _flexiGemsLevelUp) external payable whenNotPaused onlyOwnerOf(_id) { require( _attackLevelUp >= 0 && _defenseLevelUp >= 0 && _hpLevelUp >= 0 && _speedLevelUp >= 0 && _criticalRateLevelUp >= 0 && _flexiGemsLevelUp >= 0, "level up attributes must be more than 0" ); //make sure all upgrade attributes will not be negative require(msg.value == upgradeFee, "fee must be equals to upgrade price"); //make sure the fee is enough for upgrade Card storage card = cards[_id]; require(card.currentExp==card.expToNextLevel, "exp is not max yet for level up"); //reject if currentexp not maxed out require(card.level < 65535, "card level maximum has reached"); //make sure level is not maxed out, although not likely require((card.criticalRate + (_criticalRateLevelUp * gemCriticalRateConversion))<=7000, "critical rate max of 70 has reached"); //make sure criticalrate is not upgraded when it reaches 70 to prevent waste uint totalInputGems = _attackLevelUp + _defenseLevelUp + _hpLevelUp; totalInputGems += _speedLevelUp + _criticalRateLevelUp + _flexiGemsLevelUp; uint16 numOfSpecials = 0; //Cater for initial high level cards but have not leveled up before if ((card.level > 1) && (card.attack==1) && (card.defense==1) && (card.hp==3) && (card.speed==1) && (card.criticalRate==25) && (card.flexiGems==1)) { numOfSpecials = (card.level+1)/5; //auto floor to indicate how many Ns for upgradeGemsSpecial; cardlevel +1 is the new level uint totalGems = (numOfSpecials * upgradeGemsSpecial) + (((card.level) - numOfSpecials) * upgradeGems); require(totalInputGems==totalGems, "upgrade gems not used up"); //must use up all gems when upgrade } else { if (((card.level+1)%5)==0) { //special gem every 5 levels require(totalInputGems==upgradeGemsSpecial, "upgrade gems not used up"); //must use up all gems when upgrade numOfSpecials = 1; } else { require(totalInputGems==upgradeGems, "upgrade gems not used up"); //must use up all gems when upgrade } } totalDeveloperCut = totalDeveloperCut.add(upgradeFee); //start level up process _upgradeLevel(_id, _attackLevelUp, _defenseLevelUp, _hpLevelUp, _speedLevelUp, _criticalRateLevelUp, _flexiGemsLevelUp, numOfSpecials); emit LevelUp(_id); } function _upgradeLevel( uint256 _id, uint16 _attackLevelUp, uint16 _defenseLevelUp, uint16 _hpLevelUp, uint16 _speedLevelUp, uint16 _criticalRateLevelUp, uint16 _flexiGemsLevelUp, uint16 numOfSpecials) private { Card storage card = cards[_id]; uint16[] memory extraStats = new uint16[](5); //attack, defense, hp, speed, flexigem if (numOfSpecials>0) { //special gem every 5 levels if (card.cardHash%100 >= 70) { //6* or 7* cards uint cardType = (uint(card.cardHash/10000000000))%100; //0-99 if (cardType < 20) { extraStats[0]+=numOfSpecials; } else if (cardType < 40) { extraStats[1]+=numOfSpecials; } else if (cardType < 60) { extraStats[2]+=numOfSpecials; } else if (cardType < 80) { extraStats[3]+=numOfSpecials; } else { extraStats[4]+=numOfSpecials; } if (card.cardHash%100 >=90) { //7* cards uint cardTypeInner = cardType%10; //0-9 if (cardTypeInner < 2) { extraStats[0]+=numOfSpecials; } else if (cardTypeInner < 4) { extraStats[1]+=numOfSpecials; } else if (cardTypeInner < 6) { extraStats[2]+=numOfSpecials; } else if (cardTypeInner < 8) { extraStats[3]+=numOfSpecials; } else { extraStats[4]+=numOfSpecials; } } } } card.attack += (_attackLevelUp + extraStats[0]) * gemAttackConversion; card.defense += (_defenseLevelUp + extraStats[1]) * gemDefenseConversion; card.hp += (_hpLevelUp + extraStats[2]) * gemHpConversion; card.speed += (_speedLevelUp + extraStats[3]) * gemSpeedConversion; card.criticalRate += uint16(_criticalRateLevelUp * gemCriticalRateConversion); card.flexiGems += _flexiGemsLevelUp + extraStats[4]; // turn Gem into FlexiGem card.level += 1; //level + 1 card.currentExp = 0; //reset exp //card.expToNextLevel = card.level*100 + max(0,card.level-8) * (1045/1000)**card.level; uint256 tempExpLevel = card.level; if (tempExpLevel > expToNextLevelArr.length) { tempExpLevel = expToNextLevelArr.length; //cap it at max level exp } card.expToNextLevel = expToNextLevelArr[tempExpLevel]; } function max(uint a, uint b) private pure returns (uint) { return a > b ? a : b; } function challenge( uint256 _challengerCardId, uint32[5] _statUp, //0-attack, 1-defense, 2-hp, 3-speed, 4-criticalrate uint256 _defenderCardId, uint256 _defenderRank, uint16 _defenderLevel) external payable whenNotPaused onlyOwnerOf(_challengerCardId) { require(battleStart != false, "battle has not started"); //make sure the battle has started require(msg.sender != hogsmashToken.ownerOf(_defenderCardId), "cannot challenge own cards"); //make sure user doesn&#39;t attack his own cards Card storage challenger = cards[_challengerCardId]; require((_statUp[0] + _statUp[1] + _statUp[2] + _statUp[3] + _statUp[4])==challenger.flexiGems, "flexi gems not used up"); //flexi points must be exactly used, not more not less Card storage defender = cards[_defenderCardId]; if (defender.rank != _defenderRank) { emit RejectChallenge(_challengerCardId, _defenderCardId, _defenderRank, 1, uint256(block.number)); (msg.sender).transfer(msg.value); return; } if (defender.level != _defenderLevel) { emit RejectChallenge(_challengerCardId, _defenderCardId, _defenderRank, 2, uint256(block.number)); (msg.sender).transfer(msg.value); return; } uint256 requiredChallengeFee = challengeFee; if (defender.rank <150) { //0-149 rank within 150 requiredChallengeFee = requiredChallengeFee.mul(2); } require(msg.value == requiredChallengeFee, "fee must be equals to challenge price"); //challenge fee to challenge defender uint256 developerFee = 0; if (msg.value > 0) { developerFee = _calculateFee(msg.value); } uint256[] memory stats = new uint256[](14); //challengerattack, challengerdefense, challengerhp, challengerspeed, challengercritical, defendercritical, defenderhp, finalWinner stats[0] = challenger.attack + (_statUp[0] * gemAttackConversion); stats[1] = challenger.defense + (_statUp[1] * gemDefenseConversion); stats[2] = challenger.hp + (_statUp[2] * gemHpConversion); stats[3] = challenger.speed + (_statUp[3] * gemSpeedConversion); stats[4] = challenger.criticalRate + (_statUp[4] * gemCriticalRateConversion); stats[5] = defender.criticalRate; stats[6] = defender.hp; stats[8] = challenger.hp + (_statUp[2] * gemHpConversion); //challenger hp for record purpose stats[9] = challenger.rank; //for looting stats[10] = defender.rank; //for looting stats[11] = 0; //tokensGained stats[12] = _challengerCardId; stats[13] = _defenderCardId; //check challenger critical rate if (stats[4]>7000) { stats[4] = 7000; //hard cap at 70 critical rate } //check defender critical rate if (stats[5]>7000) { stats[5] = 7000; //hard cap at 70 critical rate } // 1 - fire; 2 - water; 3 - wood; 8 - light; 9 - dark; if (((challenger.element-1) == defender.element) || ((challenger.element==1) && (defender.element==3)) || ((challenger.element==8) && (defender.element==9))) { stats[4] += 3000; //30% critical rate increase for challenger if (stats[4]>8000) { stats[4] = 8000; //hard cap at 80 critical rate for element advantage } } if (((defender.element-1) == challenger.element) || ((defender.element==1) && (challenger.element==3)) || ((defender.element==8) && (challenger.element==9))) { stats[5] += 3000; //30% critical rate increase for defender if (stats[5]>8000) { stats[5] = 8000; //hard cap at 80 critical rate for element advantage } } uint256 battleSequence = _simulateBattle(challenger, defender, stats); stats[11] = _transferFees(_challengerCardId, stats, developerFee); emit BattleHistory( historyId, uint8(stats[7]), uint64(now), uint256(battleSequence), uint256(block.number), uint256(stats[11]) ); emit BattleHistoryChallenger( historyId, uint256(_challengerCardId), uint8(challenger.element), uint16(challenger.level), uint32(stats[0]), uint32(stats[1]), uint32(stats[8]), uint32(stats[3]), uint16(stats[4]), //pretty sure trimming down the uint won&#39;t affect the number as max is just 80000 uint256(stats[9]) ); emit BattleHistoryDefender( historyId, uint256(_defenderCardId), uint8(defender.element), uint16(defender.level), uint32(defender.attack), uint32(defender.defense), uint32(defender.hp), uint32(defender.speed), uint16(stats[5]), uint256(stats[10]) ); historyId = historyId.add(1); //add one for next history } function _addBattleSequence(uint8 attackType, uint8 rounds, uint256 battleSequence) private pure returns (uint256) { // Assumed rounds 0-based; attackType is 0xB (B:0,1,2,3), i.e. the last 2 bits is the value with other bits zeros uint256 mask = 0x3; mask = ~(mask << 2*rounds); uint256 newSeq = battleSequence & mask; newSeq = newSeq | (uint256(attackType) << 2*rounds); return newSeq; } function _simulateBattle(Card storage challenger, Card storage defender, uint[] memory stats) private returns (uint256 battleSequence) { bool continueBattle = true; uint8 currentAttacker = 0; //0 challenger, 1 defender uint256 tempAttackStrength; uint8 battleRound = 0; if (!_isChallengerAttackFirst(stats[3], defender.speed)){ currentAttacker = 1; } while (continueBattle) { if (currentAttacker==0) { //challenger attack if (_rollCriticalDice() <= stats[4]){ tempAttackStrength = stats[0] * 2; //critical hit battleSequence = _addBattleSequence(2, battleRound, battleSequence); //move sequence to left and add record } else { tempAttackStrength = stats[0]; //normal hit battleSequence = _addBattleSequence(0, battleRound, battleSequence); //move sequence to left and add record } if (tempAttackStrength <= defender.defense) { tempAttackStrength = 1; //at least deduct 1 hp } else { tempAttackStrength -= defender.defense; } if (stats[6] <= tempAttackStrength) { stats[6] = 0; //do not let it overflow } else { stats[6] -= tempAttackStrength; //defender hp } currentAttacker = 1; //defender turn up next } else if (currentAttacker==1) { //defender attack if (_rollCriticalDice() <= stats[5]){ tempAttackStrength = defender.attack * 2; //critical hit battleSequence = _addBattleSequence(3, battleRound, battleSequence); //move sequence to left and add record } else { tempAttackStrength = defender.attack; //normal hit battleSequence = _addBattleSequence(1, battleRound, battleSequence); //move sequence to left and add record } if (tempAttackStrength <= stats[1]) { tempAttackStrength = 1; //at least deduct 1 hp } else { tempAttackStrength -= stats[1]; } if (stats[2] <= tempAttackStrength) { stats[2] = 0; //do not let it overflow } else { stats[2] -= tempAttackStrength; //challenger hp } currentAttacker = 0; //challenger turn up next } battleRound ++; if ((battleRound>=maxBattleRounds) || (stats[6]<=0) || (stats[2]<=0)){ continueBattle = false; //end battle } } uint32 challengerGainExp = 0; uint32 defenderGainExp = 0; //calculate Exp if (challenger.level == defender.level) { //challenging a same level card challengerGainExp = activeWinExp[10]; } else if (challenger.level > defender.level) { //challenging a lower level card if ((challenger.level - defender.level) >= 11) { challengerGainExp = 1; //defender too weak, grant only 1 exp } else { //challengerGainExp = (((1 + ((defender.level - challenger.level)/10))**2) + (1/10)) * baseExp; challengerGainExp = activeWinExp[10 + defender.level - challenger.level]; //0 - 9 } } else if (challenger.level < defender.level) { //challenging a higher level card //challengerGainExp = ((1 + ((defender.level - challenger.level)/10)**(3/2))) * baseExp; uint256 levelDiff = defender.level - challenger.level; if (levelDiff > 20) { levelDiff = 20; //limit level difference to 20 as max exp gain } challengerGainExp = activeWinExp[10+levelDiff]; } if (stats[2] == stats[6]) { //challenger hp = defender hp stats[7] = 2; //draw //No EXP when draw } else if (stats[2] > stats[6]) { //challenger hp > defender hp stats[7] = 0; //challenger wins if (defender.rank < challenger.rank) { //swap ranks ranking[defender.rank] = stats[12]; //update ranking table position ranking[challenger.rank] = stats[13]; //update ranking table position uint256 tempRank = defender.rank; defender.rank = challenger.rank; //update rank on card challenger.rank = tempRank; //update rank on card } //award Exp //active win challenger.currentExp += challengerGainExp; if (challenger.currentExp > challenger.expToNextLevel) { challenger.currentExp = challenger.expToNextLevel; //cap it at max exp for level up } //passive lose //defenderGainExp = challengerGainExp*35/100*30/100 + (5/10); defenderGainExp = ((challengerGainExp*105/100) + 5)/10; // 30% of 35% + round up if (defenderGainExp <= 0) { defenderGainExp = 1; //at least 1 Exp } defender.currentExp += defenderGainExp; if (defender.currentExp > defender.expToNextLevel) { defender.currentExp = defender.expToNextLevel; //cap it at max exp for level up } } else if (stats[6] > stats[2]) { //defender hp > challenger hp stats[7] = 1; //defender wins //award Exp //active lose uint32 tempChallengerGain = challengerGainExp*35/100; //35% of winning if (tempChallengerGain <= 0) { tempChallengerGain = 1; //at least 1 Exp } challenger.currentExp += tempChallengerGain; //35% of winning if (challenger.currentExp > challenger.expToNextLevel) { challenger.currentExp = challenger.expToNextLevel; //cap it at max exp for level up } //passive win defenderGainExp = challengerGainExp*30/100; if (defenderGainExp <= 0) { defenderGainExp = 1; //at least 1 Exp } defender.currentExp += defenderGainExp; if (defender.currentExp > defender.expToNextLevel) { defender.currentExp = defender.expToNextLevel; //cap it at max exp for level up } } return battleSequence; } function _transferFees(uint256 _challengerCardId, uint[] stats, uint256 developerFee) private returns (uint256 totalGained) { totalDeveloperCut = totalDeveloperCut.add(developerFee); uint256 remainFee = msg.value.sub(developerFee); //minus developer fee totalGained = 0; if (stats[7] == 1) { //challenger loses // put all of challenger fee in rankTokens (minus developerfee of course) rankTokens[stats[10]] = rankTokens[stats[10]].add(remainFee); totalRankTokens = totalRankTokens.add(remainFee); } else { //draw or challenger wins address challengerAddress = hogsmashToken.ownerOf(_challengerCardId); //get address of card owner if (stats[7] == 0) { //challenger wins if (stats[9] > stats[10]) { //challenging a higher ranking defender //1. get tokens from defender rank if defender rank is higher if (rankTokens[stats[10]] > 0) { totalGained = totalGained.add(rankTokens[stats[10]]); totalRankTokens = totalRankTokens.sub(rankTokens[stats[10]]); rankTokens[stats[10]] = 0; } //2. get self rank tokens if moved to higher rank if (rankTokens[stats[9]] > 0) { totalGained = totalGained.add(rankTokens[stats[9]]); totalRankTokens = totalRankTokens.sub(rankTokens[stats[9]]); rankTokens[stats[9]] = 0; } } else { //challenging a lower ranking defender if (stats[9]<50) { //rank 1-50 gets to get self rank tokens and lower rank (within 150) tokens if win if ((stats[10] < 150) && (rankTokens[stats[10]] > 0)) { // can get defender rank tokens if defender rank within top 150 (0-149) totalGained = totalGained.add(rankTokens[stats[10]]); totalRankTokens = totalRankTokens.sub(rankTokens[stats[10]]); rankTokens[stats[10]] = 0; } if ((stats[10] < 150) && (rankTokens[stats[9]] > 0)) { //can get self rank tokens if defender rank within top 150 totalGained = totalGained.add(rankTokens[stats[9]]); totalRankTokens = totalRankTokens.sub(rankTokens[stats[9]]); rankTokens[stats[9]] = 0; } } } challengerAddress.transfer(totalGained.add(remainFee)); //give back challenge fee untouched + total gained } else { //draw challengerAddress.transfer(remainFee); //give back challenge fee untouched } } } function _rollCriticalDice() private returns (uint16 result){ return uint16((getRandom() % 10000) + 1); //get 1 to 10000 } function _isChallengerAttackFirst(uint _challengerSpeed, uint _defenderSpeed ) private returns (bool){ uint8 randResult = uint8((getRandom() % 100) + 1); //get 1 to 100 uint challengerChance = (((_challengerSpeed * 10 ** 3) / (_challengerSpeed + _defenderSpeed))+5) / 10;//round if (randResult <= challengerChance) { return true; } else { return false; } } /// @dev function to buy starter package, with card and tokens directly from contract function buyStarterPack() external payable whenNotPaused returns (uint256){ require(starterPackOnSale==true, "starter pack is not on sale"); require(msg.value==starterPackPrice, "fee must be equals to starter pack price"); require(address(marketplace) != address(0), "marketplace not set"); //need to set up marketplace before drafting new cards is allowed totalDeveloperCut = totalDeveloperCut.add(starterPackPrice); hogsmashToken.setApprovalForAllByContract(msg.sender, marketplace, true); //let marketplace have approval for escrow if the card goes on sale return _createCard(msg.sender, starterPackCardLevel); //level n cards } /** * @dev Create card function * @param _to The address that will own the minted card * @param _initLevel The level to start with, usually 1 * @return uint256 ID of the new card */ function _createCard(address _to, uint16 _initLevel) private returns (uint256) { require(_to != address(0), "cannot create card for unknown address"); //check if address is not 0 (the origin address) currentElement+= 1; if (currentElement==4) { currentElement = 8; } if (currentElement == 10) { currentElement = 1; } uint256 tempExpLevel = _initLevel; if (tempExpLevel > expToNextLevelArr.length) { tempExpLevel = expToNextLevelArr.length; //cap it at max level exp } uint32 tempCurrentExp = 0; if (_initLevel>1) { //let exp max out so that user can level up the card according to preference tempCurrentExp = expToNextLevelArr[tempExpLevel]; } uint256 tokenId = hogsmashToken.mint(_to); // use memory as this is a temporary variable, cheaper and will not be stored since cards store all of them Card memory _card = Card({ element: currentElement, // 1 - fire; 2 - water; 3 - wood; 8 - light; 9 - dark; level: _initLevel, // level attack: 1, // attack, defense: 1, // defense, hp: 3, // hp, speed: 1, // speed, criticalRate: 25, // criticalRate flexiGems: 1, // flexiGems, currentExp: tempCurrentExp, // currentExp, expToNextLevel: expToNextLevelArr[tempExpLevel], // expToNextLevel, cardHash: generateHash(), createdDatetime :uint64(now), rank: tokenId // rank }); cards[tokenId] = _card; ranking.push(tokenId); //push to ranking mapping emit CardCreated(msg.sender, tokenId); return tokenId; } function generateHash() private returns (uint256 hash){ hash = uint256((getRandom()%1000000000000)/10000000000); hash = hash.mul(10000000000); uint256 tempHash = ((getRandom()%(eventCardRangeMax-eventCardRangeMin+1))+eventCardRangeMin)*100; hash = hash.add(tempHash); tempHash = getRandom()%100; if (tempHash < goldPercentage) { hash = hash.add(90); } else if (tempHash < (goldPercentage+silverPercentage)) { hash = hash.add(70); } else { hash = hash.add(50); } } /// @dev function to update avatar hash function updateAvatar(uint256 _cardId, uint256 avatarHash) external payable whenNotPaused onlyOwnerOf(_cardId) { require(msg.value==avatarFee, "fee must be equals to avatar price"); Card storage card = cards[_cardId]; uint256 tempHash = card.cardHash%1000000000000; //retain hash fixed section card.cardHash = tempHash.add(avatarHash.mul(1000000000000)); emit HashUpdated(_cardId, card.cardHash); } /// @dev Compute developer&#39;s fee /// @param _challengeFee - transaction fee function _calculateFee(uint256 _challengeFee) internal view returns (uint256) { return developerCut.mul(_challengeFee/10000); } /***********************************************************************************/ /* ADMIN FUNCTIONS /***********************************************************************************/ /** * @dev External function for drafting new card for Owner, for promotional purposes * @param _cardLevel initial level of card created, must be less or equals to 20 * @return uint of cardId */ function generateInitialCard(uint16 _cardLevel) external whenNotPaused onlyOwner returns (uint256) { require(address(marketplace) != address(0), "marketplace not set"); //need to set up marketplace before drafting new cards is allowed require(_cardLevel<=20, "maximum level cannot exceed 20"); //set maximum level at 20 that Owner can generate hogsmashToken.setApprovalForAllByContract(msg.sender, marketplace, true); //let marketplace have approval for escrow if the card goes on sale return _createCard(msg.sender, _cardLevel); //level 1 cards } /// @dev Function for contract owner to put tokens into ranks for events function distributeTokensToRank(uint[] ranks, uint256 tokensPerRank) external payable onlyOwner { require(msg.value == (tokensPerRank*ranks.length), "tokens must be enough to distribute among ranks"); uint i; for (i=0; i<ranks.length; i++) { rankTokens[ranks[i]] = rankTokens[ranks[i]].add(tokensPerRank); totalRankTokens = totalRankTokens.add(tokensPerRank); } } // @dev Allows contract owner to withdraw the all developer cut from the contract function withdrawBalance() external onlyOwner { address thisAddress = this; uint256 balance = thisAddress.balance; uint256 withdrawalSum = totalDeveloperCut; if (balance >= withdrawalSum) { totalDeveloperCut = 0; owner.transfer(withdrawalSum); } } } /***********************************************************************************/ /* INTERFACES /***********************************************************************************/ interface Marketplace { function isMarketplace() external returns (bool); } interface HogSmashToken { function ownerOf(uint256 _tokenId) external view returns (address); function balanceOf(address _owner) external view returns (uint256); function tokensOf(address _owner) external view returns (uint256[]); function mint(address _to) external returns (uint256 _tokenId); function setTokenURI(uint256 _tokenId, string _uri) external; function setApprovalForAllByContract(address _sender, address _to, bool _approved) external; }
0 challenger, 1 defender
uint8 currentAttacker = 0;
8,074,625
[ 1, 20, 462, 7862, 693, 16, 404, 1652, 2345, 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, 202, 202, 11890, 28, 783, 3075, 484, 264, 273, 374, 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/80001/0x8e51A3290912E7bAd80D1200c261D9F80F87903F/sources/contracts/Contract.sol
Customer being paid for playing games
} else if(transactionType == 3) {
9,483,441
[ 1, 8883, 3832, 30591, 364, 23982, 28422, 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, 289, 469, 309, 12, 7958, 559, 422, 890, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol"; import "@openzeppelin/contracts/token/ERC777/ERC777.sol"; import "@openzeppelin/contracts/token/ERC777/ERC777.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "./Administration.sol"; import "./xStarterPoolPairB.sol"; import "./Interaction.sol"; import "./xStarterDeployers.sol"; // contract xStarterDeployer { // // address _admin; // // function setAdmin(address addr) external returns(bool) { // // _admin = addr; // // } // function deployILO( // address adminAddress_, // address proposalAddr_, // address addressOfDex_, // address addressOfDexFactory_ // ) external returns(address ILO_) { // // require(msg.sender == _admin, "Only launchpad can deploy ILO"); // address ILO = address(new xStarterPoolPairB( // adminAddress_, // proposalAddr_, // addressOfDex_, // addressOfDexFactory_ // )); // ILO_ = address(ILO); // } // } contract xStarterDeployer is BaseDeployer { function deployILO( address adminAddress_, address proposalAddr_, address addressOfDex_, address addressOfDexFactory_, address xStarterToken_, address xstarterLP_, address xStarterERCDeployer_, uint minXSTN_, uint minXSTNLP_, uint blockTime_ ) external onlyAllowedCaller returns(address ILO_) { address ILO = address(new xStarterPoolPairB( adminAddress_, proposalAddr_, addressOfDex_, addressOfDexFactory_, xStarterToken_, xstarterLP_, xStarterERCDeployer_, minXSTN_, minXSTNLP_, blockTime_ )); ILO_ = address(ILO); } } interface iXstarterDeployer { function setAllowedCaller(address allowedCaller_) external returns(bool); function deployILO( address adminAddress_, address proposalAddr_, address addressOfDex_, address addressOfDexFactory_, address xStarterToken_, address xstarterLP_, address xStarterERCDeployer_, uint minXSTN_, uint minXSTNLP_, uint blockTime_ ) external returns(address ILO_); } // contract launches xStarterPoolPairB contracts for approved ILO proposals and enforces contract xStarterLaunchPad is Administration, Interaction{ using SafeMath for uint256; using Address for address; modifier onlyEnoughDeposits() { // must add 1, given this checks to makes sure proposer has tokens for at least 1 proposal addional proposal require(depositBalance(_msgSender()) >= _depositPerProposal * (_numOfProposals[_msgSender()] + 1), 'must have minimum deposit'); _; } bool private _initialILODeployed; // xStarter's ILO address address private _initialILOAddr; address private _initialILOPropAddr; bool _deploying; // address __admin = 0xF4c8163B122fc28686990AC2777Fe090ca6b5357; // address of deployer // min amount of tokens to have deposited uint _depositPerProposal; // minimum amount of xStarter tokens or xStarter lps needed to participate uint _minXSTNLP; uint _minXSTN; uint _mineLen; address _xStarterToken; address _xStarterLP; address _xStarterGovernance; address _xStarterNFT; address public _addressOfDex; address public _addressOfDexFactory; address _xStarterDeployer; address _xStarterERCDeployer; // todo: let mapping be string and uint in which index is the position of ILOproposal in array mapping(address => uint) private _ILOProposals; address[] private _ILOProposalArray; // mapping(string => DeployedILO) private _deployedILOs; // mapping(string => GovernanceProposal) private _govProposals; mapping(address => uint16) _numOfProposals; mapping(address => uint) private _tokenDeposits; mapping(address => bool) private _currentlyFunding; mapping(string => address) private supportedDex; constructor( address xStarterToken_, address xStarterDeployer_, address xStarterERCDeployer_, uint depositPerProposal_, uint minXSTN_, uint minXSTNLP_, uint blockTime_, address addressOfDex_, address addressOfDexFactory_, address admin_ ) Administration(admin_) { _xStarterToken = xStarterToken_; _xStarterDeployer = xStarterDeployer_; _xStarterERCDeployer = xStarterERCDeployer_; _depositPerProposal = depositPerProposal_; _minXSTN = minXSTN_; _minXSTNLP = minXSTNLP_; _addressOfDex = addressOfDex_; _addressOfDexFactory = addressOfDexFactory_; _mineLen = blockTime_; } function changeMinTokensRequirements( uint minXSTN_, uint minXSTNLP_ ) external returns(bool) { require(_xStarterGovernance != address(0) && _msgSender() == _xStarterGovernance, 'Not authorized' ); _minXSTN = minXSTN_; _minXSTNLP = minXSTNLP_; return true; } function getMinTokensRequirements() public view returns(uint, uint) { return (_minXSTN, _minXSTNLP); } function addGovernance(address xStarterGovernance_) external onlyAdmin returns(bool) { _xStarterGovernance = xStarterGovernance_; return true; } function addNFT(address xStarterNFT_) external onlyAdmin returns(bool) { _xStarterNFT = xStarterNFT_; return true; } function xStarterDEXUsed() public view returns(address dexAddress, address dexFactoryAddress) { return (_addressOfDex, _addressOfDexFactory); } function xStarterContracts() public view returns(address[5] memory) { return [_xStarterGovernance, _xStarterToken, _xStarterNFT, _xStarterDeployer, _xStarterERCDeployer]; } function getProposal(address proposalAddr_) public view returns(CompactInfo memory i_) { // uint lenOfArrayAtTimeOfAdd = _ILOProposals[proposalAddr_]; // // proposalAddr does not exist return empty proposal // if(lenOfArrayAtTimeOfAdd == 0) { // return proposal; // } // proposal = _ILOProposalArray[lenOfArrayAtTimeOfAdd - 1]; require((proposalAddr_ == _initialILOAddr && _ILOProposals[proposalAddr_] == 0) || _ILOProposals[proposalAddr_] != 0, "proposal address not registered"); i_ = iXstarterProposal(proposalAddr_).getCompactInfo(); } // gets ILOProposals 5 at a time // function getProposals(uint round_) public view returns(ILOProposal[] memory, bool ) { // uint len = _ILOProposalArray.length; // require(len > 0, "No Proposals Yet"); // // uint start = round_ * 5 // uint end = (round_ * 5) + 5; // bool endOfArray = end >= len; // end = endOfArray ? len : end; // uint start = end <= 5 ? 0 : end - 5; // ILOProposal[] memory proposals = new ILOProposal[](end - start); // for (uint i=start ; i < end; i++) { // proposals[i] = _ILOProposalArray[i]; // } // return (proposals, endOfArray); // } function getProposals(uint round_) public view returns(CompactInfo[] memory, bool ) { uint len = _ILOProposalArray.length; require(len > 0, "No Proposals Yet"); // uint start = round_ * 5 uint end = (round_ * 5) + 5; bool endOfArray = end >= len; end = endOfArray ? len : end; uint start = end <= 5 ? 0 : end - 5; CompactInfo[] memory compactInfos = new CompactInfo[](end - start); uint ind = 0; for (uint i=start ; i < end; i++) { compactInfos[ind] = iXstarterProposal(_ILOProposalArray[i]).getCompactInfo(); ind++; } return (compactInfos, endOfArray); } function noOfProposals() public view returns(uint256) { return _ILOProposalArray.length; } // function IsProposerOrAdmin(address msgSender_, address proposalAddr_) public view returns(bool) { // (ILOProposal memory proposal, ) = getProposal(proposalAddr_); // return proposal.proposer != address(0) && (proposal.proposer == msgSender_ || proposal.admin == msgSender_); // } function depositBalance(address addr_) public view returns(uint) { return _tokenDeposits[addr_]; } function isDeployed(address proposalAddr_) public view returns(bool) { return iXstarterProposal(proposalAddr_).isDeployed(); } event TokensDeposited(address indexed caller_, uint indexed amount_); function depositApprovedToken() external allowedToInteract returns(bool success) { _disallowInteraction(); uint approvedAmount = IERC20(_xStarterToken).allowance(_msgSender(), address(this)); require(depositBalance(_msgSender()) + approvedAmount >= _depositPerProposal, 'new deposit plus current deposit must be greater than minimum Deposit'); success = IERC20(_xStarterToken).transferFrom(_msgSender(), address(this), approvedAmount); require(success,'not able to transfer approved tokens'); _tokenDeposits[_msgSender()] = _tokenDeposits[_msgSender()].add(approvedAmount); _allowInteraction(); emit TokensDeposited(_msgSender(), approvedAmount); } event TokensWithdrawn(address indexed caller_, uint indexed amount_); function withdrawTokens(uint amount_) external allowedToInteract returns(bool success) { require(depositBalance(_msgSender()) >= amount_, 'Not enough funds'); require(_canWithdraw(amount_), 'Must maintain a minimum deposit until proposal is completed'); _disallowInteraction(); _tokenDeposits[_msgSender()] = _tokenDeposits[_msgSender()].sub(amount_); success = IERC20(_xStarterToken).approve(_msgSender(), amount_); _allowInteraction(); emit TokensWithdrawn(_msgSender(), amount_); } function registerILOProposal(address proposalAddr_) public returns(bool success) { require(_initialILODeployed, "Initial xStarter ILO not deployed"); success = _registerILOProposal(proposalAddr_); // require(success, "not able to register ILO"); } function deployXstarterILO(address proposalAddr_) external onlyAdmin returns(address ILO){ // require(_msgSender() == __admin, "Not authorized"); require(!_initialILODeployed, "xStarter ILO already deployed"); bool success = _registerILOProposal(proposalAddr_); require(success, 'Not able to create initial ILO proposal'); // (success, ILO) = _deployILO(proposalAddr_, _msgSender()); // deploy ILO = iXstarterDeployer(_xStarterDeployer).deployILO( _msgSender(), proposalAddr_, _addressOfDex, _addressOfDexFactory, // contrib lock address(0), // xStarter token not yet distributed so should address(0), _xStarterERCDeployer, _minXSTN, _minXSTNLP, _mineLen ); // allow newly created ILO pool pair to use erc20 deployer IXStarterERCDeployer(_xStarterERCDeployer).setAllowedCaller(ILO); // change proposal state success = iXstarterProposal(proposalAddr_).deploy(ILO); require(success, 'Not able to deploy initial ILO'); _initialILODeployed = true; _initialILOAddr = ILO; _initialILOPropAddr = proposalAddr_; emit ILODeployed(proposalAddr_, _msgSender(), ILO); } function setTokenAndLPAddr() external view returns(address xStarterToken_, address xStarterLP_) { (xStarterToken_, xStarterLP_) = iXstarterProposal(_initialILOPropAddr).getTokenAndLPAddr(); require(xStarterToken_ != address(0) && xStarterLP_ != address(0), "initial xStarter ILO not completed"); } event ILODeployed(address proposalAddr_, address indexed caller_, address indexed ILO); function deployILOContract(address proposalAddr_, address ILOAdmin_) external allowedToInteract returns(bool success) { // anyone can deploy an ILO, but if ILOAdmin_ != ILO proposer then, then the msg.sender must be the ILO proposer // ILO proposer also gets the NFT rewards, so it makes no sense for anyone but the _disallowInteraction(); // initial ILO of xStarter tokens should have been completed, with liquidity pair created require(_xStarterToken != address(0) && _xStarterLP != address(0), "initial xStarter ILO not completed"); // require(!iXstarterProposal(proposalAddr_).isDeployed(), "ILO already deployed or being deployed"); address ILO; (success, ILO) = _deployILO(proposalAddr_, ILOAdmin_); require(success, "Not able to deploy ILO"); _allowInteraction(); emit ILODeployed(proposalAddr_, _msgSender(), ILO); } function _canWithdraw(uint amount_) internal view returns(bool) { if(_numOfProposals[_msgSender()] == 0) { return true; } return _tokenDeposits[_msgSender()].sub(amount_) >= _depositPerProposal * _numOfProposals[_msgSender()]; } function _deployILO(address proposalAddr_, address ILOAdmin_) internal returns (bool success, address ILO){ // check if its approved // bool approved = iXstarterProposal(proposalAddr_).approved(); bool approved = iXstarterGovernance(_xStarterGovernance).ILOApproved(proposalAddr_); require(approved, "proposal has not been approved"); // deploy ILO = iXstarterDeployer(_xStarterDeployer).deployILO( ILOAdmin_, proposalAddr_, _addressOfDex, _addressOfDexFactory, // contrib lock _xStarterToken, _xStarterLP, _xStarterERCDeployer, _minXSTN, _minXSTNLP, _mineLen ); // change proposal state success = iXstarterProposal(proposalAddr_).deploy(ILO); // allow newly created ILO pool pair to use erc20 deployer IXStarterERCDeployer(_xStarterERCDeployer).setAllowedCaller(ILO); return (success, ILO); } event ILOProposalRegistered(address indexed proposer, address indexed proposalAddr_); function _registerILOProposal(address proposalAddr_) internal returns(bool success) { _ILOProposalArray.push(proposalAddr_); _ILOProposals[proposalAddr_] = _ILOProposalArray.length; success = iXstarterProposal(proposalAddr_).register(_xStarterGovernance); require(success, 'not able to register ILOProposal'); emit ILOProposalRegistered(_msgSender(), proposalAddr_); return success; } // function _verifyILO(address proposalAddr_, string memory tokenName_, string memory tokenSymbol_, string memory infoURL_, uint totalSupply_, uint8 percentOfTokensForILO_, address fundingToken_) internal view returns(bool) { // (ILOProposal memory proposal, ) = getProposal(proposalAddr_); // require(!proposal.isOpen && !proposal.isApproved, "proposal with token symbol is either in the process of voting or already approved"); // (string memory tokenName, string memory tokenSymbol, string memory infoURL, uint totalSupply, uint8 percentOfTokensForILO, address fundingToken) = iXstarterProposal(proposalAddr_).getMainInfo(); // require( // ( // keccak256(abi.encodePacked(tokenName_)) == keccak256(abi.encodePacked(tokenName)) && // keccak256(abi.encodePacked(tokenSymbol_)) == keccak256(abi.encodePacked(tokenSymbol)) && // keccak256(abi.encodePacked(infoURL_)) == keccak256(abi.encodePacked(infoURL)) && // totalSupply_ == totalSupply && // percentOfTokensForILO_ == percentOfTokensForILO && // fundingToken_ == fundingToken), // "ILOProposal Info Error" // ); // return true; // } }
uint lenOfArrayAtTimeOfAdd = _ILOProposals[proposalAddr_]; proposalAddr does not exist return empty proposal if(lenOfArrayAtTimeOfAdd == 0) { return proposal; } proposal = _ILOProposalArray[lenOfArrayAtTimeOfAdd - 1];
function getProposal(address proposalAddr_) public view returns(CompactInfo memory i_) { require((proposalAddr_ == _initialILOAddr && _ILOProposals[proposalAddr_] == 0) || _ILOProposals[proposalAddr_] != 0, "proposal address not registered"); i_ = iXstarterProposal(proposalAddr_).getCompactInfo(); }
12,736,496
[ 1, 11890, 562, 951, 1076, 861, 950, 951, 986, 273, 389, 45, 1502, 626, 22536, 63, 685, 8016, 3178, 67, 15533, 225, 14708, 3178, 1552, 486, 1005, 327, 1008, 14708, 309, 12, 1897, 951, 1076, 861, 950, 951, 986, 422, 374, 13, 288, 377, 327, 14708, 31, 289, 14708, 273, 389, 45, 1502, 14592, 1076, 63, 1897, 951, 1076, 861, 950, 951, 986, 300, 404, 15533, 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, 565, 445, 3570, 8016, 12, 2867, 14708, 3178, 67, 13, 1071, 1476, 1135, 12, 16863, 966, 3778, 277, 67, 13, 288, 203, 3639, 2583, 12443, 685, 8016, 3178, 67, 422, 389, 6769, 45, 1502, 3178, 597, 389, 45, 1502, 626, 22536, 63, 685, 8016, 3178, 67, 65, 422, 374, 13, 747, 389, 45, 1502, 626, 22536, 63, 685, 8016, 3178, 67, 65, 480, 374, 16, 315, 685, 8016, 1758, 486, 4104, 8863, 203, 3639, 277, 67, 273, 277, 60, 10983, 387, 14592, 12, 685, 8016, 3178, 67, 2934, 588, 16863, 966, 5621, 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 ]
pragma solidity ^0.4.25; /* __ __ __ __ ______ __ __ ______ | \ _ | \ | \| \ / \ | \ | \ / \ | $$ / \ | $$ ______ | $$| $$ | $$$$$$\ _| $$_ ______ ______ ______ _| $$_ | $$$$$$\ | $$/ $\| $$ | \ | $$| $$ | $$___\$$| $$ \ / \ / \ / \| $$ \ \$$__| $$ | $$ $$$\ $$ \$$$$$$\| $$| $$ \$$ \ \$$$$$$ | $$$$$$\| $$$$$$\| $$$$$$\\$$$$$$ / $$ | $$ $$\$$\$$ / $$| $$| $$ _\$$$$$$\ | $$ __ | $$ \$$| $$ $$| $$ $$ | $$ __ | $$$$$$ | $$$$ \$$$$| $$$$$$$| $$| $$ | \__| $$ | $$| \| $$ | $$$$$$$$| $$$$$$$$ | $$| \ | $$_____ | $$$ \$$$ \$$ $$| $$| $$ \$$ $$ \$$ $$| $$ \$$ \ \$$ \ \$$ $$ | $$ \ \$$ \$$ \$$$$$$$ \$$ \$$ \$$$$$$ \$$$$ \$$ \$$$$$$$ \$$$$$$$ \$$$$ \$$$$$$$$ website: https://wallstreetmarket.tk discord: hhttps://discord.gg/FyWtwRT 20% Dividends Fees/Payouts for Exchange Win the Stock Split Jackpot.......... Players are rewarded with the ETH Threshold Jackpot when their Buy causes the total ETH Balance to cross the next ETH Threshold. ETH Thresholds are every 5 ETH: 5,10,15,20,... Whether you spend 5 ETH or 0.005 ETH to cross you win the jackpot. ETH Threshold jackpot is funded with 10% of the BUY/SELL transactions Additional Games will include Bonds, Options, and MORE! */ contract AcceptsExchange { wallstreet2 public tokenContract; function AcceptsExchange(address _tokenContract) public { tokenContract = wallstreet2(_tokenContract); } modifier onlyTokenContract { require(msg.sender == address(tokenContract)); _; } /** * @dev Standard ERC677 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint256 _value, bytes _data) external returns (bool); function tokenFallbackExpanded(address _from, uint256 _value, bytes _data, address _sender, address _referrer) external returns (bool); } contract wallstreet2 { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0 || ownerAccounts[msg.sender] > 0); //require(myDividends(true) > 0); _; } modifier notContract() { require (msg.sender == tx.origin); _; } modifier allowPlayer(){ require(boolAllowPlayer); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } modifier onlyActive(){ require(boolContractActive); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( // is the customer in the ambassador list? (ambassadors_[_customerAddress] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_) || (_customerAddress == dev) ); // updated the accumulated quota ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the ambassador phase won&#39;t reinitiate onlyAmbassadors = false; _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); // JackPot event onJackpot( address indexed customerAddress, uint indexed value, uint indexed nextThreshold ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "Wall Street 2"; string public symbol = "SHARE"; uint8 constant public decimals = 18; uint256 constant internal tokenPriceInitial_ = 0.00000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.000000001 ether; uint256 constant internal magnitude = 2**64; // proof of stake (defaults at 100 tokens) uint256 public stakingRequirement = 100e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 2 ether; uint256 constant internal ambassadorQuota_ = 20 ether; address dev; bool public boolAllowPlayer = false; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; mapping(address => uint) internal ownerAccounts; bool public allowReferral = false; //for cards uint8 public buyDividendFee_ = 150; uint8 public sellDividendFee_ = 150; bool public boolContractActive = false; // administrator list (see above on what they can do) mapping(address => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; // Special Wall Street Market Platform control from scam game contracts on Wall Street Market platform mapping(address => bool) public canAcceptTokens_; // contracts, which can accept Wall Street tokens //ETH Jackpot uint public jackpotThreshold = 5 ether; uint public jackpotAccount = 0; uint public jackpotFeeRate = 100; //10% uint public jackpotPayRate = 1000; //100% uint public jackpotThreshIncrease = 5 ether; address mkt1 = 0x0; address mkt2 = 0x0; address mkt3 = 0x0; uint mkt1Rate = 0; uint mkt2Rate = 0; uint mkt3Rate = 0; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function wallstreet2() public { // add administrators here administrators[msg.sender] = true; dev = msg.sender; ambassadors_[dev] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /** * Converts all of caller&#39;s dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress] + ownerAccounts[_customerAddress]; referralBalance_[_customerAddress] = 0; ownerAccounts[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress] + ownerAccounts[_customerAddress]; referralBalance_[_customerAddress] = 0; ownerAccounts[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data uint8 localDivFee = 200; address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); jackpotAccount = SafeMath.add(SafeMath.div(SafeMath.mul(_ethereum,jackpotFeeRate),1000),jackpotAccount); _ethereum = SafeMath.sub(_ethereum, SafeMath.div(SafeMath.mul(_ethereum,jackpotFeeRate),1000)); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, sellDividendFee_),1000); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * Remember, there&#39;s a 10% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; uint8 localDivFee = 200; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // liquify 20% of the tokens that are transfered // these are dispersed to shareholders uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, localDivFee),1000); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); // burn the fee tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); // disperse dividends among holders profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); // fire event Transfer(_customerAddress, _toAddress, _taxedTokens); // ERC20 return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ function disableInitialStage() onlyAdministrator() public { onlyAmbassadors = false; } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Set Exchange Rates */ function setExchangeRates(uint8 _newBuyFee, uint8 _newSellFee) onlyAdministrator() public { require(_newBuyFee <= 400); //40% require(_newSellFee <= 400); //40% buyDividendFee_ = _newBuyFee; sellDividendFee_ = _newSellFee; } /** * Set Marketing Rates */ function setMarketingRates(uint256 _newMkt1Rate, uint256 _newMkt2Rate, uint256 _newMkt3Rate) onlyAdministrator() public { require(_newMkt1Rate +_newMkt2Rate +_newMkt3Rate <= 180); mkt1Rate = _newMkt1Rate; mkt2Rate = _newMkt2Rate; mkt3Rate = _newMkt3Rate; } /** * Set Mkt1 Address */ function setMarket1(address _newMkt1) onlyAdministrator() public { mkt1 = _newMkt1; } /** * Set Mkt2 Address */ function setMarket2(address _newMkt2) onlyAdministrator() public { mkt2 = _newMkt2; } /** * Set Mkt3 Address */ function setMarket3(address _newMkt3) onlyAdministrator() public { mkt3 = _newMkt3; } /** * In case one of us dies, we need to replace ourselves. */ function setContractActive(bool _status) onlyAdministrator() public { boolContractActive = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } function addAmbassador(address _newAmbassador) onlyAdministrator() public { ambassadors_[_newAmbassador] = true; } /** * Set Jackpot PayRate */ function setJackpotFeeRate(uint256 _newFeeRate) onlyAdministrator() public { require(_newFeeRate <= 400); jackpotFeeRate = _newFeeRate; } /** * Set Jackpot PayRate */ function setJackpotPayRate(uint256 _newPayRate) onlyAdministrator() public { jackpotPayRate = _newPayRate; } /** * Set Jackpot Increment */ function setJackpotIncrement(uint256 _newIncrement) onlyAdministrator() public { jackpotThreshIncrease = _newIncrement; } /** * Set Jackpot Threshold Level */ function setJackpotThreshold(uint256 _newTarget) onlyAdministrator() public { jackpotThreshold = _newTarget; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return address(this).balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } function myCardDividends() public view returns(uint256) { address _customerAddress = msg.sender; return ownerAccounts[_customerAddress]; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } function getData() //Ethereum Balance, MyTokens, TotalTokens, myDividends, myRefDividends, jackpot, jackpotThreshold public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256) { return(address(this).balance, balanceOf(msg.sender), tokenSupply_, dividendsOf(msg.sender) + ownerAccounts[msg.sender], referralBalance_[msg.sender], jackpotAccount, jackpotThreshold); } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, sellDividendFee_),1000); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, buyDividendFee_),1000); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, buyDividendFee_),1000); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, sellDividendFee_),1000); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) onlyActive() internal returns(uint256) { // data setup // setup data if (mkt1 != 0x0 && mkt1Rate != 0){ ownerAccounts[mkt1] = SafeMath.add(ownerAccounts[mkt1] , SafeMath.div(SafeMath.mul(msg.value, mkt1Rate), 1000)); _incomingEthereum = SafeMath.sub(_incomingEthereum, SafeMath.div(SafeMath.mul(msg.value, mkt1Rate), 1000)); } if (mkt2 != 0x0 && mkt2Rate != 0){ ownerAccounts[mkt2] = SafeMath.add(ownerAccounts[mkt2] , SafeMath.div(SafeMath.mul(msg.value, mkt2Rate), 1000)); _incomingEthereum = SafeMath.sub(_incomingEthereum, SafeMath.div(SafeMath.mul(msg.value, mkt2Rate), 1000)); } if (mkt3 != 0x0 && mkt3Rate != 0){ ownerAccounts[mkt3] = SafeMath.add(ownerAccounts[mkt3] , SafeMath.div(SafeMath.mul(msg.value, mkt3Rate), 1000)); _incomingEthereum = SafeMath.sub(_incomingEthereum, SafeMath.div(SafeMath.mul(msg.value, mkt3Rate), 1000)); } //check for jackpot win if (address(this).balance >= jackpotThreshold){ jackpotThreshold = address(this).balance + jackpotThreshIncrease; onJackpot(msg.sender, SafeMath.div(SafeMath.mul(jackpotAccount,jackpotPayRate),1000), jackpotThreshold); ownerAccounts[msg.sender] = SafeMath.add(ownerAccounts[msg.sender], SafeMath.div(SafeMath.mul(jackpotAccount,jackpotPayRate),1000)); jackpotAccount = SafeMath.sub(jackpotAccount,SafeMath.div(SafeMath.mul(jackpotAccount,jackpotPayRate),1000)); } else { jackpotAccount = SafeMath.add(SafeMath.div(SafeMath.mul(_incomingEthereum,jackpotFeeRate),1000),jackpotAccount); _incomingEthereum = SafeMath.sub(_incomingEthereum, SafeMath.div(SafeMath.mul(_incomingEthereum,jackpotFeeRate),1000)); //SafeMath.div(SafeMath.mul(_incomingEthereum,jackpotFeeRate),1000); } uint256 _referralBonus = SafeMath.div(SafeMath.div(SafeMath.mul(_incomingEthereum, buyDividendFee_ ),1000), 3); uint256 _dividends = SafeMath.sub(SafeMath.div(SafeMath.mul(_incomingEthereum, buyDividendFee_ ),1000), _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, SafeMath.div(SafeMath.mul(_incomingEthereum, buyDividendFee_),1000)); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != msg.sender && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can&#39;t give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender], _amountOfTokens); // Tells the contract that the buyer doesn&#39;t deserve dividends for the tokens before they owned them; //really i know you think you do but you don&#39;t int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[msg.sender] += _updatedPayouts; // fire event onTokenPurchase(msg.sender, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It&#39;s an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It&#39;s an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei 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; } } } /** * @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&#39;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; } }
* Set Jackpot PayRate/
function setJackpotFeeRate(uint256 _newFeeRate) onlyAdministrator() public { require(_newFeeRate <= 400); jackpotFeeRate = _newFeeRate; }
2,084,702
[ 1, 694, 804, 484, 13130, 13838, 4727, 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 ]
[ 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, 444, 46, 484, 13130, 14667, 4727, 12, 11890, 5034, 389, 2704, 14667, 4727, 13, 203, 3639, 1338, 4446, 14207, 1435, 203, 3639, 1071, 203, 565, 288, 203, 3639, 2583, 24899, 2704, 14667, 4727, 1648, 7409, 1769, 203, 3639, 525, 484, 13130, 14667, 4727, 273, 389, 2704, 14667, 4727, 31, 203, 565, 289, 203, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.2; contract MST { /* Public variables of the token */ string public standard = 'Token 0.1'; string public name; string public symbol; uint8 public decimals; uint256 public initialSupply; uint256 public totalSupply; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /* Initializes contract with initial supply tokens to the creator of the contract */ function MST() { initialSupply = 1000000000; name ="Mining Security Token"; decimals = 18; symbol = "MST"; balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply } /* Send coins */ function transfer(address _to, uint256 _value) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows balanceOf[msg.sender] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient } /* This unnamed function is called whenever someone tries to send ether to it */ function () { throw; // Prevents accidental sending of ether } }
Public variables of the token */ This creates an array with all balances */ Initializes contract with initial supply tokens to the creator of the contract */
function MST() { initialSupply = 1000000000; name ="Mining Security Token"; decimals = 18; symbol = "MST"; }
13,996,774
[ 1, 4782, 3152, 434, 326, 1147, 342, 1220, 3414, 392, 526, 598, 777, 324, 26488, 342, 10188, 3128, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 6835, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 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, 490, 882, 1435, 288, 203, 203, 540, 2172, 3088, 1283, 273, 15088, 3784, 31, 203, 540, 508, 273, 6, 2930, 310, 6036, 3155, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 540, 3273, 273, 315, 49, 882, 14432, 203, 540, 203, 4766, 27699, 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 ]
// SPDX-License-Identifier: Unlicense pragma solidity >=0.8.4; import "./PRBMath.sol"; /// @title PRBMathUD60x18Typed /// @author Paul Razvan Berg /// @notice Smart contract library for advanced fixed-point math that works with uint256 numbers considered to have 18 /// trailing decimals. We call this number representation unsigned 60.18-decimal fixed-point, since there can be up to 60 /// digits in the integer part and up to 18 decimals in the fractional part. The numbers are bound by the minimum and the /// maximum values permitted by the Solidity type uint256. /// @dev This is the same as PRBMathUD59x18, except that it works with structs instead of raw uint256s. library PRBMathUD60x18Typed { /// STORAGE /// /// @dev Half the SCALE number. uint256 internal constant HALF_SCALE = 5e17; /// @dev log2(e) as an unsigned 60.18-decimal fixed-point number. uint256 internal constant LOG2_E = 1_442695040888963407; /// @dev The maximum value an unsigned 60.18-decimal fixed-point number can have. uint256 internal constant MAX_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_584007913129639935; /// @dev The maximum whole value an unsigned 60.18-decimal fixed-point number can have. uint256 internal constant MAX_WHOLE_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_000000000000000000; /// @dev How many trailing decimals can be represented. uint256 internal constant SCALE = 1e18; /// @notice Adds two unsigned 60.18-decimal fixed-point numbers together, returning a new unsigned 60.18-decimal /// fixed-point number. /// @param x The first summand as an unsigned 60.18-decimal fixed-point number. /// @param y The second summand as an unsigned 60.18-decimal fixed-point number. /// @param result The sum as an unsigned 59.18 decimal fixed-point number. function add(PRBMath.UD60x18 memory x, PRBMath.UD60x18 memory y) internal pure returns (PRBMath.UD60x18 memory result) { unchecked { uint256 rValue = x.value + y.value; if (rValue < x.value) { revert PRBMathUD60x18__AddOverflow(x.value, y.value); } result = PRBMath.UD60x18({ value: rValue }); } } /// @notice Calculates the arithmetic average of x and y, rounding down. /// @param x The first operand as an unsigned 60.18-decimal fixed-point number. /// @param y The second operand as an unsigned 60.18-decimal fixed-point number. /// @return result The arithmetic average as an unsigned 60.18-decimal fixed-point number. function avg(PRBMath.UD60x18 memory x, PRBMath.UD60x18 memory y) internal pure returns (PRBMath.UD60x18 memory result) { // The operations can never overflow. unchecked { // The last operand checks if both x and y are odd and if that is the case, we add 1 to the result. We need // to do this because if both numbers are odd, the 0.5 remainder gets truncated twice. uint256 rValue = (x.value >> 1) + (y.value >> 1) + (x.value & y.value & 1); result = PRBMath.UD60x18({ value: rValue }); } } /// @notice Yields the least unsigned 60.18 decimal fixed-point number greater than or equal to x. /// /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts. /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// /// Requirements: /// - x must be less than or equal to MAX_WHOLE_UD60x18. /// /// @param x The unsigned 60.18-decimal fixed-point number to ceil. /// @param result The least integer greater than or equal to x, as an unsigned 60.18-decimal fixed-point number. function ceil(PRBMath.UD60x18 memory x) internal pure returns (PRBMath.UD60x18 memory result) { uint256 xValue = x.value; if (xValue > MAX_WHOLE_UD60x18) { revert PRBMathUD60x18__CeilOverflow(xValue); } uint256 rValue; assembly { // Equivalent to "x % SCALE" but faster. let remainder := mod(xValue, SCALE) // Equivalent to "SCALE - remainder" but faster. let delta := sub(SCALE, remainder) // Equivalent to "x + delta * (remainder > 0 ? 1 : 0)" but faster. rValue := add(xValue, mul(delta, gt(remainder, 0))) } result = PRBMath.UD60x18({ value: rValue }); } /// @notice Divides two unsigned 60.18-decimal fixed-point numbers, returning a new unsigned 60.18-decimal fixed-point number. /// /// @dev Uses mulDiv to enable overflow-safe multiplication and division. /// /// Requirements: /// - The denominator cannot be zero. /// /// @param x The numerator as an unsigned 60.18-decimal fixed-point number. /// @param y The denominator as an unsigned 60.18-decimal fixed-point number. /// @param result The quotient as an unsigned 60.18-decimal fixed-point number. function div(PRBMath.UD60x18 memory x, PRBMath.UD60x18 memory y) internal pure returns (PRBMath.UD60x18 memory result) { result = PRBMath.UD60x18({ value: PRBMath.mulDiv(x.value, SCALE, y.value) }); } /// @notice Returns Euler's number as an unsigned 60.18-decimal fixed-point number. /// @dev See https://en.wikipedia.org/wiki/E_(mathematical_constant). function e() internal pure returns (PRBMath.UD60x18 memory result) { result = PRBMath.UD60x18({ value: 2_718281828459045235 }); } /// @notice Calculates the natural exponent of x. /// /// @dev Based on the insight that e^x = 2^(x * log2(e)). /// /// Requirements: /// - All from "log2". /// - x must be less than 88.722839111672999628. /// /// @param x The exponent as an unsigned 60.18-decimal fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function exp(PRBMath.UD60x18 memory x) internal pure returns (PRBMath.UD60x18 memory result) { uint256 xValue = x.value; // Without this check, the value passed to "exp2" would be greater than 192. if (xValue >= 133_084258667509499441) { revert PRBMathUD60x18__ExpInputTooBig(xValue); } // Do the fixed-point multiplication inline to save gas. unchecked { uint256 doubleScaleProduct = x.value * LOG2_E; PRBMath.UD60x18 memory exponent = PRBMath.UD60x18({ value: (doubleScaleProduct + HALF_SCALE) / SCALE }); result = exp2(exponent); } } /// @notice Calculates the binary exponent of x using the binary fraction method. /// /// @dev See https://ethereum.stackexchange.com/q/79903/24693. /// /// Requirements: /// - x must be 192 or less. /// - The result must fit within MAX_UD60x18. /// /// @param x The exponent as an unsigned 60.18-decimal fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function exp2(PRBMath.UD60x18 memory x) internal pure returns (PRBMath.UD60x18 memory result) { // 2^192 doesn't fit within the 192.64-bit format used internally in this function. if (x.value >= 192e18) { revert PRBMathUD60x18__Exp2InputTooBig(x.value); } unchecked { // Convert x to the 192.64-bit fixed-point format. uint256 x192x64 = (x.value << 64) / SCALE; // Pass x to the PRBMath.exp2 function, which uses the 192.64-bit fixed-point number representation. result = PRBMath.UD60x18({ value: PRBMath.exp2(x192x64) }); } } /// @notice Yields the greatest unsigned 60.18 decimal fixed-point number less than or equal to x. /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts. /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// @param x The unsigned 60.18-decimal fixed-point number to floor. /// @param result The greatest integer less than or equal to x, as an unsigned 60.18-decimal fixed-point number. function floor(PRBMath.UD60x18 memory x) internal pure returns (PRBMath.UD60x18 memory result) { uint256 xValue = x.value; uint256 rValue; assembly { // Equivalent to "x % SCALE" but faster. let remainder := mod(xValue, SCALE) // Equivalent to "x - remainder * (remainder > 0 ? 1 : 0)" but faster. rValue := sub(xValue, mul(remainder, gt(remainder, 0))) } result = PRBMath.UD60x18({ value: rValue }); } /// @notice Yields the excess beyond the floor of x. /// @dev Based on the odd function definition https://en.wikipedia.org/wiki/Fractional_part. /// @param x The unsigned 60.18-decimal fixed-point number to get the fractional part of. /// @param result The fractional part of x as an unsigned 60.18-decimal fixed-point number. function frac(PRBMath.UD60x18 memory x) internal pure returns (PRBMath.UD60x18 memory result) { uint256 xValue = x.value; uint256 rValue; assembly { rValue := mod(xValue, SCALE) } result = PRBMath.UD60x18({ value: rValue }); } /// @notice Converts a number from basic integer form to unsigned 60.18-decimal fixed-point representation. /// /// @dev Requirements: /// - x must be less than or equal to MAX_UD60x18 divided by SCALE. /// /// @param x The basic integer to convert. /// @param result The same number in unsigned 60.18-decimal fixed-point representation. function fromUint(uint256 x) internal pure returns (PRBMath.UD60x18 memory result) { unchecked { if (x > MAX_UD60x18 / SCALE) { revert PRBMathUD60x18__FromUintOverflow(x); } result = PRBMath.UD60x18({ value: x * SCALE }); } } /// @notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down. /// /// @dev Requirements: /// - x * y must fit within MAX_UD60x18, lest it overflows. /// /// @param x The first operand as an unsigned 60.18-decimal fixed-point number. /// @param y The second operand as an unsigned 60.18-decimal fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function gm(PRBMath.UD60x18 memory x, PRBMath.UD60x18 memory y) internal pure returns (PRBMath.UD60x18 memory result) { if (x.value == 0) { return PRBMath.UD60x18({ value: 0 }); } unchecked { // Checking for overflow this way is faster than letting Solidity do it. uint256 xy = x.value * y.value; if (xy / x.value != y.value) { revert PRBMathUD60x18__GmOverflow(x.value, y.value); } // We don't need to multiply by the SCALE here because the x*y product had already picked up a factor of SCALE // during multiplication. See the comments within the "sqrt" function. result = PRBMath.UD60x18({ value: PRBMath.sqrt(xy) }); } } /// @notice Calculates 1 / x, rounding toward zero. /// /// @dev Requirements: /// - x cannot be zero. /// /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the inverse. /// @return result The inverse as an unsigned 60.18-decimal fixed-point number. function inv(PRBMath.UD60x18 memory x) internal pure returns (PRBMath.UD60x18 memory result) { unchecked { // 1e36 is SCALE * SCALE. result = PRBMath.UD60x18({ value: 1e36 / x.value }); } } /// @notice Calculates the natural logarithm of x. /// /// @dev Based on the insight that ln(x) = log2(x) / log2(e). /// /// Requirements: /// - All from "log2". /// /// Caveats: /// - All from "log2". /// - This doesn't return exactly 1 for 2.718281828459045235, for that we would need more fine-grained precision. /// /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the natural logarithm. /// @return result The natural logarithm as an unsigned 60.18-decimal fixed-point number. function ln(PRBMath.UD60x18 memory x) internal pure returns (PRBMath.UD60x18 memory result) { // Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x) // can return is 196205294292027477728. unchecked { uint256 rValue = (log2(x).value * SCALE) / LOG2_E; result = PRBMath.UD60x18({ value: rValue }); } } /// @notice Calculates the common logarithm of x. /// /// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common /// logarithm based on the insight that log10(x) = log2(x) / log2(10). /// /// Requirements: /// - All from "log2". /// /// Caveats: /// - All from "log2". /// /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the common logarithm. /// @return result The common logarithm as an unsigned 60.18-decimal fixed-point number. function log10(PRBMath.UD60x18 memory x) internal pure returns (PRBMath.UD60x18 memory result) { uint256 xValue = x.value; if (xValue < SCALE) { revert PRBMathUD60x18__LogInputTooSmall(xValue); } // Note that the "mul" in this block is the assembly multiplication operation, not the "mul" function defined // in this contract. uint256 rValue; // prettier-ignore assembly { switch xValue case 1 { rValue := mul(SCALE, sub(0, 18)) } case 10 { rValue := mul(SCALE, sub(1, 18)) } case 100 { rValue := mul(SCALE, sub(2, 18)) } case 1000 { rValue := mul(SCALE, sub(3, 18)) } case 10000 { rValue := mul(SCALE, sub(4, 18)) } case 100000 { rValue := mul(SCALE, sub(5, 18)) } case 1000000 { rValue := mul(SCALE, sub(6, 18)) } case 10000000 { rValue := mul(SCALE, sub(7, 18)) } case 100000000 { rValue := mul(SCALE, sub(8, 18)) } case 1000000000 { rValue := mul(SCALE, sub(9, 18)) } case 10000000000 { rValue := mul(SCALE, sub(10, 18)) } case 100000000000 { rValue := mul(SCALE, sub(11, 18)) } case 1000000000000 { rValue := mul(SCALE, sub(12, 18)) } case 10000000000000 { rValue := mul(SCALE, sub(13, 18)) } case 100000000000000 { rValue := mul(SCALE, sub(14, 18)) } case 1000000000000000 { rValue := mul(SCALE, sub(15, 18)) } case 10000000000000000 { rValue := mul(SCALE, sub(16, 18)) } case 100000000000000000 { rValue := mul(SCALE, sub(17, 18)) } case 1000000000000000000 { rValue := 0 } case 10000000000000000000 { rValue := SCALE } case 100000000000000000000 { rValue := mul(SCALE, 2) } case 1000000000000000000000 { rValue := mul(SCALE, 3) } case 10000000000000000000000 { rValue := mul(SCALE, 4) } case 100000000000000000000000 { rValue := mul(SCALE, 5) } case 1000000000000000000000000 { rValue := mul(SCALE, 6) } case 10000000000000000000000000 { rValue := mul(SCALE, 7) } case 100000000000000000000000000 { rValue := mul(SCALE, 8) } case 1000000000000000000000000000 { rValue := mul(SCALE, 9) } case 10000000000000000000000000000 { rValue := mul(SCALE, 10) } case 100000000000000000000000000000 { rValue := mul(SCALE, 11) } case 1000000000000000000000000000000 { rValue := mul(SCALE, 12) } case 10000000000000000000000000000000 { rValue := mul(SCALE, 13) } case 100000000000000000000000000000000 { rValue := mul(SCALE, 14) } case 1000000000000000000000000000000000 { rValue := mul(SCALE, 15) } case 10000000000000000000000000000000000 { rValue := mul(SCALE, 16) } case 100000000000000000000000000000000000 { rValue := mul(SCALE, 17) } case 1000000000000000000000000000000000000 { rValue := mul(SCALE, 18) } case 10000000000000000000000000000000000000 { rValue := mul(SCALE, 19) } case 100000000000000000000000000000000000000 { rValue := mul(SCALE, 20) } case 1000000000000000000000000000000000000000 { rValue := mul(SCALE, 21) } case 10000000000000000000000000000000000000000 { rValue := mul(SCALE, 22) } case 100000000000000000000000000000000000000000 { rValue := mul(SCALE, 23) } case 1000000000000000000000000000000000000000000 { rValue := mul(SCALE, 24) } case 10000000000000000000000000000000000000000000 { rValue := mul(SCALE, 25) } case 100000000000000000000000000000000000000000000 { rValue := mul(SCALE, 26) } case 1000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 27) } case 10000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 28) } case 100000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 29) } case 1000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 30) } case 10000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 31) } case 100000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 32) } case 1000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 33) } case 10000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 34) } case 100000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 35) } case 1000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 36) } case 10000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 37) } case 100000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 38) } case 1000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 39) } case 10000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 40) } case 100000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 41) } case 1000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 42) } case 10000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 43) } case 100000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 44) } case 1000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 45) } case 10000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 46) } case 100000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 47) } case 1000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 48) } case 10000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 49) } case 100000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 50) } case 1000000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 51) } case 10000000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 52) } case 100000000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 53) } case 1000000000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 54) } case 10000000000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 55) } case 100000000000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 56) } case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 57) } case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 58) } case 100000000000000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 59) } default { rValue := MAX_UD60x18 } } if (rValue != MAX_UD60x18) { result = PRBMath.UD60x18({ value: rValue }); } else { // Do the fixed-point division inline to save gas. The denominator is log2(10). unchecked { rValue = (log2(x).value * SCALE) / 3_321928094887362347; result = PRBMath.UD60x18({ value: rValue }); } } } /// @notice Calculates the binary logarithm of x. /// /// @dev Based on the iterative approximation algorithm. /// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation /// /// Requirements: /// - x must be greater than or equal to SCALE, otherwise the result would be negative. /// /// Caveats: /// - The results are nor perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation. /// /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the binary logarithm. /// @return result The binary logarithm as an unsigned 60.18-decimal fixed-point number. function log2(PRBMath.UD60x18 memory x) internal pure returns (PRBMath.UD60x18 memory result) { uint256 xValue = x.value; if (xValue < SCALE) { revert PRBMathUD60x18__LogInputTooSmall(xValue); } unchecked { // Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n). uint256 n = PRBMath.mostSignificantBit(xValue / SCALE); // The integer part of the logarithm as an unsigned 60.18-decimal fixed-point number. The operation can't overflow // because n is maximum 255 and SCALE is 1e18. uint256 rValue = n * SCALE; // This is y = x * 2^(-n). uint256 y = xValue >> n; // If y = 1, the fractional part is zero. if (y == SCALE) { return PRBMath.UD60x18({ value: rValue }); } // Calculate the fractional part via the iterative approximation. // The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster. for (uint256 delta = HALF_SCALE; delta > 0; delta >>= 1) { y = (y * y) / SCALE; // Is y^2 > 2 and so in the range [2,4)? if (y >= 2 * SCALE) { // Add the 2^(-m) factor to the logarithm. rValue += delta; // Corresponds to z/2 on Wikipedia. y >>= 1; } } result = PRBMath.UD60x18({ value: rValue }); } } /// @notice Multiplies two unsigned 60.18-decimal fixed-point numbers together, returning a new unsigned 60.18-decimal /// fixed-point number. /// @dev See the documentation for the "PRBMath.mulDivFixedPoint" function. /// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number. /// @param y The multiplier as an unsigned 60.18-decimal fixed-point number. /// @return result The product as an unsigned 60.18-decimal fixed-point number. function mul(PRBMath.UD60x18 memory x, PRBMath.UD60x18 memory y) internal pure returns (PRBMath.UD60x18 memory result) { result = PRBMath.UD60x18({ value: PRBMath.mulDivFixedPoint(x.value, y.value) }); } /// @notice Returns PI as an unsigned 60.18-decimal fixed-point number. function pi() internal pure returns (PRBMath.UD60x18 memory result) { result = PRBMath.UD60x18({ value: 3_141592653589793238 }); } /// @notice Raises x to the power of y. /// /// @dev Based on the insight that x^y = 2^(log2(x) * y). /// /// Requirements: /// - All from "exp2", "log2" and "mul". /// /// Caveats: /// - All from "exp2", "log2" and "mul". /// - Assumes 0^0 is 1. /// /// @param x Number to raise to given power y, as an unsigned 60.18-decimal fixed-point number. /// @param y Exponent to raise x to, as an unsigned 60.18-decimal fixed-point number. /// @return result x raised to power y, as an unsigned 60.18-decimal fixed-point number. function pow(PRBMath.UD60x18 memory x, PRBMath.UD60x18 memory y) internal pure returns (PRBMath.UD60x18 memory result) { if (x.value == 0) { return PRBMath.UD60x18({ value: y.value == 0 ? SCALE : uint256(0) }); } else { result = exp2(mul(log2(x), y)); } } /// @notice Raises x (unsigned 60.18-decimal fixed-point number) to the power of y (basic unsigned integer) using the /// famous algorithm "exponentiation by squaring". /// /// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring /// /// Requirements: /// - The result must fit within MAX_UD60x18. /// /// Caveats: /// - All from "mul". /// - Assumes 0^0 is 1. /// /// @param x The base as an unsigned 60.18-decimal fixed-point number. /// @param y The exponent as an uint256. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function powu(PRBMath.UD60x18 memory x, uint256 y) internal pure returns (PRBMath.UD60x18 memory result) { // Calculate the first iteration of the loop in advance. uint256 xValue = x.value; uint256 rValue = y & 1 > 0 ? xValue : SCALE; // Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster. for (y >>= 1; y > 0; y >>= 1) { xValue = PRBMath.mulDivFixedPoint(xValue, xValue); // Equivalent to "y % 2 == 1" but faster. if (y & 1 > 0) { rValue = PRBMath.mulDivFixedPoint(rValue, xValue); } } result = PRBMath.UD60x18({ value: rValue }); } /// @notice Returns 1 as an unsigned 60.18-decimal fixed-point number. function scale() internal pure returns (PRBMath.UD60x18 memory result) { result = PRBMath.UD60x18({ value: SCALE }); } /// @notice Calculates the square root of x, rounding down. /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Requirements: /// - x must be less than MAX_UD60x18 / SCALE. /// /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the square root. /// @return result The result as an unsigned 60.18-decimal fixed-point . function sqrt(PRBMath.UD60x18 memory x) internal pure returns (PRBMath.UD60x18 memory result) { unchecked { if (x.value > MAX_UD60x18 / SCALE) { revert PRBMathUD60x18__SqrtOverflow(x.value); } // Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two unsigned // 60.18-decimal fixed-point numbers together (in this case, those two numbers are both the square root). result = PRBMath.UD60x18({ value: PRBMath.sqrt(x.value * SCALE) }); } } /// @notice Subtracts one unsigned 60.18-decimal fixed-point number from another one, returning a new unsigned 60.18-decimal /// fixed-point number. /// @param x The minuend as an unsigned 60.18-decimal fixed-point number. /// @param y The subtrahend as an unsigned 60.18-decimal fixed-point number. /// @param result The difference as an unsigned 60.18 decimal fixed-point number. function sub(PRBMath.UD60x18 memory x, PRBMath.UD60x18 memory y) internal pure returns (PRBMath.UD60x18 memory result) { unchecked { if (x.value < y.value) { revert PRBMathUD60x18__SubUnderflow(x.value, y.value); } result = PRBMath.UD60x18({ value: x.value - y.value }); } } /// @notice Converts a unsigned 60.18-decimal fixed-point number to basic integer form, rounding down in the process. /// @param x The unsigned 60.18-decimal fixed-point number to convert. /// @return result The same number in basic integer form. function toUint(PRBMath.UD60x18 memory x) internal pure returns (uint256 result) { unchecked { result = x.value / SCALE; } } }
Note that the "mul" in this block is the assembly multiplication operation, not the "mul" function defined in this contract.
uint256 rValue;
1,827,478
[ 1, 8067, 716, 326, 315, 16411, 6, 316, 333, 1203, 353, 326, 19931, 23066, 1674, 16, 486, 326, 315, 16411, 6, 445, 2553, 316, 333, 6835, 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 ]
[ 1, 1, 1, 1, 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 ]
[ 1, 3639, 2254, 5034, 436, 620, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.17; /** * @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; /** * @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) onlyOwner public { if (newOwner != address(0)) { owner = newOwner; } } } /** * @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 allow actions only when the contract IS paused */ modifier whenNotPaused() { require (!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require (paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public returns (bool) { paused = false; Unpause(); return true; } } /** * @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 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 SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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; } } /** * @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){ 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 constant 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 Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * 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); _; } /** * @dev Function to mint tokens * @param _to The address that will recieve 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) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Transfer(0X0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract ReporterToken is MintableToken, Pausable{ string public name = "Reporter Token"; string public symbol = "NEWS"; uint256 public decimals = 18; bool public tradingStarted = false; /** * @dev modifier that throws if trading has not started yet */ modifier hasStartedTrading() { require(tradingStarted); _; } /** * @dev Allows the owner to enable the trading. This can not be undone */ function startTrading() public onlyOwner { tradingStarted = true; } /** * @dev Allows anyone to transfer the Reporter tokens once trading has started * @param _to the recipient address of the tokens. * @param _value number of tokens to be transfered. */ function transfer(address _to, uint _value) hasStartedTrading whenNotPaused public returns (bool) { return super.transfer(_to, _value); } /** * @dev Allows anyone to transfer the Reporter tokens once trading has started * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) hasStartedTrading whenNotPaused public returns (bool) { return super.transferFrom(_from, _to, _value); } function emergencyERC20Drain( ERC20 oddToken, uint amount ) public { oddToken.transfer(owner, amount); } } contract ReporterTokenSale is Ownable, Pausable{ using SafeMath for uint256; // The token being sold ReporterToken public token; uint256 public decimals; uint256 public oneCoin; // start and end block where investments are allowed (both inclusive) uint256 public startTimestamp; uint256 public endTimestamp; // address where funds are collected address public multiSig; function setWallet(address _newWallet) public onlyOwner { multiSig = _newWallet; } // These will be set by setTier() uint256 public rate; // how many token units a buyer gets per wei uint256 public minContribution = 0.0001 ether; // minimum contributio to participate in tokensale uint256 public maxContribution = 1000 ether; // default limit to tokens that the users can buy // *************************** // amount of raised money in wei uint256 public weiRaised; // amount of raised tokens uint256 public tokenRaised; // maximum amount of tokens being created uint256 public maxTokens; // maximum amount of tokens for sale uint256 public tokensForSale; // 36 Million Tokens for SALE // number of participants in presale uint256 public numberOfPurchasers = 0; // for whitelist address public cs; // for rate uint public r; // switch on/off the authorisation , default: false bool public freeForAll = false; mapping (address => bool) public authorised; // just to annoy the heck out of americans event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event SaleClosed(); function ReporterTokenSale() public { startTimestamp = 1508684400; // 22 Oct. 2017. 15:00 UTC endTimestamp = 1529074800; // (GMT): 2018. June 15., Friday 15:00:00 multiSig = 0xD00d085F125EAFEA9e8c5D3f4bc25e6D0c93Af0e; token = new ReporterToken(); decimals = token.decimals(); oneCoin = 10 ** decimals; maxTokens = 60 * (10**6) * oneCoin; tokensForSale = 36 * (10**6) * oneCoin; rate = 3000; } function currentTime() public constant returns (uint256) { return now; } /** * @dev Calculates the amount of bonus coins the buyer gets */ function setTier(uint newR) internal { // first 9M tokens get extra 42% of tokens, next half get 17% if (tokenRaised <= 9000000 * oneCoin) { rate = newR * 142/100; //minContribution = 100 ether; //maxContribution = 1000000 ether; } else if (tokenRaised <= 18000000 * oneCoin) { rate = newR * 117/100; //minContribution = 5 ether; //maxContribution = 1000000 ether; } else { rate = newR * 1; //minContribution = 0.01 ether; //maxContribution = 100 ether; } } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { if (currentTime() > endTimestamp) return true; if (tokenRaised >= tokensForSale) return true; // if we reach the tokensForSale return false; } /** * @dev throws if person sending is not contract owner or cs role */ modifier onlyCSorOwner() { require((msg.sender == owner) || (msg.sender==cs)); _; } modifier onlyCS() { require(msg.sender == cs); _; } /** * @dev throws if person sending is not authorised or sends nothing */ modifier onlyAuthorised() { require (authorised[msg.sender] || freeForAll); require (currentTime() >= startTimestamp); require (!hasEnded()); require (multiSig != 0x0); require(tokensForSale > tokenRaised); // check we are not over the number of tokensForSale _; } /** * @dev authorise an account to participate */ function authoriseAccount(address whom) onlyCSorOwner public { authorised[whom] = true; } /** * @dev authorise a lot of accounts in one go */ function authoriseManyAccounts(address[] many) onlyCSorOwner public { for (uint256 i = 0; i < many.length; i++) { authorised[many[i]] = true; } } /** * @dev ban an account from participation (default) */ function blockAccount(address whom) onlyCSorOwner public { authorised[whom] = false; } /** * @dev set a new CS representative */ function setCS(address newCS) onlyOwner public { cs = newCS; } /** * @dev set a newRate if have a big different in ether/dollar rate */ function setRate(uint newRate) onlyCS public { require(0 < newRate && newRate <= 8000); r = newRate; } function placeTokens(address beneficiary, uint256 _tokens) onlyCS public { //check minimum and maximum amount require(_tokens != 0); require(!hasEnded()); uint256 amount = 0; if (token.balanceOf(beneficiary) == 0) { numberOfPurchasers++; } tokenRaised = tokenRaised.add(_tokens); // so we can go slightly over token.mint(beneficiary, _tokens); TokenPurchase(beneficiary, amount, _tokens); } // low level token purchase function function buyTokens(address beneficiary, uint256 amount) onlyAuthorised whenNotPaused internal { setTier(r); //check minimum and maximum amount require(amount >= minContribution); require(amount <= maxContribution); // calculate token amount to be created uint256 tokens = amount.mul(rate); // update state weiRaised = weiRaised.add(amount); if (token.balanceOf(beneficiary) == 0) { numberOfPurchasers++; } tokenRaised = tokenRaised.add(tokens); // so we can go slightly over token.mint(beneficiary, tokens); TokenPurchase(beneficiary, amount, tokens); multiSig.transfer(this.balance); // better in case any other ether ends up here } // transfer ownership of the token to the owner of the presale contract function finishSale() public onlyOwner { require(hasEnded()); // assign the rest of the 60M tokens to the reserve uint unassigned; if(maxTokens > tokenRaised) { unassigned = maxTokens.sub(tokenRaised); token.mint(multiSig,unassigned); } token.finishMinting(); token.transferOwnership(owner); SaleClosed(); } // fallback function can be used to buy tokens function () public payable { buyTokens(msg.sender, msg.value); } function emergencyERC20Drain( ERC20 oddToken, uint amount ) public { oddToken.transfer(owner, amount); } }
* @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; function Ownable() public { owner = msg.sender; } modifier onlyOwner(){ require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { if (newOwner != address(0)) { owner = newOwner; } } function transferOwnership(address newOwner) onlyOwner public { if (newOwner != address(0)) { owner = newOwner; } } }
640,032
[ 1, 5460, 429, 225, 1021, 14223, 6914, 6835, 711, 392, 3410, 1758, 16, 471, 8121, 5337, 6093, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 14223, 6914, 288, 203, 565, 1758, 1071, 3410, 31, 203, 203, 203, 565, 445, 14223, 6914, 1435, 1071, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 203, 565, 9606, 1338, 5541, 1435, 95, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1338, 5541, 1071, 288, 203, 3639, 309, 261, 2704, 5541, 480, 1758, 12, 20, 3719, 288, 203, 5411, 3410, 273, 394, 5541, 31, 203, 3639, 289, 203, 565, 289, 203, 565, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1338, 5541, 1071, 288, 203, 3639, 309, 261, 2704, 5541, 480, 1758, 12, 20, 3719, 288, 203, 5411, 3410, 273, 394, 5541, 31, 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, -100, -100, -100, -100, -100, -100, -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 // File: @openzeppelin/contracts-ethereum-package/contracts/math/Math.sol pragma solidity ^0.6.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; } } /** * @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 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 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; } } 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); } } /** * @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 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 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. * 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 { using SafeMath for uint256; function safeTransfer( IERC20 token, address to, uint256 value ) internal { require(token.transfer(to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `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) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { 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, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { 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 Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This 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 amount) internal { 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 Destroys `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, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } uint256[50] private ______gap; } interface IStrategy { function unsalvagableTokens(address tokens) external view returns (bool); function governance() external view returns (address); function controller() external view returns (address); function underlying() external view returns (address); function vault() external view returns (address); function withdrawAllToVault() external; function withdrawToVault(uint256 amount) external; function investedUnderlyingBalance() external view returns (uint256); // itsNotMuch() // should only be called by controller function salvage(address recipient, address token, uint256 amount) external; function doHardWork() external; function depositArbCheck() external view returns(bool); } contract VaultUSDC is ERC20, Ownable { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; event Withdraw(address indexed beneficiary, uint256 amount); event Deposit(address indexed beneficiary, uint256 amount); event Invest(uint256 amount); event NewStratCandidate(address implementation); event UpgradeStrat(address implementation); struct StratCandidate { address implementation; uint256 proposedTime; } // The last proposed strategy to switch to. StratCandidate public stratCandidate; // The strategy currently in use by the vault. address public strategy; // The token the vault accepts and looks to maximize. address public underlying; // The minimum time it has to pass before a strat candidate can be approved. uint256 public immutable approvalDelay; uint256 public underlyingUnit; uint256 public fractionToInvestNumerator = 96; uint256 public fractionToInvestDenominator = 100; constructor( address _underlying, string memory _name, string memory _symbol, uint256 _approvalDelay ) public ERC20(_name, _symbol) { underlying = _underlying; approvalDelay = _approvalDelay; underlyingUnit = 10 ** uint256(ERC20(underlying).decimals()); } modifier whenStrategyDefined() { require(strategy != address(0), "Strategy must be defined"); _; } /** * Chooses the best strategy and re-invests. If the strategy did not change, it just calls * doHardWork on the current strategy. Call this to claim hard rewards. */ function doHardWork() whenStrategyDefined external { // ensure that new funds are invested too invest(); IStrategy(strategy).doHardWork(); } /* * Returns the cash balance across all users in this contract. */ function underlyingBalanceInVault() view public returns (uint256) { return IERC20(underlying).balanceOf(address(this)); } /* Returns the current underlying (e.g., DAI's) balance together with * the invested amount (if DAI is invested elsewhere by the strategy). */ function underlyingBalanceWithInvestment() view public returns (uint256) { if (strategy == address(0)) { // initial state, when not set return underlyingBalanceInVault(); } return underlyingBalanceInVault().add(IStrategy(strategy).investedUnderlyingBalance()); } function getPricePerFullShare() public view returns (uint256) { return totalSupply() == 0 ? underlyingUnit : underlyingUnit.mul(underlyingBalanceWithInvestment()).div(totalSupply()); } /* get the user's share (in underlying) */ function underlyingBalanceWithInvestmentForHolder(address holder) view external returns (uint256) { if (totalSupply() == 0) { return 0; } return underlyingBalanceWithInvestment() .mul(balanceOf(holder)) .div(totalSupply()); } /** * @dev Sets the candidate for the new strat to use with this vault. * @param _implementation The address of the candidate strategy. */ function proposeStrat(address _implementation) public onlyOwner { stratCandidate = StratCandidate({ implementation: _implementation, proposedTime: block.timestamp }); emit NewStratCandidate(_implementation); } /** * @dev It switches the active strat for the strat candidate. After upgrading, the * candidate implementation is set to the 0x00 address, and proposedTime to a time * happening in +100 years for safety. */ function upgradeStrat() public onlyOwner { require( stratCandidate.implementation != address(0), "There is no candidate" ); require( stratCandidate.proposedTime.add(approvalDelay) < block.timestamp, "Delay has not passed" ); if (strategy != stratCandidate.implementation) { require(IStrategy(stratCandidate.implementation).underlying() == underlying, "Vault underlying must match Strategy underlying"); require(IStrategy(stratCandidate.implementation).vault() == address(this), "the strategy does not belong to this vault"); if (strategy != address(0)) { // if the original strategy (no underscore) is defined IERC20(underlying).safeApprove(strategy, 0); IStrategy(strategy).withdrawAllToVault(); } strategy = stratCandidate.implementation; stratCandidate.implementation = address(0); stratCandidate.proposedTime = 0; IERC20(underlying).safeApprove(address(strategy), 0); IERC20(underlying).safeApprove(address(strategy), uint256(~0)); emit UpgradeStrat(stratCandidate.implementation); } } function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external onlyOwner { require(denominator > 0, "denominator must be greater than 0"); require(numerator <= denominator, "denominator must be greater than or equal to the numerator"); fractionToInvestNumerator = numerator; fractionToInvestDenominator = denominator; } function rebalance() external onlyOwner { withdrawAll(); invest(); } function availableToInvestOut() public view returns (uint256) { uint256 wantInvestInTotal = underlyingBalanceWithInvestment() .mul(fractionToInvestNumerator) .div(fractionToInvestDenominator); uint256 alreadyInvested = IStrategy(strategy).investedUnderlyingBalance(); if (alreadyInvested >= wantInvestInTotal) { return 0; } else { uint256 remainingToInvest = wantInvestInTotal.sub(alreadyInvested); return remainingToInvest <= underlyingBalanceInVault() // TODO: we think that the "else" branch of the ternary operation is not // going to get hit ? remainingToInvest : underlyingBalanceInVault(); } } function invest() internal whenStrategyDefined { uint256 availableAmount = availableToInvestOut(); if (availableAmount > 0) { IERC20(underlying).safeTransfer(strategy, availableAmount); emit Invest(availableAmount); } } /* * Allows for depositing the underlying asset in exchange for shares. * Approval is assumed. */ function deposit(uint256 amount) external { _deposit(amount, msg.sender, msg.sender); } /* * Allows for depositing the underlying asset in exchange for shares * assigned to the holder. * This facilitates depositing for someone else (using DepositHelper) */ function depositFor(uint256 amount, address holder) public { _deposit(amount, msg.sender, holder); } function withdrawAll() public onlyOwner whenStrategyDefined { IStrategy(strategy).withdrawAllToVault(); } function withdraw(uint256 numberOfShares) external { require(totalSupply() > 0, "Vault has no shares"); require(numberOfShares > 0, "numberOfShares must be greater than 0"); uint256 totalSupply = totalSupply(); _burn(msg.sender, numberOfShares); uint256 underlyingAmountToWithdraw = underlyingBalanceWithInvestment() .mul(numberOfShares) .div(totalSupply); if (underlyingAmountToWithdraw > underlyingBalanceInVault()) { // withdraw everything from the strategy to accurately check the share value if (numberOfShares == totalSupply) { IStrategy(strategy).withdrawAllToVault(); } else { uint256 missing = underlyingAmountToWithdraw.sub(underlyingBalanceInVault()); IStrategy(strategy).withdrawToVault(missing); } // recalculate to improve accuracy underlyingAmountToWithdraw = Math.min(underlyingBalanceWithInvestment() .mul(numberOfShares) .div(totalSupply), underlyingBalanceInVault()); } IERC20(underlying).safeTransfer(msg.sender, underlyingAmountToWithdraw); // update the withdrawal amount for the holder emit Withdraw(msg.sender, underlyingAmountToWithdraw); } function _deposit(uint256 amount, address sender, address beneficiary) internal { require(amount > 0, "Cannot deposit 0"); require(beneficiary != address(0), "holder must be defined"); if (address(strategy) != address(0)) { require(IStrategy(strategy).depositArbCheck(), "Too much arb"); } uint256 toMint = totalSupply() == 0 ? amount : amount.mul(totalSupply()).div(underlyingBalanceWithInvestment()); _mint(beneficiary, toMint); IERC20(underlying).safeTransferFrom(sender, address(this), amount); // update the contribution amount for the beneficiary emit Deposit(beneficiary, amount); } }
update the withdrawal amount for the holder
emit Withdraw(msg.sender, underlyingAmountToWithdraw);
209,143
[ 1, 2725, 326, 598, 9446, 287, 3844, 364, 326, 10438, 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, 3626, 3423, 9446, 12, 3576, 18, 15330, 16, 6808, 6275, 774, 1190, 9446, 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, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /// @title JPEGCardsCigStaking /// @notice This contract allows JPEG Cards cigarette holders to stake one of their cigarettes to /// increase the liquidation limit rate and credit limit rate when borrowing from {NFTVault}. contract JPEGCardsCigStaking is Ownable, ReentrancyGuard, Pausable { event Deposit(address indexed account, uint256 indexed cardIndex); event Withdrawal(address indexed account, uint256 indexed cardIndex); struct UserData { uint256 stakedCig; bool isStaking; } IERC721 public immutable cards; mapping(uint256 => bool) public cigs; mapping(address => UserData) public userData; constructor(IERC721 _cards, uint256[] memory _cigList) { require(address(_cards) != address(0), "INVALID_ADDRESS"); uint256 length = _cigList.length; require(length > 0, "INVALID_LIST"); cards = _cards; for (uint i; i < length; ++i) { cigs[_cigList[i]] = true; } _pause(); } /// @notice Allows users to deposit one of their cigarette JPEG cards. /// @param _idx The index of the NFT to stake. function deposit(uint256 _idx) external nonReentrant whenNotPaused { require(cigs[_idx], "NOT_CIG"); UserData storage data = userData[msg.sender]; require(!data.isStaking, "CANNOT_STAKE_MULTIPLE"); data.isStaking = true; data.stakedCig = _idx; cards.transferFrom(msg.sender, address(this), _idx); emit Deposit(msg.sender, _idx); } /// @notice Allows users to withdraw their staked cigarette JPEG card. /// @param _idx The index of the NFT to unstake. function withdraw(uint256 _idx) external nonReentrant whenNotPaused { UserData storage data = userData[msg.sender]; require(data.stakedCig == _idx && data.isStaking, "NOT_STAKED"); data.isStaking = false; data.stakedCig = 0; cards.safeTransferFrom(address(this), msg.sender, _idx); emit Withdrawal(msg.sender, _idx); } /// @notice Allows the DAO to add a card to the list of cigarettes. /// @param _idx The index of the card. function addCig(uint256 _idx) external onlyOwner { cigs[_idx] = true; } /// @notice Allows the DAO to pause deposits/withdrawals function pause() external onlyOwner { _pause(); } /// @notice Allows the DAO to unpause deposits/withdrawals function unpause() external onlyOwner { _unpause(); } /// @return Whether the user is staking a cigarette or not. function isUserStaking(address _user) external view returns (bool) { return userData[_user].isStaking; } } // SPDX-License-Identifier: MIT // 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; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^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() { _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); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/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 // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // 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; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^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); }
@title JPEGCardsCigStaking @notice This contract allows JPEG Cards cigarette holders to stake one of their cigarettes to increase the liquidation limit rate and credit limit rate when borrowing from {NFTVault}.
contract JPEGCardsCigStaking is Ownable, ReentrancyGuard, Pausable { event Deposit(address indexed account, uint256 indexed cardIndex); event Withdrawal(address indexed account, uint256 indexed cardIndex); pragma solidity ^0.8.4; struct UserData { uint256 stakedCig; bool isStaking; } IERC721 public immutable cards; mapping(uint256 => bool) public cigs; mapping(address => UserData) public userData; constructor(IERC721 _cards, uint256[] memory _cigList) { require(address(_cards) != address(0), "INVALID_ADDRESS"); uint256 length = _cigList.length; require(length > 0, "INVALID_LIST"); cards = _cards; for (uint i; i < length; ++i) { cigs[_cigList[i]] = true; } _pause(); } constructor(IERC721 _cards, uint256[] memory _cigList) { require(address(_cards) != address(0), "INVALID_ADDRESS"); uint256 length = _cigList.length; require(length > 0, "INVALID_LIST"); cards = _cards; for (uint i; i < length; ++i) { cigs[_cigList[i]] = true; } _pause(); } function deposit(uint256 _idx) external nonReentrant whenNotPaused { require(cigs[_idx], "NOT_CIG"); UserData storage data = userData[msg.sender]; require(!data.isStaking, "CANNOT_STAKE_MULTIPLE"); data.isStaking = true; data.stakedCig = _idx; cards.transferFrom(msg.sender, address(this), _idx); emit Deposit(msg.sender, _idx); } function withdraw(uint256 _idx) external nonReentrant whenNotPaused { UserData storage data = userData[msg.sender]; require(data.stakedCig == _idx && data.isStaking, "NOT_STAKED"); data.isStaking = false; data.stakedCig = 0; cards.safeTransferFrom(address(this), msg.sender, _idx); emit Withdrawal(msg.sender, _idx); } function addCig(uint256 _idx) external onlyOwner { cigs[_idx] = true; } function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } function isUserStaking(address _user) external view returns (bool) { return userData[_user].isStaking; } }
1,740,064
[ 1, 28698, 30492, 39, 360, 510, 6159, 225, 1220, 6835, 5360, 28038, 14338, 87, 276, 360, 20731, 736, 366, 4665, 358, 384, 911, 1245, 434, 3675, 276, 360, 834, 748, 281, 358, 10929, 326, 4501, 26595, 367, 1800, 4993, 471, 12896, 1800, 4993, 1347, 29759, 310, 628, 288, 50, 4464, 12003, 5496, 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, 16351, 28038, 30492, 39, 360, 510, 6159, 353, 14223, 6914, 16, 868, 8230, 12514, 16709, 16, 21800, 16665, 288, 203, 203, 565, 871, 4019, 538, 305, 12, 2867, 8808, 2236, 16, 2254, 5034, 8808, 5270, 1016, 1769, 203, 565, 871, 3423, 9446, 287, 12, 2867, 8808, 2236, 16, 2254, 5034, 8808, 5270, 1016, 1769, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 1958, 31109, 288, 203, 3639, 2254, 5034, 384, 9477, 39, 360, 31, 203, 3639, 1426, 353, 510, 6159, 31, 203, 565, 289, 203, 203, 565, 467, 654, 39, 27, 5340, 1071, 11732, 18122, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 1426, 13, 1071, 276, 360, 87, 31, 203, 565, 2874, 12, 2867, 516, 31109, 13, 1071, 13530, 31, 203, 203, 565, 3885, 12, 45, 654, 39, 27, 5340, 389, 3327, 87, 16, 2254, 5034, 8526, 3778, 389, 71, 360, 682, 13, 288, 203, 3639, 2583, 12, 2867, 24899, 3327, 87, 13, 480, 1758, 12, 20, 3631, 315, 9347, 67, 15140, 8863, 203, 203, 3639, 2254, 5034, 769, 273, 389, 71, 360, 682, 18, 2469, 31, 203, 3639, 2583, 12, 2469, 405, 374, 16, 315, 9347, 67, 7085, 8863, 203, 203, 3639, 18122, 273, 389, 3327, 87, 31, 203, 3639, 364, 261, 11890, 277, 31, 277, 411, 769, 31, 965, 77, 13, 288, 203, 5411, 276, 360, 87, 63, 67, 71, 360, 682, 63, 77, 13563, 273, 638, 31, 203, 3639, 289, 203, 203, 3639, 389, 19476, 5621, 203, 565, 289, 203, 203, 565, 2 ]