contract_name
stringlengths
1
61
file_path
stringlengths
5
50.4k
contract_address
stringlengths
42
42
language
stringclasses
1 value
class_name
stringlengths
1
61
class_code
stringlengths
4
330k
class_documentation
stringlengths
0
29.1k
class_documentation_type
stringclasses
6 values
func_name
stringlengths
0
62
func_code
stringlengths
1
303k
func_documentation
stringlengths
2
14.9k
func_documentation_type
stringclasses
4 values
compiler_version
stringlengths
15
42
license_type
stringclasses
14 values
swarm_source
stringlengths
0
71
meta
dict
__index_level_0__
int64
0
60.4k
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
withdrawERC20Tokens
function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); }
// Function to withdraw any ERC20 tokens
LineComment
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 11351, 11668 ] }
58,361
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
approveGameContract
function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; }
// Admin can approve (or disapprove) game contracts
LineComment
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 11733, 11921 ] }
58,362
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
setPaths
function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; }
// Admin function to set _pathStart and _pathEnd
LineComment
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 11982, 12591 ] }
58,363
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
addNewItem
function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); }
/* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */
Comment
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 12711, 13344 ] }
58,364
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
addNewItemAndTransfer
function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); }
/* Admin can add new item template and send it to receiver in one call */
Comment
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 13436, 14107 ] }
58,365
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
createFromTemplate
function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; }
/* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */
Comment
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 14370, 15227 ] }
58,366
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
changeFeaturesForItem
function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); }
/* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */
Comment
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 15442, 16215 ] }
58,367
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
getFeaturesOfItem
function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; }
/* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */
Comment
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 17384, 17827 ] }
58,368
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
uint2str
function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); }
/* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */
Comment
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 18200, 18727 ] }
58,369
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
addTreasureChest
function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; }
/* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */
Comment
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 19106, 19315 ] }
58,370
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
burn
function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } }
/* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */
Comment
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 19673, 20016 ] }
58,371
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
_burn
function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; }
// Burn owner's tokenId
LineComment
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 20053, 20903 ] }
58,372
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
totalSupply
function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; }
// Return the total supply
LineComment
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 21061, 21413 ] }
58,373
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
tokenByIndex
function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; }
// Return the templateId of _index token
LineComment
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 21466, 21685 ] }
58,374
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
tokenOfOwnerByIndex
function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; }
// Return The token templateId for the index'th token assigned to owner
LineComment
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 21769, 22041 ] }
58,375
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
name
function name() external view returns(string memory) { return _name; }
/** * @dev Gets the token name * @return string representing the token name */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 22146, 22271 ] }
58,376
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
symbol
function symbol() external view returns(string memory) { return _symbol; }
/** * @dev Gets the token symbol * @return string representing the token symbol */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 22380, 22509 ] }
58,377
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
tokenURI
function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); }
/** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 22710, 23063 ] }
58,378
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
balanceOf
function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; }
/** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 23268, 23477 ] }
58,379
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
ownerOf
function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; }
/** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 23703, 24062 ] }
58,380
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
approve
function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); }
/** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 24488, 24834 ] }
58,381
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
getApproved
function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; }
/** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 25122, 25331 ] }
58,382
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
setApprovalForAll
function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); }
/** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 25626, 25900 ] }
58,383
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
isApprovedForAll
function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; }
/** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 26224, 26437 ] }
58,384
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
transferFrom
function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); }
/** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 26875, 27114 ] }
58,385
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
safeTransferFrom
function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); }
/** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 27762, 28002 ] }
58,386
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
safeTransferFrom
function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); }
/** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 28716, 29047 ] }
58,387
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
_exists
function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); }
/** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 29238, 29449 ] }
58,388
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
_isApprovedOrOwner
function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); }
/** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 29816, 30344 ] }
58,389
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
_mint
function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); }
/** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 30590, 30907 ] }
58,390
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
_transferFrom
function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); }
/** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 31285, 31756 ] }
58,391
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
_checkOnERC721Received
function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); }
/** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 32285, 32779 ] }
58,392
Inventory
Inventory.sol
0x9680223f7069203e361f55fefc89b7c1a952cdcc
Solidity
Inventory
contract Inventory is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; string private _pathStart; string private _pathEnd; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Treasure chest reward token (VIDYA) ERC20Token public constant treasureChestRewardToken = ERC20Token(0x3D3D35bb9bEC23b06Ca00fe472b50E7A4c692C30); // Uniswap token ERC20Token public constant UNI_ADDRESS = ERC20Token(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984); // Unicorn's Head uint256 private constant UNICORN_TEMPLATE_ID = 11; uint256 public UNICORN_TOTAL_SUPPLY = 0; mapping (address => bool) public unicornClaimed; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping of contract addresses that are allowed to edit item features mapping (address => bool) private _approvedGameContract; // Mapping from token ID to respective treasure chest rewards in VIDYA tokens mapping (uint256 => uint256) public treasureChestRewards; // Mapping to calculate how many treasure hunts an address has participated in mapping (address => uint256) public treasureHuntPoints; // Mapping for the different equipment items of each address/character // 0 - head, 1 - left hand, 2 - neck, 3 - right hand, 4 - chest, 5 - legs mapping (address => uint256[6]) public characterEquipment; // To check if a template exists mapping (uint256 => bool) _templateExists; /* Item struct holds the templateId, a total of 4 additional features and the burned status */ struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; } /* Template struct holds the uri for each Item- a reference to the json file which describes them */ struct Template { string uri; } // All items created, ever, both burned and not burned Item[] public allItems; // Admin editable templates for each item Template[] public itemTemplates; modifier onlyApprovedGame() { require(_approvedGameContract[msg.sender], "msg.sender is not an approved game contract"); _; } modifier tokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token does not exist"); _; } modifier isOwnedByOrigin(uint256 _tokenId) { require(ownerOf(_tokenId) == tx.origin, "tx.origin is not the token owner"); _; } modifier isOwnerOrApprovedGame(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || _approvedGameContract[msg.sender], "Not owner or approved game"); _; } modifier templateExists(uint256 _templateId) { require(_templateExists[_templateId], "Template does not exist"); _; } constructor() public { _name = "Inventory"; _symbol = "ITEM"; _pathStart = "https://team3d.io/inventory/json/"; _pathEnd = ".json"; _registerInterface(InterfaceId_ERC721Metadata); _registerInterface(_InterfaceId_ERC721Enumerable); _registerInterface(_InterfaceId_ERC721); // Add the "nothing" item to msg.sender // This is a dummy item so that valid items in allItems start with 1 addNewItem(0,0); } // Get the Unicorn's head item function mintUnicorn() external { uint256 id; require(UNICORN_TOTAL_SUPPLY < 100, "Unicorns are now extinct"); require(!unicornClaimed[msg.sender], "You have already claimed a unicorn"); require(UNI_ADDRESS.balanceOf(msg.sender) >= 1000 * 10**18, "Min balance 1000 UNI"); require(_templateExists[UNICORN_TEMPLATE_ID], "Unicorn template has not been added yet"); checkAndTransferVIDYA(1000 * 10**18); // Unicorn's head costs 1000 VIDYA id = allItems.push(Item(UNICORN_TEMPLATE_ID,0,0,0,0,0,false)) -1; UNICORN_TOTAL_SUPPLY = UNICORN_TOTAL_SUPPLY.add(1); unicornClaimed[msg.sender] = true; // Materialize _mint(msg.sender, id); } function checkAndTransferVIDYA(uint256 _amount) private { require(treasureChestRewardToken.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed"); } function equip( uint256 _tokenId, uint8 _equipmentPosition ) external tokenExists(_tokenId) { require(_equipmentPosition < 6); require(allItems[_tokenId].equipmentPosition == _equipmentPosition, "Item cannot be equipped in this slot"); characterEquipment[msg.sender][_equipmentPosition] = _tokenId; } function unequip( uint8 _equipmentPosition ) external { require(_equipmentPosition < 6); characterEquipment[msg.sender][_equipmentPosition] = 0; } function getEquipment( address player ) public view returns(uint256[6] memory) { return characterEquipment[player]; } // The total supply of any one item // Ask for example how many of "Torch" item exist function getIndividualCount( uint256 _templateId ) public view returns(uint256) { uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If match found & is not burned if (allItems[i].templateId == _templateId && !allItems[i].burned) { counter++; } } // Total supply of item using the _templateId return counter; } // Total supply of any one item owned by _owner // Ask for example how many of "Torch" item does the _owner have function getIndividualOwnedCount( uint256 _templateId, address _owner ) public view returns(uint256) { uint counter = 0; uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { /* If ownedItems[i]'s templateId matches the one in allItems[] */ if(allItems[ownedItems[i]].templateId == _templateId) { counter++; } } // Total supply of _templateId that _owner owns return counter; } // Given a _tokenId returns how many other tokens exist with // the same _templateId function getIndividualCountByID( uint256 _tokenId ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for for(uint i = 0; i < allItems.length; i++) { if(templateId == allItems[i].templateId && !allItems[i].burned) { counter++; } } return counter; } // Given a _tokenId returns how many other tokens the _owner has // with the same _templateId function getIndividualOwnedCountByID( uint256 _tokenId, address _owner ) public view tokenExists(_tokenId) returns(uint256) { uint256 counter = 0; uint256 templateId = allItems[_tokenId].templateId; // templateId we are looking for uint[] memory ownedItems = getItemsByOwner(_owner); for(uint i = 0; i < ownedItems.length; i++) { // The item cannot be burned because of getItemsByOwner(_owner), no need to check if(templateId == allItems[ownedItems[i]].templateId) { counter++; } } return counter; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds */ function getTemplateCountsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualCountByID(_tokenIds[i]); } return counts; } /* Given an array of _tokenIds return the corresponding _templateId count for each of those _tokenIds that the _owner owns */ function getTemplateCountsByTokenIDsOfOwner( uint[] memory _tokenIds, address _owner ) public view returns(uint[] memory) { uint[] memory counts = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { counts[i] = getIndividualOwnedCountByID(_tokenIds[i], _owner); } return counts; } /* Given an array of _tokenIds return the corresponding _templateIds for each of those _tokenIds Useful for cross referencing / weeding out duplicates to populate the UI */ function getTemplateIDsByTokenIDs( uint[] memory _tokenIds ) public view returns(uint[] memory) { uint[] memory templateIds = new uint[](_tokenIds.length); for(uint i = 0; i < _tokenIds.length; i++) { templateIds[i] = allItems[_tokenIds[i]].templateId; } return templateIds; } // Get all the item id's by owner function getItemsByOwner( address _owner ) public view returns(uint[] memory) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < allItems.length; i++) { // If owner is _owner and token is not burned if (_tokenOwner[i] == _owner && !allItems[i].burned) { result[counter] = i; counter++; } } // Array of ID's in allItems that _owner owns return result; } // Function to withdraw any ERC20 tokens function withdrawERC20Tokens( address _tokenContract ) external onlyOwner returns(bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // Admin can approve (or disapprove) game contracts function approveGameContract( address _game, bool _status ) external onlyOwner { _approvedGameContract[_game] = _status; } // Admin function to set _pathStart and _pathEnd function setPaths( string calldata newPathStart, string calldata newPathEnd ) external onlyOwner returns(bool) { bool success; if(keccak256(abi.encodePacked(_pathStart)) != keccak256(abi.encodePacked(newPathStart))) { _pathStart = newPathStart; success = true; } if(keccak256(abi.encodePacked(_pathEnd)) != keccak256(abi.encodePacked(newPathEnd))) { _pathEnd = newPathEnd; success = true; } return success; } /* Admin can add new item template The _templateId is a reference to Template struct in itemTemplates[] */ function addNewItem( uint256 _templateId, uint8 _equipmentPosition ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(msg.sender, id); } /* Admin can add new item template and send it to receiver in one call */ function addNewItemAndTransfer( uint256 _templateId, uint8 _equipmentPosition, address receiver ) public onlyOwner { uint256 id; // Does the _templateId exist or do we need to add it? if(!_templateExists[_templateId]) { // Add template id for this item as reference itemTemplates.push(Template(uint2str(_templateId))); _templateExists[_templateId] = true; } id = allItems.push(Item(_templateId,0,0,0,0,_equipmentPosition,false)) -1; // Materialize _mint(receiver, id); } /* Allows approved game contracts to create new items from already existing templates (added by admin) In other words this function allows a game to spawn more of ie. "Torch" and set its default features etc */ function createFromTemplate( uint256 _templateId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public templateExists(_templateId) onlyApprovedGame returns(uint256) { uint256 id; address player = tx.origin; id = allItems.push( Item( _templateId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition, false ) ) -1; // Materialize to tx.origin (and not msg.sender aka. the game contract) _mint(player, id); // id of the new item return id; } /* Change feature values of _tokenId Only succeeds when: the tx.origin (a player) owns the item the msg.sender (game contract) is a manually approved game address */ function changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) public onlyApprovedGame // msg.sender has to be a manually approved game address tokenExists(_tokenId) // check if _tokenId exists in the first place isOwnedByOrigin(_tokenId) // does the tx.origin (player in a game) own the token? returns(bool) { return ( _changeFeaturesForItem( _tokenId, _feature1, _feature2, _feature3, _feature4, _equipmentPosition ) ); } function _changeFeaturesForItem( uint256 _tokenId, uint8 _feature1, uint8 _feature2, uint8 _feature3, uint8 _feature4, uint8 _equipmentPosition ) internal returns(bool) { Item storage item = allItems[_tokenId]; if(item.feature1 != _feature1) { item.feature1 = _feature1; } if(item.feature2 != _feature2) { item.feature2 = _feature2; } if(item.feature3 != _feature3) { item.feature3 = _feature3; } if(item.feature4 != _feature4) { item.feature4 = _feature4; } if(item.equipmentPosition != _equipmentPosition) { item.equipmentPosition = _equipmentPosition; } return true; } /* Features of _tokenId Useful in various games where the _tokenId should have traits etc. Example: a "Torch" could start with 255 and degrade during gameplay over time Note: maximum value for uint8 type is 255 */ function getFeaturesOfItem( uint256 _tokenId ) public view returns(uint8[] memory) { Item storage item = allItems[_tokenId]; uint8[] memory features = new uint8[](4); features[0] = item.feature1; features[1] = item.feature2; features[2] = item.feature3; features[3] = item.feature4; return features; } /* Turn uint256 into a string Reason: ERC721 standard needs token uri to return as string, but we don't want to store long urls to the json files on-chain. Instead we use this returned string (which is actually just an ID) and say to front ends that the token uri can be found at somethingsomething.io/tokens/<id>.json */ function uint2str( uint256 i ) internal pure returns(string memory) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function append( string memory a, string memory b, string memory c ) internal pure returns(string memory) { return string( abi.encodePacked(a, b, c) ); } /* * Adds an NFT and the corresponding reward for whoever finds it and burns it. */ function addTreasureChest(uint256 _tokenId, uint256 _rewardsAmount) external tokenExists(_tokenId) onlyApprovedGame { treasureChestRewards[_tokenId] = _rewardsAmount; } /* Burn the _tokenId Succeeds when: token exists msg.sender is either direct owner of the token OR msg.sender is a manually approved game contract If tx.origin and msg.sender are different, burn the _tokenId of the tx.origin (the player, not the game contract) */ function burn( uint256 _tokenId ) public tokenExists(_tokenId) isOwnerOrApprovedGame(_tokenId) returns(bool) { if (tx.origin == msg.sender) { return _burn(_tokenId, msg.sender); } else { return _burn(_tokenId, tx.origin); } } // Burn owner's tokenId function _burn( uint256 _tokenId, address owner ) internal returns(bool) { // Set burned status on token allItems[_tokenId].burned = true; // Set new owner to 0x0 _tokenOwner[_tokenId] = address(0); // Remove from old owner _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); // Check if it's a treasure hunt token uint256 treasureChestRewardsForToken = treasureChestRewards[_tokenId]; if (treasureChestRewardsForToken > 0) { treasureChestRewardToken.transfer(msg.sender, treasureChestRewardsForToken); treasureHuntPoints[owner]++; } // Fire event emit Transfer(owner, address(0), _tokenId); return true; } function getLevel(address player) public view returns(uint256) { return treasureHuntPoints[player]; } // Return the total supply function totalSupply() public view returns(uint256) { uint256 counter; for(uint i = 0; i < allItems.length; i++) { if(!allItems[i].burned) { counter++; } } // All tokens which are not burned return counter; } // Return the templateId of _index token function tokenByIndex( uint256 _index ) public view returns(uint256) { require(_index < totalSupply()); return allItems[_index].templateId; } // Return The token templateId for the index'th token assigned to owner function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getItemsByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns(string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI( uint256 tokenId ) external view returns(string memory) { require(_exists(tokenId)); uint256 tokenTemplateId = allItems[tokenId].templateId; string memory id = uint2str(tokenTemplateId); return append(_pathStart, id, _pathEnd); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf( address owner ) public view returns(uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view returns(address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); require(!allItems[tokenId].burned, "This token is burned"); // Probably useless require at this point return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve( address to, uint256 tokenId ) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved( uint256 tokenId ) public view returns(address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll( address to, bool approved ) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists( uint256 tokenId ) internal view returns(bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns(bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint( address to, uint256 tokenId ) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom( address from, address to, uint256 tokenId ) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns(bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
_clearApproval
function _clearApproval( uint256 tokenId ) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } }
/** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://3d6f0cf075dd3e4b74e4524d3514f301990ef7f34c54193bd247324d93b04317
{ "func_code_index": [ 32941, 33153 ] }
58,393
GoodDollar
contracts/token/GoodDollar.sol
0x67c5870b4a41d4ebef24d2456547a03f1f3e094b
Solidity
GoodDollar
contract GoodDollar is ERC677BridgeToken, IdentityGuard, FormulaHolder { address feeRecipient; // Overrides hard-coded decimal in DAOToken uint256 public constant decimals = 2; /** * @dev constructor * @param _name The name of the token * @param _symbol The symbol of the token * @param _cap the cap of the token. no cap if 0 * @param _formula the fee formula contract * @param _identity the identity contract * @param _feeRecipient the address that receives transaction fees */ constructor( string memory _name, string memory _symbol, uint256 _cap, AbstractFees _formula, Identity _identity, address _feeRecipient ) public ERC677BridgeToken(_name, _symbol, _cap) IdentityGuard(_identity) FormulaHolder(_formula) { feeRecipient = _feeRecipient; } /** * @dev Processes fees from given value and sends * remainder to given address * @param to the address to be sent to * @param value the value to be processed and then * transferred * @return a boolean that indicates if the operation was successful */ function transfer(address to, uint256 value) public returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super.transfer(to, bruttoValue); } /** * @dev Approve the passed address to spend the specified * amount of tokens on behalf of msg.sender * @param spender The address which will spend the funds * @param value The amount of tokens to be spent * @return a boolean that indicates if the operation was successful */ function approve(address spender, uint256 value) public returns (bool) { return super.approve(spender, value); } /** * @dev Transfer tokens from one address to another * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value the amount of tokens to be transferred * @return a boolean that indicates if the operation was successful */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { uint256 bruttoValue = processFees(from, to, value); return super.transferFrom(from, to, bruttoValue); } /** * @dev Processes transfer fees and calls ERC677Token transferAndCall function * @param to address to transfer to * @param value the amount to transfer * @param data The data to pass to transferAndCall * @return a bool indicating if transfer function succeeded */ function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super._transferAndCall(to, bruttoValue, data); } /** * @dev Minting function * @param to the address that will receive the minted tokens * @param value the amount of tokens to mint * @return a boolean that indicated if the operation was successful */ function mint(address to, uint256 value) public onlyMinter requireNotBlacklisted(to) returns (bool) { if (cap > 0) { require(totalSupply().add(value) <= cap, "Cannot increase supply beyond cap"); } super._mint(to, value); return true; } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public onlyNotBlacklisted { super.burn(value); } /** * @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 onlyNotBlacklisted requireNotBlacklisted(from) { super.burnFrom(from, value); } /** * @dev Increase the amount of tokens that an owner allows a spender * @param spender The address which will spend the funds * @param addedValue The amount of tokens to increase the allowance by * @return a boolean that indicated if the operation was successful */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { return super.increaseAllowance(spender, addedValue); } /** * @dev Decrease the amount of tokens that an owner allowed to a spender * @param spender The address which will spend the funds * @param subtractedValue The amount of tokens to decrease the allowance by * @return a boolean that indicated if the operation was successful */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees(uint256 value) public view returns (uint256, bool) { return formula.getTxFees(value, address(0), address(0)); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees( uint256 value, address sender, address recipient ) public view returns (uint256, bool) { return formula.getTxFees(value, sender, recipient); } /** * @dev Sets the address that receives the transactional fees. * can only be called by owner * @param _feeRecipient The new address to receive transactional fees */ function setFeeRecipient(address _feeRecipient) public onlyOwner { feeRecipient = _feeRecipient; } /** * @dev Sends transactional fees to feeRecipient address from given address * @param account The account that sends the fees * @param value The amount to subtract fees from * @return an uint256 that represents the given value minus the transactional fees */ function processFees( address account, address recipient, uint256 value ) internal returns (uint256) { (uint256 txFees, bool senderPays) = getFees(value, account, recipient); if (txFees > 0 && !identity.isDAOContract(msg.sender)) { require( senderPays == false || value.add(txFees) <= balanceOf(account), "Not enough balance to pay TX fee" ); if (account == msg.sender) { super.transfer(feeRecipient, txFees); } else { super.transferFrom(account, feeRecipient, txFees); } return senderPays ? value : value.sub(txFees); } return value; } }
/** * @title The GoodDollar ERC677 token contract */
NatSpecMultiLine
transfer
function transfer(address to, uint256 value) public returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super.transfer(to, bruttoValue); }
/** * @dev Processes fees from given value and sends * remainder to given address * @param to the address to be sent to * @param value the value to be processed and then * transferred * @return a boolean that indicates if the operation was successful */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
MIT
bzzr://377577b98803c2210dfa17f6feaf68d6a856726073543a35d4a8526c1f78cc9f
{ "func_code_index": [ 1242, 1438 ] }
58,394
GoodDollar
contracts/token/GoodDollar.sol
0x67c5870b4a41d4ebef24d2456547a03f1f3e094b
Solidity
GoodDollar
contract GoodDollar is ERC677BridgeToken, IdentityGuard, FormulaHolder { address feeRecipient; // Overrides hard-coded decimal in DAOToken uint256 public constant decimals = 2; /** * @dev constructor * @param _name The name of the token * @param _symbol The symbol of the token * @param _cap the cap of the token. no cap if 0 * @param _formula the fee formula contract * @param _identity the identity contract * @param _feeRecipient the address that receives transaction fees */ constructor( string memory _name, string memory _symbol, uint256 _cap, AbstractFees _formula, Identity _identity, address _feeRecipient ) public ERC677BridgeToken(_name, _symbol, _cap) IdentityGuard(_identity) FormulaHolder(_formula) { feeRecipient = _feeRecipient; } /** * @dev Processes fees from given value and sends * remainder to given address * @param to the address to be sent to * @param value the value to be processed and then * transferred * @return a boolean that indicates if the operation was successful */ function transfer(address to, uint256 value) public returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super.transfer(to, bruttoValue); } /** * @dev Approve the passed address to spend the specified * amount of tokens on behalf of msg.sender * @param spender The address which will spend the funds * @param value The amount of tokens to be spent * @return a boolean that indicates if the operation was successful */ function approve(address spender, uint256 value) public returns (bool) { return super.approve(spender, value); } /** * @dev Transfer tokens from one address to another * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value the amount of tokens to be transferred * @return a boolean that indicates if the operation was successful */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { uint256 bruttoValue = processFees(from, to, value); return super.transferFrom(from, to, bruttoValue); } /** * @dev Processes transfer fees and calls ERC677Token transferAndCall function * @param to address to transfer to * @param value the amount to transfer * @param data The data to pass to transferAndCall * @return a bool indicating if transfer function succeeded */ function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super._transferAndCall(to, bruttoValue, data); } /** * @dev Minting function * @param to the address that will receive the minted tokens * @param value the amount of tokens to mint * @return a boolean that indicated if the operation was successful */ function mint(address to, uint256 value) public onlyMinter requireNotBlacklisted(to) returns (bool) { if (cap > 0) { require(totalSupply().add(value) <= cap, "Cannot increase supply beyond cap"); } super._mint(to, value); return true; } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public onlyNotBlacklisted { super.burn(value); } /** * @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 onlyNotBlacklisted requireNotBlacklisted(from) { super.burnFrom(from, value); } /** * @dev Increase the amount of tokens that an owner allows a spender * @param spender The address which will spend the funds * @param addedValue The amount of tokens to increase the allowance by * @return a boolean that indicated if the operation was successful */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { return super.increaseAllowance(spender, addedValue); } /** * @dev Decrease the amount of tokens that an owner allowed to a spender * @param spender The address which will spend the funds * @param subtractedValue The amount of tokens to decrease the allowance by * @return a boolean that indicated if the operation was successful */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees(uint256 value) public view returns (uint256, bool) { return formula.getTxFees(value, address(0), address(0)); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees( uint256 value, address sender, address recipient ) public view returns (uint256, bool) { return formula.getTxFees(value, sender, recipient); } /** * @dev Sets the address that receives the transactional fees. * can only be called by owner * @param _feeRecipient The new address to receive transactional fees */ function setFeeRecipient(address _feeRecipient) public onlyOwner { feeRecipient = _feeRecipient; } /** * @dev Sends transactional fees to feeRecipient address from given address * @param account The account that sends the fees * @param value The amount to subtract fees from * @return an uint256 that represents the given value minus the transactional fees */ function processFees( address account, address recipient, uint256 value ) internal returns (uint256) { (uint256 txFees, bool senderPays) = getFees(value, account, recipient); if (txFees > 0 && !identity.isDAOContract(msg.sender)) { require( senderPays == false || value.add(txFees) <= balanceOf(account), "Not enough balance to pay TX fee" ); if (account == msg.sender) { super.transfer(feeRecipient, txFees); } else { super.transferFrom(account, feeRecipient, txFees); } return senderPays ? value : value.sub(txFees); } return value; } }
/** * @title The GoodDollar ERC677 token contract */
NatSpecMultiLine
approve
function approve(address spender, uint256 value) public returns (bool) { return super.approve(spender, value); }
/** * @dev Approve the passed address to spend the specified * amount of tokens on behalf of msg.sender * @param spender The address which will spend the funds * @param value The amount of tokens to be spent * @return a boolean that indicates if the operation was successful */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
MIT
bzzr://377577b98803c2210dfa17f6feaf68d6a856726073543a35d4a8526c1f78cc9f
{ "func_code_index": [ 1760, 1891 ] }
58,395
GoodDollar
contracts/token/GoodDollar.sol
0x67c5870b4a41d4ebef24d2456547a03f1f3e094b
Solidity
GoodDollar
contract GoodDollar is ERC677BridgeToken, IdentityGuard, FormulaHolder { address feeRecipient; // Overrides hard-coded decimal in DAOToken uint256 public constant decimals = 2; /** * @dev constructor * @param _name The name of the token * @param _symbol The symbol of the token * @param _cap the cap of the token. no cap if 0 * @param _formula the fee formula contract * @param _identity the identity contract * @param _feeRecipient the address that receives transaction fees */ constructor( string memory _name, string memory _symbol, uint256 _cap, AbstractFees _formula, Identity _identity, address _feeRecipient ) public ERC677BridgeToken(_name, _symbol, _cap) IdentityGuard(_identity) FormulaHolder(_formula) { feeRecipient = _feeRecipient; } /** * @dev Processes fees from given value and sends * remainder to given address * @param to the address to be sent to * @param value the value to be processed and then * transferred * @return a boolean that indicates if the operation was successful */ function transfer(address to, uint256 value) public returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super.transfer(to, bruttoValue); } /** * @dev Approve the passed address to spend the specified * amount of tokens on behalf of msg.sender * @param spender The address which will spend the funds * @param value The amount of tokens to be spent * @return a boolean that indicates if the operation was successful */ function approve(address spender, uint256 value) public returns (bool) { return super.approve(spender, value); } /** * @dev Transfer tokens from one address to another * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value the amount of tokens to be transferred * @return a boolean that indicates if the operation was successful */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { uint256 bruttoValue = processFees(from, to, value); return super.transferFrom(from, to, bruttoValue); } /** * @dev Processes transfer fees and calls ERC677Token transferAndCall function * @param to address to transfer to * @param value the amount to transfer * @param data The data to pass to transferAndCall * @return a bool indicating if transfer function succeeded */ function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super._transferAndCall(to, bruttoValue, data); } /** * @dev Minting function * @param to the address that will receive the minted tokens * @param value the amount of tokens to mint * @return a boolean that indicated if the operation was successful */ function mint(address to, uint256 value) public onlyMinter requireNotBlacklisted(to) returns (bool) { if (cap > 0) { require(totalSupply().add(value) <= cap, "Cannot increase supply beyond cap"); } super._mint(to, value); return true; } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public onlyNotBlacklisted { super.burn(value); } /** * @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 onlyNotBlacklisted requireNotBlacklisted(from) { super.burnFrom(from, value); } /** * @dev Increase the amount of tokens that an owner allows a spender * @param spender The address which will spend the funds * @param addedValue The amount of tokens to increase the allowance by * @return a boolean that indicated if the operation was successful */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { return super.increaseAllowance(spender, addedValue); } /** * @dev Decrease the amount of tokens that an owner allowed to a spender * @param spender The address which will spend the funds * @param subtractedValue The amount of tokens to decrease the allowance by * @return a boolean that indicated if the operation was successful */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees(uint256 value) public view returns (uint256, bool) { return formula.getTxFees(value, address(0), address(0)); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees( uint256 value, address sender, address recipient ) public view returns (uint256, bool) { return formula.getTxFees(value, sender, recipient); } /** * @dev Sets the address that receives the transactional fees. * can only be called by owner * @param _feeRecipient The new address to receive transactional fees */ function setFeeRecipient(address _feeRecipient) public onlyOwner { feeRecipient = _feeRecipient; } /** * @dev Sends transactional fees to feeRecipient address from given address * @param account The account that sends the fees * @param value The amount to subtract fees from * @return an uint256 that represents the given value minus the transactional fees */ function processFees( address account, address recipient, uint256 value ) internal returns (uint256) { (uint256 txFees, bool senderPays) = getFees(value, account, recipient); if (txFees > 0 && !identity.isDAOContract(msg.sender)) { require( senderPays == false || value.add(txFees) <= balanceOf(account), "Not enough balance to pay TX fee" ); if (account == msg.sender) { super.transfer(feeRecipient, txFees); } else { super.transferFrom(account, feeRecipient, txFees); } return senderPays ? value : value.sub(txFees); } return value; } }
/** * @title The GoodDollar ERC677 token contract */
NatSpecMultiLine
transferFrom
function transferFrom( address from, address to, uint256 value ) public returns (bool) { uint256 bruttoValue = processFees(from, to, value); return super.transferFrom(from, to, bruttoValue); }
/** * @dev Transfer tokens from one address to another * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value the amount of tokens to be transferred * @return a boolean that indicates if the operation was successful */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
MIT
bzzr://377577b98803c2210dfa17f6feaf68d6a856726073543a35d4a8526c1f78cc9f
{ "func_code_index": [ 2229, 2481 ] }
58,396
GoodDollar
contracts/token/GoodDollar.sol
0x67c5870b4a41d4ebef24d2456547a03f1f3e094b
Solidity
GoodDollar
contract GoodDollar is ERC677BridgeToken, IdentityGuard, FormulaHolder { address feeRecipient; // Overrides hard-coded decimal in DAOToken uint256 public constant decimals = 2; /** * @dev constructor * @param _name The name of the token * @param _symbol The symbol of the token * @param _cap the cap of the token. no cap if 0 * @param _formula the fee formula contract * @param _identity the identity contract * @param _feeRecipient the address that receives transaction fees */ constructor( string memory _name, string memory _symbol, uint256 _cap, AbstractFees _formula, Identity _identity, address _feeRecipient ) public ERC677BridgeToken(_name, _symbol, _cap) IdentityGuard(_identity) FormulaHolder(_formula) { feeRecipient = _feeRecipient; } /** * @dev Processes fees from given value and sends * remainder to given address * @param to the address to be sent to * @param value the value to be processed and then * transferred * @return a boolean that indicates if the operation was successful */ function transfer(address to, uint256 value) public returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super.transfer(to, bruttoValue); } /** * @dev Approve the passed address to spend the specified * amount of tokens on behalf of msg.sender * @param spender The address which will spend the funds * @param value The amount of tokens to be spent * @return a boolean that indicates if the operation was successful */ function approve(address spender, uint256 value) public returns (bool) { return super.approve(spender, value); } /** * @dev Transfer tokens from one address to another * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value the amount of tokens to be transferred * @return a boolean that indicates if the operation was successful */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { uint256 bruttoValue = processFees(from, to, value); return super.transferFrom(from, to, bruttoValue); } /** * @dev Processes transfer fees and calls ERC677Token transferAndCall function * @param to address to transfer to * @param value the amount to transfer * @param data The data to pass to transferAndCall * @return a bool indicating if transfer function succeeded */ function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super._transferAndCall(to, bruttoValue, data); } /** * @dev Minting function * @param to the address that will receive the minted tokens * @param value the amount of tokens to mint * @return a boolean that indicated if the operation was successful */ function mint(address to, uint256 value) public onlyMinter requireNotBlacklisted(to) returns (bool) { if (cap > 0) { require(totalSupply().add(value) <= cap, "Cannot increase supply beyond cap"); } super._mint(to, value); return true; } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public onlyNotBlacklisted { super.burn(value); } /** * @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 onlyNotBlacklisted requireNotBlacklisted(from) { super.burnFrom(from, value); } /** * @dev Increase the amount of tokens that an owner allows a spender * @param spender The address which will spend the funds * @param addedValue The amount of tokens to increase the allowance by * @return a boolean that indicated if the operation was successful */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { return super.increaseAllowance(spender, addedValue); } /** * @dev Decrease the amount of tokens that an owner allowed to a spender * @param spender The address which will spend the funds * @param subtractedValue The amount of tokens to decrease the allowance by * @return a boolean that indicated if the operation was successful */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees(uint256 value) public view returns (uint256, bool) { return formula.getTxFees(value, address(0), address(0)); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees( uint256 value, address sender, address recipient ) public view returns (uint256, bool) { return formula.getTxFees(value, sender, recipient); } /** * @dev Sets the address that receives the transactional fees. * can only be called by owner * @param _feeRecipient The new address to receive transactional fees */ function setFeeRecipient(address _feeRecipient) public onlyOwner { feeRecipient = _feeRecipient; } /** * @dev Sends transactional fees to feeRecipient address from given address * @param account The account that sends the fees * @param value The amount to subtract fees from * @return an uint256 that represents the given value minus the transactional fees */ function processFees( address account, address recipient, uint256 value ) internal returns (uint256) { (uint256 txFees, bool senderPays) = getFees(value, account, recipient); if (txFees > 0 && !identity.isDAOContract(msg.sender)) { require( senderPays == false || value.add(txFees) <= balanceOf(account), "Not enough balance to pay TX fee" ); if (account == msg.sender) { super.transfer(feeRecipient, txFees); } else { super.transferFrom(account, feeRecipient, txFees); } return senderPays ? value : value.sub(txFees); } return value; } }
/** * @title The GoodDollar ERC677 token contract */
NatSpecMultiLine
transferAndCall
function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super._transferAndCall(to, bruttoValue, data); }
/** * @dev Processes transfer fees and calls ERC677Token transferAndCall function * @param to address to transfer to * @param value the amount to transfer * @param data The data to pass to transferAndCall * @return a bool indicating if transfer function succeeded */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
MIT
bzzr://377577b98803c2210dfa17f6feaf68d6a856726073543a35d4a8526c1f78cc9f
{ "func_code_index": [ 2792, 3066 ] }
58,397
GoodDollar
contracts/token/GoodDollar.sol
0x67c5870b4a41d4ebef24d2456547a03f1f3e094b
Solidity
GoodDollar
contract GoodDollar is ERC677BridgeToken, IdentityGuard, FormulaHolder { address feeRecipient; // Overrides hard-coded decimal in DAOToken uint256 public constant decimals = 2; /** * @dev constructor * @param _name The name of the token * @param _symbol The symbol of the token * @param _cap the cap of the token. no cap if 0 * @param _formula the fee formula contract * @param _identity the identity contract * @param _feeRecipient the address that receives transaction fees */ constructor( string memory _name, string memory _symbol, uint256 _cap, AbstractFees _formula, Identity _identity, address _feeRecipient ) public ERC677BridgeToken(_name, _symbol, _cap) IdentityGuard(_identity) FormulaHolder(_formula) { feeRecipient = _feeRecipient; } /** * @dev Processes fees from given value and sends * remainder to given address * @param to the address to be sent to * @param value the value to be processed and then * transferred * @return a boolean that indicates if the operation was successful */ function transfer(address to, uint256 value) public returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super.transfer(to, bruttoValue); } /** * @dev Approve the passed address to spend the specified * amount of tokens on behalf of msg.sender * @param spender The address which will spend the funds * @param value The amount of tokens to be spent * @return a boolean that indicates if the operation was successful */ function approve(address spender, uint256 value) public returns (bool) { return super.approve(spender, value); } /** * @dev Transfer tokens from one address to another * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value the amount of tokens to be transferred * @return a boolean that indicates if the operation was successful */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { uint256 bruttoValue = processFees(from, to, value); return super.transferFrom(from, to, bruttoValue); } /** * @dev Processes transfer fees and calls ERC677Token transferAndCall function * @param to address to transfer to * @param value the amount to transfer * @param data The data to pass to transferAndCall * @return a bool indicating if transfer function succeeded */ function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super._transferAndCall(to, bruttoValue, data); } /** * @dev Minting function * @param to the address that will receive the minted tokens * @param value the amount of tokens to mint * @return a boolean that indicated if the operation was successful */ function mint(address to, uint256 value) public onlyMinter requireNotBlacklisted(to) returns (bool) { if (cap > 0) { require(totalSupply().add(value) <= cap, "Cannot increase supply beyond cap"); } super._mint(to, value); return true; } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public onlyNotBlacklisted { super.burn(value); } /** * @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 onlyNotBlacklisted requireNotBlacklisted(from) { super.burnFrom(from, value); } /** * @dev Increase the amount of tokens that an owner allows a spender * @param spender The address which will spend the funds * @param addedValue The amount of tokens to increase the allowance by * @return a boolean that indicated if the operation was successful */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { return super.increaseAllowance(spender, addedValue); } /** * @dev Decrease the amount of tokens that an owner allowed to a spender * @param spender The address which will spend the funds * @param subtractedValue The amount of tokens to decrease the allowance by * @return a boolean that indicated if the operation was successful */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees(uint256 value) public view returns (uint256, bool) { return formula.getTxFees(value, address(0), address(0)); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees( uint256 value, address sender, address recipient ) public view returns (uint256, bool) { return formula.getTxFees(value, sender, recipient); } /** * @dev Sets the address that receives the transactional fees. * can only be called by owner * @param _feeRecipient The new address to receive transactional fees */ function setFeeRecipient(address _feeRecipient) public onlyOwner { feeRecipient = _feeRecipient; } /** * @dev Sends transactional fees to feeRecipient address from given address * @param account The account that sends the fees * @param value The amount to subtract fees from * @return an uint256 that represents the given value minus the transactional fees */ function processFees( address account, address recipient, uint256 value ) internal returns (uint256) { (uint256 txFees, bool senderPays) = getFees(value, account, recipient); if (txFees > 0 && !identity.isDAOContract(msg.sender)) { require( senderPays == false || value.add(txFees) <= balanceOf(account), "Not enough balance to pay TX fee" ); if (account == msg.sender) { super.transfer(feeRecipient, txFees); } else { super.transferFrom(account, feeRecipient, txFees); } return senderPays ? value : value.sub(txFees); } return value; } }
/** * @title The GoodDollar ERC677 token contract */
NatSpecMultiLine
mint
function mint(address to, uint256 value) public onlyMinter requireNotBlacklisted(to) returns (bool) { if (cap > 0) { require(totalSupply().add(value) <= cap, "Cannot increase supply beyond cap"); } super._mint(to, value); return true; }
/** * @dev Minting function * @param to the address that will receive the minted tokens * @param value the amount of tokens to mint * @return a boolean that indicated if the operation was successful */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
MIT
bzzr://377577b98803c2210dfa17f6feaf68d6a856726073543a35d4a8526c1f78cc9f
{ "func_code_index": [ 3306, 3642 ] }
58,398
GoodDollar
contracts/token/GoodDollar.sol
0x67c5870b4a41d4ebef24d2456547a03f1f3e094b
Solidity
GoodDollar
contract GoodDollar is ERC677BridgeToken, IdentityGuard, FormulaHolder { address feeRecipient; // Overrides hard-coded decimal in DAOToken uint256 public constant decimals = 2; /** * @dev constructor * @param _name The name of the token * @param _symbol The symbol of the token * @param _cap the cap of the token. no cap if 0 * @param _formula the fee formula contract * @param _identity the identity contract * @param _feeRecipient the address that receives transaction fees */ constructor( string memory _name, string memory _symbol, uint256 _cap, AbstractFees _formula, Identity _identity, address _feeRecipient ) public ERC677BridgeToken(_name, _symbol, _cap) IdentityGuard(_identity) FormulaHolder(_formula) { feeRecipient = _feeRecipient; } /** * @dev Processes fees from given value and sends * remainder to given address * @param to the address to be sent to * @param value the value to be processed and then * transferred * @return a boolean that indicates if the operation was successful */ function transfer(address to, uint256 value) public returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super.transfer(to, bruttoValue); } /** * @dev Approve the passed address to spend the specified * amount of tokens on behalf of msg.sender * @param spender The address which will spend the funds * @param value The amount of tokens to be spent * @return a boolean that indicates if the operation was successful */ function approve(address spender, uint256 value) public returns (bool) { return super.approve(spender, value); } /** * @dev Transfer tokens from one address to another * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value the amount of tokens to be transferred * @return a boolean that indicates if the operation was successful */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { uint256 bruttoValue = processFees(from, to, value); return super.transferFrom(from, to, bruttoValue); } /** * @dev Processes transfer fees and calls ERC677Token transferAndCall function * @param to address to transfer to * @param value the amount to transfer * @param data The data to pass to transferAndCall * @return a bool indicating if transfer function succeeded */ function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super._transferAndCall(to, bruttoValue, data); } /** * @dev Minting function * @param to the address that will receive the minted tokens * @param value the amount of tokens to mint * @return a boolean that indicated if the operation was successful */ function mint(address to, uint256 value) public onlyMinter requireNotBlacklisted(to) returns (bool) { if (cap > 0) { require(totalSupply().add(value) <= cap, "Cannot increase supply beyond cap"); } super._mint(to, value); return true; } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public onlyNotBlacklisted { super.burn(value); } /** * @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 onlyNotBlacklisted requireNotBlacklisted(from) { super.burnFrom(from, value); } /** * @dev Increase the amount of tokens that an owner allows a spender * @param spender The address which will spend the funds * @param addedValue The amount of tokens to increase the allowance by * @return a boolean that indicated if the operation was successful */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { return super.increaseAllowance(spender, addedValue); } /** * @dev Decrease the amount of tokens that an owner allowed to a spender * @param spender The address which will spend the funds * @param subtractedValue The amount of tokens to decrease the allowance by * @return a boolean that indicated if the operation was successful */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees(uint256 value) public view returns (uint256, bool) { return formula.getTxFees(value, address(0), address(0)); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees( uint256 value, address sender, address recipient ) public view returns (uint256, bool) { return formula.getTxFees(value, sender, recipient); } /** * @dev Sets the address that receives the transactional fees. * can only be called by owner * @param _feeRecipient The new address to receive transactional fees */ function setFeeRecipient(address _feeRecipient) public onlyOwner { feeRecipient = _feeRecipient; } /** * @dev Sends transactional fees to feeRecipient address from given address * @param account The account that sends the fees * @param value The amount to subtract fees from * @return an uint256 that represents the given value minus the transactional fees */ function processFees( address account, address recipient, uint256 value ) internal returns (uint256) { (uint256 txFees, bool senderPays) = getFees(value, account, recipient); if (txFees > 0 && !identity.isDAOContract(msg.sender)) { require( senderPays == false || value.add(txFees) <= balanceOf(account), "Not enough balance to pay TX fee" ); if (account == msg.sender) { super.transfer(feeRecipient, txFees); } else { super.transferFrom(account, feeRecipient, txFees); } return senderPays ? value : value.sub(txFees); } return value; } }
/** * @title The GoodDollar ERC677 token contract */
NatSpecMultiLine
burn
function burn(uint256 value) public onlyNotBlacklisted { super.burn(value); }
/** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
MIT
bzzr://377577b98803c2210dfa17f6feaf68d6a856726073543a35d4a8526c1f78cc9f
{ "func_code_index": [ 3766, 3862 ] }
58,399
GoodDollar
contracts/token/GoodDollar.sol
0x67c5870b4a41d4ebef24d2456547a03f1f3e094b
Solidity
GoodDollar
contract GoodDollar is ERC677BridgeToken, IdentityGuard, FormulaHolder { address feeRecipient; // Overrides hard-coded decimal in DAOToken uint256 public constant decimals = 2; /** * @dev constructor * @param _name The name of the token * @param _symbol The symbol of the token * @param _cap the cap of the token. no cap if 0 * @param _formula the fee formula contract * @param _identity the identity contract * @param _feeRecipient the address that receives transaction fees */ constructor( string memory _name, string memory _symbol, uint256 _cap, AbstractFees _formula, Identity _identity, address _feeRecipient ) public ERC677BridgeToken(_name, _symbol, _cap) IdentityGuard(_identity) FormulaHolder(_formula) { feeRecipient = _feeRecipient; } /** * @dev Processes fees from given value and sends * remainder to given address * @param to the address to be sent to * @param value the value to be processed and then * transferred * @return a boolean that indicates if the operation was successful */ function transfer(address to, uint256 value) public returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super.transfer(to, bruttoValue); } /** * @dev Approve the passed address to spend the specified * amount of tokens on behalf of msg.sender * @param spender The address which will spend the funds * @param value The amount of tokens to be spent * @return a boolean that indicates if the operation was successful */ function approve(address spender, uint256 value) public returns (bool) { return super.approve(spender, value); } /** * @dev Transfer tokens from one address to another * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value the amount of tokens to be transferred * @return a boolean that indicates if the operation was successful */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { uint256 bruttoValue = processFees(from, to, value); return super.transferFrom(from, to, bruttoValue); } /** * @dev Processes transfer fees and calls ERC677Token transferAndCall function * @param to address to transfer to * @param value the amount to transfer * @param data The data to pass to transferAndCall * @return a bool indicating if transfer function succeeded */ function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super._transferAndCall(to, bruttoValue, data); } /** * @dev Minting function * @param to the address that will receive the minted tokens * @param value the amount of tokens to mint * @return a boolean that indicated if the operation was successful */ function mint(address to, uint256 value) public onlyMinter requireNotBlacklisted(to) returns (bool) { if (cap > 0) { require(totalSupply().add(value) <= cap, "Cannot increase supply beyond cap"); } super._mint(to, value); return true; } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public onlyNotBlacklisted { super.burn(value); } /** * @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 onlyNotBlacklisted requireNotBlacklisted(from) { super.burnFrom(from, value); } /** * @dev Increase the amount of tokens that an owner allows a spender * @param spender The address which will spend the funds * @param addedValue The amount of tokens to increase the allowance by * @return a boolean that indicated if the operation was successful */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { return super.increaseAllowance(spender, addedValue); } /** * @dev Decrease the amount of tokens that an owner allowed to a spender * @param spender The address which will spend the funds * @param subtractedValue The amount of tokens to decrease the allowance by * @return a boolean that indicated if the operation was successful */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees(uint256 value) public view returns (uint256, bool) { return formula.getTxFees(value, address(0), address(0)); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees( uint256 value, address sender, address recipient ) public view returns (uint256, bool) { return formula.getTxFees(value, sender, recipient); } /** * @dev Sets the address that receives the transactional fees. * can only be called by owner * @param _feeRecipient The new address to receive transactional fees */ function setFeeRecipient(address _feeRecipient) public onlyOwner { feeRecipient = _feeRecipient; } /** * @dev Sends transactional fees to feeRecipient address from given address * @param account The account that sends the fees * @param value The amount to subtract fees from * @return an uint256 that represents the given value minus the transactional fees */ function processFees( address account, address recipient, uint256 value ) internal returns (uint256) { (uint256 txFees, bool senderPays) = getFees(value, account, recipient); if (txFees > 0 && !identity.isDAOContract(msg.sender)) { require( senderPays == false || value.add(txFees) <= balanceOf(account), "Not enough balance to pay TX fee" ); if (account == msg.sender) { super.transfer(feeRecipient, txFees); } else { super.transferFrom(account, feeRecipient, txFees); } return senderPays ? value : value.sub(txFees); } return value; } }
/** * @title The GoodDollar ERC677 token contract */
NatSpecMultiLine
burnFrom
function burnFrom(address from, uint256 value) public onlyNotBlacklisted requireNotBlacklisted(from) { super.burnFrom(from, value); }
/** * @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 */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
MIT
bzzr://377577b98803c2210dfa17f6feaf68d6a856726073543a35d4a8526c1f78cc9f
{ "func_code_index": [ 4116, 4300 ] }
58,400
GoodDollar
contracts/token/GoodDollar.sol
0x67c5870b4a41d4ebef24d2456547a03f1f3e094b
Solidity
GoodDollar
contract GoodDollar is ERC677BridgeToken, IdentityGuard, FormulaHolder { address feeRecipient; // Overrides hard-coded decimal in DAOToken uint256 public constant decimals = 2; /** * @dev constructor * @param _name The name of the token * @param _symbol The symbol of the token * @param _cap the cap of the token. no cap if 0 * @param _formula the fee formula contract * @param _identity the identity contract * @param _feeRecipient the address that receives transaction fees */ constructor( string memory _name, string memory _symbol, uint256 _cap, AbstractFees _formula, Identity _identity, address _feeRecipient ) public ERC677BridgeToken(_name, _symbol, _cap) IdentityGuard(_identity) FormulaHolder(_formula) { feeRecipient = _feeRecipient; } /** * @dev Processes fees from given value and sends * remainder to given address * @param to the address to be sent to * @param value the value to be processed and then * transferred * @return a boolean that indicates if the operation was successful */ function transfer(address to, uint256 value) public returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super.transfer(to, bruttoValue); } /** * @dev Approve the passed address to spend the specified * amount of tokens on behalf of msg.sender * @param spender The address which will spend the funds * @param value The amount of tokens to be spent * @return a boolean that indicates if the operation was successful */ function approve(address spender, uint256 value) public returns (bool) { return super.approve(spender, value); } /** * @dev Transfer tokens from one address to another * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value the amount of tokens to be transferred * @return a boolean that indicates if the operation was successful */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { uint256 bruttoValue = processFees(from, to, value); return super.transferFrom(from, to, bruttoValue); } /** * @dev Processes transfer fees and calls ERC677Token transferAndCall function * @param to address to transfer to * @param value the amount to transfer * @param data The data to pass to transferAndCall * @return a bool indicating if transfer function succeeded */ function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super._transferAndCall(to, bruttoValue, data); } /** * @dev Minting function * @param to the address that will receive the minted tokens * @param value the amount of tokens to mint * @return a boolean that indicated if the operation was successful */ function mint(address to, uint256 value) public onlyMinter requireNotBlacklisted(to) returns (bool) { if (cap > 0) { require(totalSupply().add(value) <= cap, "Cannot increase supply beyond cap"); } super._mint(to, value); return true; } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public onlyNotBlacklisted { super.burn(value); } /** * @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 onlyNotBlacklisted requireNotBlacklisted(from) { super.burnFrom(from, value); } /** * @dev Increase the amount of tokens that an owner allows a spender * @param spender The address which will spend the funds * @param addedValue The amount of tokens to increase the allowance by * @return a boolean that indicated if the operation was successful */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { return super.increaseAllowance(spender, addedValue); } /** * @dev Decrease the amount of tokens that an owner allowed to a spender * @param spender The address which will spend the funds * @param subtractedValue The amount of tokens to decrease the allowance by * @return a boolean that indicated if the operation was successful */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees(uint256 value) public view returns (uint256, bool) { return formula.getTxFees(value, address(0), address(0)); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees( uint256 value, address sender, address recipient ) public view returns (uint256, bool) { return formula.getTxFees(value, sender, recipient); } /** * @dev Sets the address that receives the transactional fees. * can only be called by owner * @param _feeRecipient The new address to receive transactional fees */ function setFeeRecipient(address _feeRecipient) public onlyOwner { feeRecipient = _feeRecipient; } /** * @dev Sends transactional fees to feeRecipient address from given address * @param account The account that sends the fees * @param value The amount to subtract fees from * @return an uint256 that represents the given value minus the transactional fees */ function processFees( address account, address recipient, uint256 value ) internal returns (uint256) { (uint256 txFees, bool senderPays) = getFees(value, account, recipient); if (txFees > 0 && !identity.isDAOContract(msg.sender)) { require( senderPays == false || value.add(txFees) <= balanceOf(account), "Not enough balance to pay TX fee" ); if (account == msg.sender) { super.transfer(feeRecipient, txFees); } else { super.transferFrom(account, feeRecipient, txFees); } return senderPays ? value : value.sub(txFees); } return value; } }
/** * @title The GoodDollar ERC677 token contract */
NatSpecMultiLine
increaseAllowance
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { return super.increaseAllowance(spender, addedValue); }
/** * @dev Increase the amount of tokens that an owner allows a spender * @param spender The address which will spend the funds * @param addedValue The amount of tokens to increase the allowance by * @return a boolean that indicated if the operation was successful */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
MIT
bzzr://377577b98803c2210dfa17f6feaf68d6a856726073543a35d4a8526c1f78cc9f
{ "func_code_index": [ 4606, 4790 ] }
58,401
GoodDollar
contracts/token/GoodDollar.sol
0x67c5870b4a41d4ebef24d2456547a03f1f3e094b
Solidity
GoodDollar
contract GoodDollar is ERC677BridgeToken, IdentityGuard, FormulaHolder { address feeRecipient; // Overrides hard-coded decimal in DAOToken uint256 public constant decimals = 2; /** * @dev constructor * @param _name The name of the token * @param _symbol The symbol of the token * @param _cap the cap of the token. no cap if 0 * @param _formula the fee formula contract * @param _identity the identity contract * @param _feeRecipient the address that receives transaction fees */ constructor( string memory _name, string memory _symbol, uint256 _cap, AbstractFees _formula, Identity _identity, address _feeRecipient ) public ERC677BridgeToken(_name, _symbol, _cap) IdentityGuard(_identity) FormulaHolder(_formula) { feeRecipient = _feeRecipient; } /** * @dev Processes fees from given value and sends * remainder to given address * @param to the address to be sent to * @param value the value to be processed and then * transferred * @return a boolean that indicates if the operation was successful */ function transfer(address to, uint256 value) public returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super.transfer(to, bruttoValue); } /** * @dev Approve the passed address to spend the specified * amount of tokens on behalf of msg.sender * @param spender The address which will spend the funds * @param value The amount of tokens to be spent * @return a boolean that indicates if the operation was successful */ function approve(address spender, uint256 value) public returns (bool) { return super.approve(spender, value); } /** * @dev Transfer tokens from one address to another * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value the amount of tokens to be transferred * @return a boolean that indicates if the operation was successful */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { uint256 bruttoValue = processFees(from, to, value); return super.transferFrom(from, to, bruttoValue); } /** * @dev Processes transfer fees and calls ERC677Token transferAndCall function * @param to address to transfer to * @param value the amount to transfer * @param data The data to pass to transferAndCall * @return a bool indicating if transfer function succeeded */ function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super._transferAndCall(to, bruttoValue, data); } /** * @dev Minting function * @param to the address that will receive the minted tokens * @param value the amount of tokens to mint * @return a boolean that indicated if the operation was successful */ function mint(address to, uint256 value) public onlyMinter requireNotBlacklisted(to) returns (bool) { if (cap > 0) { require(totalSupply().add(value) <= cap, "Cannot increase supply beyond cap"); } super._mint(to, value); return true; } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public onlyNotBlacklisted { super.burn(value); } /** * @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 onlyNotBlacklisted requireNotBlacklisted(from) { super.burnFrom(from, value); } /** * @dev Increase the amount of tokens that an owner allows a spender * @param spender The address which will spend the funds * @param addedValue The amount of tokens to increase the allowance by * @return a boolean that indicated if the operation was successful */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { return super.increaseAllowance(spender, addedValue); } /** * @dev Decrease the amount of tokens that an owner allowed to a spender * @param spender The address which will spend the funds * @param subtractedValue The amount of tokens to decrease the allowance by * @return a boolean that indicated if the operation was successful */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees(uint256 value) public view returns (uint256, bool) { return formula.getTxFees(value, address(0), address(0)); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees( uint256 value, address sender, address recipient ) public view returns (uint256, bool) { return formula.getTxFees(value, sender, recipient); } /** * @dev Sets the address that receives the transactional fees. * can only be called by owner * @param _feeRecipient The new address to receive transactional fees */ function setFeeRecipient(address _feeRecipient) public onlyOwner { feeRecipient = _feeRecipient; } /** * @dev Sends transactional fees to feeRecipient address from given address * @param account The account that sends the fees * @param value The amount to subtract fees from * @return an uint256 that represents the given value minus the transactional fees */ function processFees( address account, address recipient, uint256 value ) internal returns (uint256) { (uint256 txFees, bool senderPays) = getFees(value, account, recipient); if (txFees > 0 && !identity.isDAOContract(msg.sender)) { require( senderPays == false || value.add(txFees) <= balanceOf(account), "Not enough balance to pay TX fee" ); if (account == msg.sender) { super.transfer(feeRecipient, txFees); } else { super.transferFrom(account, feeRecipient, txFees); } return senderPays ? value : value.sub(txFees); } return value; } }
/** * @title The GoodDollar ERC677 token contract */
NatSpecMultiLine
decreaseAllowance
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { return super.decreaseAllowance(spender, subtractedValue); }
/** * @dev Decrease the amount of tokens that an owner allowed to a spender * @param spender The address which will spend the funds * @param subtractedValue The amount of tokens to decrease the allowance by * @return a boolean that indicated if the operation was successful */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
MIT
bzzr://377577b98803c2210dfa17f6feaf68d6a856726073543a35d4a8526c1f78cc9f
{ "func_code_index": [ 5105, 5299 ] }
58,402
GoodDollar
contracts/token/GoodDollar.sol
0x67c5870b4a41d4ebef24d2456547a03f1f3e094b
Solidity
GoodDollar
contract GoodDollar is ERC677BridgeToken, IdentityGuard, FormulaHolder { address feeRecipient; // Overrides hard-coded decimal in DAOToken uint256 public constant decimals = 2; /** * @dev constructor * @param _name The name of the token * @param _symbol The symbol of the token * @param _cap the cap of the token. no cap if 0 * @param _formula the fee formula contract * @param _identity the identity contract * @param _feeRecipient the address that receives transaction fees */ constructor( string memory _name, string memory _symbol, uint256 _cap, AbstractFees _formula, Identity _identity, address _feeRecipient ) public ERC677BridgeToken(_name, _symbol, _cap) IdentityGuard(_identity) FormulaHolder(_formula) { feeRecipient = _feeRecipient; } /** * @dev Processes fees from given value and sends * remainder to given address * @param to the address to be sent to * @param value the value to be processed and then * transferred * @return a boolean that indicates if the operation was successful */ function transfer(address to, uint256 value) public returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super.transfer(to, bruttoValue); } /** * @dev Approve the passed address to spend the specified * amount of tokens on behalf of msg.sender * @param spender The address which will spend the funds * @param value The amount of tokens to be spent * @return a boolean that indicates if the operation was successful */ function approve(address spender, uint256 value) public returns (bool) { return super.approve(spender, value); } /** * @dev Transfer tokens from one address to another * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value the amount of tokens to be transferred * @return a boolean that indicates if the operation was successful */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { uint256 bruttoValue = processFees(from, to, value); return super.transferFrom(from, to, bruttoValue); } /** * @dev Processes transfer fees and calls ERC677Token transferAndCall function * @param to address to transfer to * @param value the amount to transfer * @param data The data to pass to transferAndCall * @return a bool indicating if transfer function succeeded */ function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super._transferAndCall(to, bruttoValue, data); } /** * @dev Minting function * @param to the address that will receive the minted tokens * @param value the amount of tokens to mint * @return a boolean that indicated if the operation was successful */ function mint(address to, uint256 value) public onlyMinter requireNotBlacklisted(to) returns (bool) { if (cap > 0) { require(totalSupply().add(value) <= cap, "Cannot increase supply beyond cap"); } super._mint(to, value); return true; } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public onlyNotBlacklisted { super.burn(value); } /** * @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 onlyNotBlacklisted requireNotBlacklisted(from) { super.burnFrom(from, value); } /** * @dev Increase the amount of tokens that an owner allows a spender * @param spender The address which will spend the funds * @param addedValue The amount of tokens to increase the allowance by * @return a boolean that indicated if the operation was successful */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { return super.increaseAllowance(spender, addedValue); } /** * @dev Decrease the amount of tokens that an owner allowed to a spender * @param spender The address which will spend the funds * @param subtractedValue The amount of tokens to decrease the allowance by * @return a boolean that indicated if the operation was successful */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees(uint256 value) public view returns (uint256, bool) { return formula.getTxFees(value, address(0), address(0)); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees( uint256 value, address sender, address recipient ) public view returns (uint256, bool) { return formula.getTxFees(value, sender, recipient); } /** * @dev Sets the address that receives the transactional fees. * can only be called by owner * @param _feeRecipient The new address to receive transactional fees */ function setFeeRecipient(address _feeRecipient) public onlyOwner { feeRecipient = _feeRecipient; } /** * @dev Sends transactional fees to feeRecipient address from given address * @param account The account that sends the fees * @param value The amount to subtract fees from * @return an uint256 that represents the given value minus the transactional fees */ function processFees( address account, address recipient, uint256 value ) internal returns (uint256) { (uint256 txFees, bool senderPays) = getFees(value, account, recipient); if (txFees > 0 && !identity.isDAOContract(msg.sender)) { require( senderPays == false || value.add(txFees) <= balanceOf(account), "Not enough balance to pay TX fee" ); if (account == msg.sender) { super.transfer(feeRecipient, txFees); } else { super.transferFrom(account, feeRecipient, txFees); } return senderPays ? value : value.sub(txFees); } return value; } }
/** * @title The GoodDollar ERC677 token contract */
NatSpecMultiLine
getFees
function getFees(uint256 value) public view returns (uint256, bool) { return formula.getTxFees(value, address(0), address(0)); }
/** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
MIT
bzzr://377577b98803c2210dfa17f6feaf68d6a856726073543a35d4a8526c1f78cc9f
{ "func_code_index": [ 5447, 5594 ] }
58,403
GoodDollar
contracts/token/GoodDollar.sol
0x67c5870b4a41d4ebef24d2456547a03f1f3e094b
Solidity
GoodDollar
contract GoodDollar is ERC677BridgeToken, IdentityGuard, FormulaHolder { address feeRecipient; // Overrides hard-coded decimal in DAOToken uint256 public constant decimals = 2; /** * @dev constructor * @param _name The name of the token * @param _symbol The symbol of the token * @param _cap the cap of the token. no cap if 0 * @param _formula the fee formula contract * @param _identity the identity contract * @param _feeRecipient the address that receives transaction fees */ constructor( string memory _name, string memory _symbol, uint256 _cap, AbstractFees _formula, Identity _identity, address _feeRecipient ) public ERC677BridgeToken(_name, _symbol, _cap) IdentityGuard(_identity) FormulaHolder(_formula) { feeRecipient = _feeRecipient; } /** * @dev Processes fees from given value and sends * remainder to given address * @param to the address to be sent to * @param value the value to be processed and then * transferred * @return a boolean that indicates if the operation was successful */ function transfer(address to, uint256 value) public returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super.transfer(to, bruttoValue); } /** * @dev Approve the passed address to spend the specified * amount of tokens on behalf of msg.sender * @param spender The address which will spend the funds * @param value The amount of tokens to be spent * @return a boolean that indicates if the operation was successful */ function approve(address spender, uint256 value) public returns (bool) { return super.approve(spender, value); } /** * @dev Transfer tokens from one address to another * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value the amount of tokens to be transferred * @return a boolean that indicates if the operation was successful */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { uint256 bruttoValue = processFees(from, to, value); return super.transferFrom(from, to, bruttoValue); } /** * @dev Processes transfer fees and calls ERC677Token transferAndCall function * @param to address to transfer to * @param value the amount to transfer * @param data The data to pass to transferAndCall * @return a bool indicating if transfer function succeeded */ function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super._transferAndCall(to, bruttoValue, data); } /** * @dev Minting function * @param to the address that will receive the minted tokens * @param value the amount of tokens to mint * @return a boolean that indicated if the operation was successful */ function mint(address to, uint256 value) public onlyMinter requireNotBlacklisted(to) returns (bool) { if (cap > 0) { require(totalSupply().add(value) <= cap, "Cannot increase supply beyond cap"); } super._mint(to, value); return true; } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public onlyNotBlacklisted { super.burn(value); } /** * @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 onlyNotBlacklisted requireNotBlacklisted(from) { super.burnFrom(from, value); } /** * @dev Increase the amount of tokens that an owner allows a spender * @param spender The address which will spend the funds * @param addedValue The amount of tokens to increase the allowance by * @return a boolean that indicated if the operation was successful */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { return super.increaseAllowance(spender, addedValue); } /** * @dev Decrease the amount of tokens that an owner allowed to a spender * @param spender The address which will spend the funds * @param subtractedValue The amount of tokens to decrease the allowance by * @return a boolean that indicated if the operation was successful */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees(uint256 value) public view returns (uint256, bool) { return formula.getTxFees(value, address(0), address(0)); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees( uint256 value, address sender, address recipient ) public view returns (uint256, bool) { return formula.getTxFees(value, sender, recipient); } /** * @dev Sets the address that receives the transactional fees. * can only be called by owner * @param _feeRecipient The new address to receive transactional fees */ function setFeeRecipient(address _feeRecipient) public onlyOwner { feeRecipient = _feeRecipient; } /** * @dev Sends transactional fees to feeRecipient address from given address * @param account The account that sends the fees * @param value The amount to subtract fees from * @return an uint256 that represents the given value minus the transactional fees */ function processFees( address account, address recipient, uint256 value ) internal returns (uint256) { (uint256 txFees, bool senderPays) = getFees(value, account, recipient); if (txFees > 0 && !identity.isDAOContract(msg.sender)) { require( senderPays == false || value.add(txFees) <= balanceOf(account), "Not enough balance to pay TX fee" ); if (account == msg.sender) { super.transfer(feeRecipient, txFees); } else { super.transferFrom(account, feeRecipient, txFees); } return senderPays ? value : value.sub(txFees); } return value; } }
/** * @title The GoodDollar ERC677 token contract */
NatSpecMultiLine
getFees
function getFees( uint256 value, address sender, address recipient ) public view returns (uint256, bool) { return formula.getTxFees(value, sender, recipient); }
/** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
MIT
bzzr://377577b98803c2210dfa17f6feaf68d6a856726073543a35d4a8526c1f78cc9f
{ "func_code_index": [ 5742, 5953 ] }
58,404
GoodDollar
contracts/token/GoodDollar.sol
0x67c5870b4a41d4ebef24d2456547a03f1f3e094b
Solidity
GoodDollar
contract GoodDollar is ERC677BridgeToken, IdentityGuard, FormulaHolder { address feeRecipient; // Overrides hard-coded decimal in DAOToken uint256 public constant decimals = 2; /** * @dev constructor * @param _name The name of the token * @param _symbol The symbol of the token * @param _cap the cap of the token. no cap if 0 * @param _formula the fee formula contract * @param _identity the identity contract * @param _feeRecipient the address that receives transaction fees */ constructor( string memory _name, string memory _symbol, uint256 _cap, AbstractFees _formula, Identity _identity, address _feeRecipient ) public ERC677BridgeToken(_name, _symbol, _cap) IdentityGuard(_identity) FormulaHolder(_formula) { feeRecipient = _feeRecipient; } /** * @dev Processes fees from given value and sends * remainder to given address * @param to the address to be sent to * @param value the value to be processed and then * transferred * @return a boolean that indicates if the operation was successful */ function transfer(address to, uint256 value) public returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super.transfer(to, bruttoValue); } /** * @dev Approve the passed address to spend the specified * amount of tokens on behalf of msg.sender * @param spender The address which will spend the funds * @param value The amount of tokens to be spent * @return a boolean that indicates if the operation was successful */ function approve(address spender, uint256 value) public returns (bool) { return super.approve(spender, value); } /** * @dev Transfer tokens from one address to another * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value the amount of tokens to be transferred * @return a boolean that indicates if the operation was successful */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { uint256 bruttoValue = processFees(from, to, value); return super.transferFrom(from, to, bruttoValue); } /** * @dev Processes transfer fees and calls ERC677Token transferAndCall function * @param to address to transfer to * @param value the amount to transfer * @param data The data to pass to transferAndCall * @return a bool indicating if transfer function succeeded */ function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super._transferAndCall(to, bruttoValue, data); } /** * @dev Minting function * @param to the address that will receive the minted tokens * @param value the amount of tokens to mint * @return a boolean that indicated if the operation was successful */ function mint(address to, uint256 value) public onlyMinter requireNotBlacklisted(to) returns (bool) { if (cap > 0) { require(totalSupply().add(value) <= cap, "Cannot increase supply beyond cap"); } super._mint(to, value); return true; } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public onlyNotBlacklisted { super.burn(value); } /** * @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 onlyNotBlacklisted requireNotBlacklisted(from) { super.burnFrom(from, value); } /** * @dev Increase the amount of tokens that an owner allows a spender * @param spender The address which will spend the funds * @param addedValue The amount of tokens to increase the allowance by * @return a boolean that indicated if the operation was successful */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { return super.increaseAllowance(spender, addedValue); } /** * @dev Decrease the amount of tokens that an owner allowed to a spender * @param spender The address which will spend the funds * @param subtractedValue The amount of tokens to decrease the allowance by * @return a boolean that indicated if the operation was successful */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees(uint256 value) public view returns (uint256, bool) { return formula.getTxFees(value, address(0), address(0)); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees( uint256 value, address sender, address recipient ) public view returns (uint256, bool) { return formula.getTxFees(value, sender, recipient); } /** * @dev Sets the address that receives the transactional fees. * can only be called by owner * @param _feeRecipient The new address to receive transactional fees */ function setFeeRecipient(address _feeRecipient) public onlyOwner { feeRecipient = _feeRecipient; } /** * @dev Sends transactional fees to feeRecipient address from given address * @param account The account that sends the fees * @param value The amount to subtract fees from * @return an uint256 that represents the given value minus the transactional fees */ function processFees( address account, address recipient, uint256 value ) internal returns (uint256) { (uint256 txFees, bool senderPays) = getFees(value, account, recipient); if (txFees > 0 && !identity.isDAOContract(msg.sender)) { require( senderPays == false || value.add(txFees) <= balanceOf(account), "Not enough balance to pay TX fee" ); if (account == msg.sender) { super.transfer(feeRecipient, txFees); } else { super.transferFrom(account, feeRecipient, txFees); } return senderPays ? value : value.sub(txFees); } return value; } }
/** * @title The GoodDollar ERC677 token contract */
NatSpecMultiLine
setFeeRecipient
function setFeeRecipient(address _feeRecipient) public onlyOwner { feeRecipient = _feeRecipient; }
/** * @dev Sets the address that receives the transactional fees. * can only be called by owner * @param _feeRecipient The new address to receive transactional fees */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
MIT
bzzr://377577b98803c2210dfa17f6feaf68d6a856726073543a35d4a8526c1f78cc9f
{ "func_code_index": [ 6153, 6270 ] }
58,405
GoodDollar
contracts/token/GoodDollar.sol
0x67c5870b4a41d4ebef24d2456547a03f1f3e094b
Solidity
GoodDollar
contract GoodDollar is ERC677BridgeToken, IdentityGuard, FormulaHolder { address feeRecipient; // Overrides hard-coded decimal in DAOToken uint256 public constant decimals = 2; /** * @dev constructor * @param _name The name of the token * @param _symbol The symbol of the token * @param _cap the cap of the token. no cap if 0 * @param _formula the fee formula contract * @param _identity the identity contract * @param _feeRecipient the address that receives transaction fees */ constructor( string memory _name, string memory _symbol, uint256 _cap, AbstractFees _formula, Identity _identity, address _feeRecipient ) public ERC677BridgeToken(_name, _symbol, _cap) IdentityGuard(_identity) FormulaHolder(_formula) { feeRecipient = _feeRecipient; } /** * @dev Processes fees from given value and sends * remainder to given address * @param to the address to be sent to * @param value the value to be processed and then * transferred * @return a boolean that indicates if the operation was successful */ function transfer(address to, uint256 value) public returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super.transfer(to, bruttoValue); } /** * @dev Approve the passed address to spend the specified * amount of tokens on behalf of msg.sender * @param spender The address which will spend the funds * @param value The amount of tokens to be spent * @return a boolean that indicates if the operation was successful */ function approve(address spender, uint256 value) public returns (bool) { return super.approve(spender, value); } /** * @dev Transfer tokens from one address to another * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value the amount of tokens to be transferred * @return a boolean that indicates if the operation was successful */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { uint256 bruttoValue = processFees(from, to, value); return super.transferFrom(from, to, bruttoValue); } /** * @dev Processes transfer fees and calls ERC677Token transferAndCall function * @param to address to transfer to * @param value the amount to transfer * @param data The data to pass to transferAndCall * @return a bool indicating if transfer function succeeded */ function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool) { uint256 bruttoValue = processFees(msg.sender, to, value); return super._transferAndCall(to, bruttoValue, data); } /** * @dev Minting function * @param to the address that will receive the minted tokens * @param value the amount of tokens to mint * @return a boolean that indicated if the operation was successful */ function mint(address to, uint256 value) public onlyMinter requireNotBlacklisted(to) returns (bool) { if (cap > 0) { require(totalSupply().add(value) <= cap, "Cannot increase supply beyond cap"); } super._mint(to, value); return true; } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public onlyNotBlacklisted { super.burn(value); } /** * @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 onlyNotBlacklisted requireNotBlacklisted(from) { super.burnFrom(from, value); } /** * @dev Increase the amount of tokens that an owner allows a spender * @param spender The address which will spend the funds * @param addedValue The amount of tokens to increase the allowance by * @return a boolean that indicated if the operation was successful */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { return super.increaseAllowance(spender, addedValue); } /** * @dev Decrease the amount of tokens that an owner allowed to a spender * @param spender The address which will spend the funds * @param subtractedValue The amount of tokens to decrease the allowance by * @return a boolean that indicated if the operation was successful */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees(uint256 value) public view returns (uint256, bool) { return formula.getTxFees(value, address(0), address(0)); } /** * @dev Gets the current transaction fees * @return an uint256 that represents * the current transaction fees */ function getFees( uint256 value, address sender, address recipient ) public view returns (uint256, bool) { return formula.getTxFees(value, sender, recipient); } /** * @dev Sets the address that receives the transactional fees. * can only be called by owner * @param _feeRecipient The new address to receive transactional fees */ function setFeeRecipient(address _feeRecipient) public onlyOwner { feeRecipient = _feeRecipient; } /** * @dev Sends transactional fees to feeRecipient address from given address * @param account The account that sends the fees * @param value The amount to subtract fees from * @return an uint256 that represents the given value minus the transactional fees */ function processFees( address account, address recipient, uint256 value ) internal returns (uint256) { (uint256 txFees, bool senderPays) = getFees(value, account, recipient); if (txFees > 0 && !identity.isDAOContract(msg.sender)) { require( senderPays == false || value.add(txFees) <= balanceOf(account), "Not enough balance to pay TX fee" ); if (account == msg.sender) { super.transfer(feeRecipient, txFees); } else { super.transferFrom(account, feeRecipient, txFees); } return senderPays ? value : value.sub(txFees); } return value; } }
/** * @title The GoodDollar ERC677 token contract */
NatSpecMultiLine
processFees
function processFees( address account, address recipient, uint256 value ) internal returns (uint256) { (uint256 txFees, bool senderPays) = getFees(value, account, recipient); if (txFees > 0 && !identity.isDAOContract(msg.sender)) { require( senderPays == false || value.add(txFees) <= balanceOf(account), "Not enough balance to pay TX fee" ); if (account == msg.sender) { super.transfer(feeRecipient, txFees); } else { super.transferFrom(account, feeRecipient, txFees); } return senderPays ? value : value.sub(txFees); } return value; }
/** * @dev Sends transactional fees to feeRecipient address from given address * @param account The account that sends the fees * @param value The amount to subtract fees from * @return an uint256 that represents the given value minus the transactional fees */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
MIT
bzzr://377577b98803c2210dfa17f6feaf68d6a856726073543a35d4a8526c1f78cc9f
{ "func_code_index": [ 6569, 7331 ] }
58,406
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
Ownable
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 Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
owner
function owner() public view returns (address) { return _owner; }
/** * @return the address of the owner. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 457, 541 ] }
58,407
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
Ownable
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 Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
isOwner
function isOwner() public view returns (bool) { return msg.sender == _owner; }
/** * @return true if `msg.sender` is the owner of the contract. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 792, 889 ] }
58,408
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
Ownable
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 Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
renounceOwnership
function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); }
/** * @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. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 1247, 1392 ] }
58,409
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
Ownable
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 Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 1564, 1678 ] }
58,410
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
Ownable
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 Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
_transferOwnership
function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; }
/** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 1823, 2015 ] }
58,411
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
SafeMath
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 SafeMath * @dev Unsigned math operations with safety checks that revert on error. */
NatSpecMultiLine
mul
function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; }
/** * @dev Multiplies two unsigned integers, reverts on overflow. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 106, 544 ] }
58,412
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
SafeMath
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 SafeMath * @dev Unsigned math operations with safety checks that revert on error. */
NatSpecMultiLine
div
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 Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 674, 982 ] }
58,413
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
SafeMath
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 SafeMath * @dev Unsigned math operations with safety checks that revert on error. */
NatSpecMultiLine
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; }
/** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 1115, 1270 ] }
58,414
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
SafeMath
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 SafeMath * @dev Unsigned math operations with safety checks that revert on error. */
NatSpecMultiLine
add
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; }
/** * @dev Adds two unsigned integers, reverts on overflow. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 1353, 1508 ] }
58,415
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
SafeMath
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 SafeMath * @dev Unsigned math operations with safety checks that revert on error. */
NatSpecMultiLine
mod
function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; }
/** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 1664, 1793 ] }
58,416
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
ERC20
contract ERC20 is IERC20, Ownable { 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); } /** * @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)); } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * 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. */
NatSpecMultiLine
totalSupply
function totalSupply() public view returns (uint256) { return _totalSupply; }
/** * @dev Total number of tokens in existence. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 307, 403 ] }
58,417
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
ERC20
contract ERC20 is IERC20, Ownable { 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); } /** * @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)); } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * 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. */
NatSpecMultiLine
balanceOf
function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; }
/** * @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. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 617, 728 ] }
58,418
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
ERC20
contract ERC20 is IERC20, Ownable { 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); } /** * @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)); } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * 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. */
NatSpecMultiLine
allowance
function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; }
/** * @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. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 1062, 1198 ] }
58,419
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
ERC20
contract ERC20 is IERC20, Ownable { 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); } /** * @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)); } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * 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. */
NatSpecMultiLine
transfer
function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; }
/** * @dev Transfer token to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 1368, 1513 ] }
58,420
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
ERC20
contract ERC20 is IERC20, Ownable { 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); } /** * @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)); } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * 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. */
NatSpecMultiLine
approve
function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, 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. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 2155, 2308 ] }
58,421
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
ERC20
contract ERC20 is IERC20, Ownable { 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); } /** * @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)); } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * 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. */
NatSpecMultiLine
transferFrom
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 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 */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 2776, 3009 ] }
58,422
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
ERC20
contract ERC20 is IERC20, Ownable { 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); } /** * @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)); } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * 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. */
NatSpecMultiLine
increaseAllowance
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); 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. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 3530, 3738 ] }
58,423
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
ERC20
contract ERC20 is IERC20, Ownable { 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); } /** * @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)); } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * 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. */
NatSpecMultiLine
decreaseAllowance
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); 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. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 4264, 4482 ] }
58,424
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
ERC20
contract ERC20 is IERC20, Ownable { 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); } /** * @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)); } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * 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. */
NatSpecMultiLine
_transfer
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 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. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 4705, 4972 ] }
58,425
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
ERC20
contract ERC20 is IERC20, Ownable { 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); } /** * @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)); } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * 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. */
NatSpecMultiLine
_mint
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 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. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 5319, 5593 ] }
58,426
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
ERC20
contract ERC20 is IERC20, Ownable { 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); } /** * @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)); } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * 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. */
NatSpecMultiLine
_burn
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 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. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 5822, 6096 ] }
58,427
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
ERC20
contract ERC20 is IERC20, Ownable { 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); } /** * @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)); } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * 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. */
NatSpecMultiLine
_approve
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 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. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 6364, 6623 ] }
58,428
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
ERC20
contract ERC20 is IERC20, Ownable { 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); } /** * @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)); } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * 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. */
NatSpecMultiLine
_burnFrom
function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(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. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 7017, 7204 ] }
58,429
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
ERC20Detailed
contract ERC20Detailed is ERC20 { string constant private _name = "VECOIN "; string constant private _symbol = "VECX"; uint256 constant private _decimals = 8; /** * @return the name of the token. */ function name() public pure returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public pure returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public pure returns (uint256) { return _decimals; } }
/** * @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. */
NatSpecMultiLine
name
function name() public pure returns (string memory) { return _name; }
/** * @return the name of the token. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 236, 324 ] }
58,430
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
ERC20Detailed
contract ERC20Detailed is ERC20 { string constant private _name = "VECOIN "; string constant private _symbol = "VECX"; uint256 constant private _decimals = 8; /** * @return the name of the token. */ function name() public pure returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public pure returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public pure returns (uint256) { return _decimals; } }
/** * @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. */
NatSpecMultiLine
symbol
function symbol() public pure returns (string memory) { return _symbol; }
/** * @return the symbol of the token. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 386, 478 ] }
58,431
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
ERC20Detailed
contract ERC20Detailed is ERC20 { string constant private _name = "VECOIN "; string constant private _symbol = "VECX"; uint256 constant private _decimals = 8; /** * @return the name of the token. */ function name() public pure returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public pure returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public pure returns (uint256) { return _decimals; } }
/** * @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. */
NatSpecMultiLine
decimals
function decimals() public pure returns (uint256) { return _decimals; }
/** * @return the number of decimals of the token. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 552, 642 ] }
58,432
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
VeCoin
contract VeCoin is ERC20Detailed { constructor() public { uint256 totalSupply = 21000000000 * (10 ** decimals()); _mint(0x5f7F964eFd5E122049911006912056ebe83C547F,totalSupply); } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance. * @param from address The account whose tokens will be burned. * @param value uint256 The amount of token to be burned. */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } function transfer(address _to, uint256 _value) public returns (bool) { return super.transfer(_to,_value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { return super.transferFrom(_from, _to, _value); } function increaseAllowance(address _spender, uint _addedValue) public returns (bool) { return super.increaseAllowance(_spender, _addedValue); } function decreaseAllowance(address _spender, uint _subtractedValue) public returns (bool) { return super.decreaseAllowance(_spender, _subtractedValue); } }
burn
function burn(uint256 value) public { _burn(msg.sender, value); }
/** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 338, 422 ] }
58,433
VeCoin
VeCoin.sol
0xfee581bfe5b479644535ff51b9f04b33db6f8a0f
Solidity
VeCoin
contract VeCoin is ERC20Detailed { constructor() public { uint256 totalSupply = 21000000000 * (10 ** decimals()); _mint(0x5f7F964eFd5E122049911006912056ebe83C547F,totalSupply); } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance. * @param from address The account whose tokens will be burned. * @param value uint256 The amount of token to be burned. */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } function transfer(address _to, uint256 _value) public returns (bool) { return super.transfer(_to,_value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { return super.transferFrom(_from, _to, _value); } function increaseAllowance(address _spender, uint _addedValue) public returns (bool) { return super.increaseAllowance(_spender, _addedValue); } function decreaseAllowance(address _spender, uint _subtractedValue) public returns (bool) { return super.decreaseAllowance(_spender, _subtractedValue); } }
burnFrom
function burnFrom(address from, uint256 value) public { _burnFrom(from, value); }
/** * @dev Burns a specific amount of tokens from the target address and decrements allowance. * @param from address The account whose tokens will be burned. * @param value uint256 The amount of token to be burned. */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://02728af1698cb44a3cab106ec4a68085420e0a285bc5078b60f21c983e8b40bf
{ "func_code_index": [ 676, 776 ] }
58,434
PriIPoolTemplate
localhost/interface/IERC20.sol
0x3b210fa9bce89b760797b43fcd6eeb808588f86e
Solidity
IERC20
interface IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); 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 `amount` tokens are moved from one account (`sender`) to * another (`recipient`). * * Note that `amount` may be zero. */ event Transfer(address indexed sender, address indexed recipient, uint256 amount); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `amount` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 amount); }
balanceOf
function balanceOf(address account) external view returns (uint256);
/** * @dev Returns the amount of tokens owned by `account`. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
MIT
ipfs://127dec459665ed171c7f632fff44c82a49f0cac568999898151c250b1484f7f0
{ "func_code_index": [ 349, 422 ] }
58,435
PriIPoolTemplate
localhost/interface/IERC20.sol
0x3b210fa9bce89b760797b43fcd6eeb808588f86e
Solidity
IERC20
interface IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); 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 `amount` tokens are moved from one account (`sender`) to * another (`recipient`). * * Note that `amount` may be zero. */ event Transfer(address indexed sender, address indexed recipient, uint256 amount); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `amount` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 amount); }
transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
MIT
ipfs://127dec459665ed171c7f632fff44c82a49f0cac568999898151c250b1484f7f0
{ "func_code_index": [ 646, 728 ] }
58,436
PriIPoolTemplate
localhost/interface/IERC20.sol
0x3b210fa9bce89b760797b43fcd6eeb808588f86e
Solidity
IERC20
interface IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); 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 `amount` tokens are moved from one account (`sender`) to * another (`recipient`). * * Note that `amount` may be zero. */ event Transfer(address indexed sender, address indexed recipient, uint256 amount); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `amount` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 amount); }
allowance
function allowance(address owner, address spender) external view returns (uint256);
/** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
MIT
ipfs://127dec459665ed171c7f632fff44c82a49f0cac568999898151c250b1484f7f0
{ "func_code_index": [ 1007, 1095 ] }
58,437
PriIPoolTemplate
localhost/interface/IERC20.sol
0x3b210fa9bce89b760797b43fcd6eeb808588f86e
Solidity
IERC20
interface IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); 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 `amount` tokens are moved from one account (`sender`) to * another (`recipient`). * * Note that `amount` may be zero. */ event Transfer(address indexed sender, address indexed recipient, uint256 amount); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `amount` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 amount); }
approve
function approve(address spender, uint256 amount) external returns (bool);
/** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
MIT
ipfs://127dec459665ed171c7f632fff44c82a49f0cac568999898151c250b1484f7f0
{ "func_code_index": [ 1759, 1838 ] }
58,438
PriIPoolTemplate
localhost/interface/IERC20.sol
0x3b210fa9bce89b760797b43fcd6eeb808588f86e
Solidity
IERC20
interface IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); 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 `amount` tokens are moved from one account (`sender`) to * another (`recipient`). * * Note that `amount` may be zero. */ event Transfer(address indexed sender, address indexed recipient, uint256 amount); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `amount` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 amount); }
transferFrom
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
MIT
ipfs://127dec459665ed171c7f632fff44c82a49f0cac568999898151c250b1484f7f0
{ "func_code_index": [ 2151, 2253 ] }
58,439
fragmentClaimer
Address.sol
0xee30651c467d40a1cf09011168e3c21c7ae7a59c
Solidity
Address
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"); } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
isContract
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 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. */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
None
bzzr://45f1717a79bde92515920374a30077a127b7f7e73088c98aa39d9dadf20483c0
{ "func_code_index": [ 460, 1261 ] }
58,440
fragmentClaimer
Address.sol
0xee30651c467d40a1cf09011168e3c21c7ae7a59c
Solidity
Address
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"); } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
toPayable
function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); }
/** * @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._ */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
None
bzzr://45f1717a79bde92515920374a30077a127b7f7e73088c98aa39d9dadf20483c0
{ "func_code_index": [ 1466, 1595 ] }
58,441
fragmentClaimer
Address.sol
0xee30651c467d40a1cf09011168e3c21c7ae7a59c
Solidity
Address
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"); } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
sendValue
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"); }
/** * @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._ */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
None
bzzr://45f1717a79bde92515920374a30077a127b7f7e73088c98aa39d9dadf20483c0
{ "func_code_index": [ 2548, 2917 ] }
58,442
fragmentClaimer
ERC721MetadataMintable.sol
0xee30651c467d40a1cf09011168e3c21c7ae7a59c
Solidity
ERC721MetadataMintable
contract ERC721MetadataMintable is ERC721, ERC721Metadata, MinterRole { constructor(string memory name, string memory symbol) ERC721Metadata(name, symbol) public {} /** * @dev Function to mint tokens. * @param to The address that will receive the minted tokens. * @param tokenId The token id to mint. * @param tokenURI The token URI of the minted token. * @return A boolean that indicates if the operation was successful. */ function mintWithTokenURI(address to, uint256 tokenId, string memory tokenURI) public onlyMinter returns (bool) { _mint(to, tokenId); _setTokenURI(tokenId, tokenURI); return true; } }
/** * @title ERC721MetadataMintable * @dev ERC721 minting logic with metadata. */
NatSpecMultiLine
mintWithTokenURI
function mintWithTokenURI(address to, uint256 tokenId, string memory tokenURI) public onlyMinter returns (bool) { _mint(to, tokenId); _setTokenURI(tokenId, tokenURI); return true; }
/** * @dev Function to mint tokens. * @param to The address that will receive the minted tokens. * @param tokenId The token id to mint. * @param tokenURI The token URI of the minted token. * @return A boolean that indicates if the operation was successful. */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
None
bzzr://45f1717a79bde92515920374a30077a127b7f7e73088c98aa39d9dadf20483c0
{ "func_code_index": [ 463, 676 ] }
58,443
RegulatorProxyFactory
RegulatorProxyFactory.sol
0x8180522f083bf9a1f756745e5decff48e007d370
Solidity
Proxy
contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ function () payable external { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal { } /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } }
/** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */
NatSpecMultiLine
function () payable external { _fallback(); }
/** * @dev Fallback function. * Implemented entirely in `_fallback`. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3
{ "func_code_index": [ 105, 161 ] }
58,444
RegulatorProxyFactory
RegulatorProxyFactory.sol
0x8180522f083bf9a1f756745e5decff48e007d370
Solidity
Proxy
contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ function () payable external { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal { } /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } }
/** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */
NatSpecMultiLine
_implementation
function _implementation() internal view returns (address);
/** * @return The Address of the implementation. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3
{ "func_code_index": [ 227, 289 ] }
58,445
RegulatorProxyFactory
RegulatorProxyFactory.sol
0x8180522f083bf9a1f756745e5decff48e007d370
Solidity
Proxy
contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ function () payable external { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal { } /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } }
/** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */
NatSpecMultiLine
_delegate
function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } }
/** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3
{ "func_code_index": [ 580, 1333 ] }
58,446
RegulatorProxyFactory
RegulatorProxyFactory.sol
0x8180522f083bf9a1f756745e5decff48e007d370
Solidity
Proxy
contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ function () payable external { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal { } /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } }
/** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */
NatSpecMultiLine
_willFallback
function _willFallback() internal { }
/** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3
{ "func_code_index": [ 1546, 1589 ] }
58,447
RegulatorProxyFactory
RegulatorProxyFactory.sol
0x8180522f083bf9a1f756745e5decff48e007d370
Solidity
Proxy
contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ function () payable external { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal { } /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } }
/** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */
NatSpecMultiLine
_fallback
function _fallback() internal { _willFallback(); _delegate(_implementation()); }
/** * @dev fallback implementation. * Extracted to enable manual triggering. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3
{ "func_code_index": [ 1687, 1783 ] }
58,448
RegulatorProxyFactory
RegulatorProxyFactory.sol
0x8180522f083bf9a1f756745e5decff48e007d370
Solidity
AddressUtils
library AddressUtils { /** * 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 addr address to check * @return whether the target address is a contract */ function isContract(address addr) 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. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } }
/** * Utility library of inline functions on addresses */
NatSpecMultiLine
isContract
function isContract(address addr) 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. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; }
/** * 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 addr address to check * @return whether the target address is a contract */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3
{ "func_code_index": [ 358, 948 ] }
58,449
RegulatorProxyFactory
RegulatorProxyFactory.sol
0x8180522f083bf9a1f756745e5decff48e007d370
Solidity
UpgradeabilityProxy
contract UpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is * validated in the constructor. */ bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; /** * @dev Contract constructor. * @param _implementation Address of the initial implementation. */ constructor(address _implementation) public { assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation")); _setImplementation(_implementation); } /** * @dev Returns the current implementation. * @return Address of the current implementation */ function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) private { require(AddressUtils.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } }
/** * @title UpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */
NatSpecMultiLine
_implementation
function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } }
/** * @dev Returns the current implementation. * @return Address of the current implementation */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3
{ "func_code_index": [ 958, 1122 ] }
58,450
RegulatorProxyFactory
RegulatorProxyFactory.sol
0x8180522f083bf9a1f756745e5decff48e007d370
Solidity
UpgradeabilityProxy
contract UpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is * validated in the constructor. */ bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; /** * @dev Contract constructor. * @param _implementation Address of the initial implementation. */ constructor(address _implementation) public { assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation")); _setImplementation(_implementation); } /** * @dev Returns the current implementation. * @return Address of the current implementation */ function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) private { require(AddressUtils.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } }
/** * @title UpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */
NatSpecMultiLine
_upgradeTo
function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); }
/** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3
{ "func_code_index": [ 1260, 1408 ] }
58,451
RegulatorProxyFactory
RegulatorProxyFactory.sol
0x8180522f083bf9a1f756745e5decff48e007d370
Solidity
UpgradeabilityProxy
contract UpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is * validated in the constructor. */ bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; /** * @dev Contract constructor. * @param _implementation Address of the initial implementation. */ constructor(address _implementation) public { assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation")); _setImplementation(_implementation); } /** * @dev Returns the current implementation. * @return Address of the current implementation */ function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) private { require(AddressUtils.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } }
/** * @title UpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */
NatSpecMultiLine
_setImplementation
function _setImplementation(address newImplementation) private { require(AddressUtils.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } }
/** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3
{ "func_code_index": [ 1548, 1848 ] }
58,452
RegulatorProxyFactory
RegulatorProxyFactory.sol
0x8180522f083bf9a1f756745e5decff48e007d370
Solidity
Ownable
contract Ownable { address public owner; address public pendingOwner; 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; pendingOwner = address(0); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @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)); pendingOwner = _newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". This adds two-phase * ownership control to OpenZeppelin's Ownable class. In this model, the original owner * designates a new owner but does not actually transfer ownership. The new owner then accepts * ownership and completes the transfer. */
NatSpecMultiLine
transferOwnership
function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); pendingOwner = _newOwner; }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3
{ "func_code_index": [ 884, 1026 ] }
58,453
RegulatorProxyFactory
RegulatorProxyFactory.sol
0x8180522f083bf9a1f756745e5decff48e007d370
Solidity
Ownable
contract Ownable { address public owner; address public pendingOwner; 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; pendingOwner = address(0); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @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)); pendingOwner = _newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". This adds two-phase * ownership control to OpenZeppelin's Ownable class. In this model, the original owner * designates a new owner but does not actually transfer ownership. The new owner then accepts * ownership and completes the transfer. */
NatSpecMultiLine
claimOwnership
function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); }
/** * @dev Allows the pendingOwner address to finalize the transfer. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3
{ "func_code_index": [ 1112, 1283 ] }
58,454
RegulatorProxyFactory
RegulatorProxyFactory.sol
0x8180522f083bf9a1f756745e5decff48e007d370
Solidity
RegulatorStorage
contract RegulatorStorage is Ownable { /** Structs */ /* Contains metadata about a permission to execute a particular method signature. */ struct Permission { string name; // A one-word description for the permission. e.g. "canMint" string description; // A longer description for the permission. e.g. "Allows user to mint tokens." string contract_name; // e.g. "PermissionedToken" bool active; // Permissions can be turned on or off by regulator } /** Constants: stores method signatures. These are potential permissions that a user can have, and each permission gives the user the ability to call the associated PermissionedToken method signature */ bytes4 public constant MINT_SIG = bytes4(keccak256("mint(address,uint256)")); bytes4 public constant MINT_CUSD_SIG = bytes4(keccak256("mintCUSD(address,uint256)")); bytes4 public constant DESTROY_BLACKLISTED_TOKENS_SIG = bytes4(keccak256("destroyBlacklistedTokens(address,uint256)")); bytes4 public constant APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG = bytes4(keccak256("approveBlacklistedAddressSpender(address)")); bytes4 public constant BLACKLISTED_SIG = bytes4(keccak256("blacklisted()")); /** Mappings */ /* each method signature maps to a Permission */ mapping (bytes4 => Permission) public permissions; /* list of validators, either active or inactive */ mapping (address => bool) public validators; /* each user can be given access to a given method signature */ mapping (address => mapping (bytes4 => bool)) public userPermissions; /** Events */ event PermissionAdded(bytes4 methodsignature); event PermissionRemoved(bytes4 methodsignature); event ValidatorAdded(address indexed validator); event ValidatorRemoved(address indexed validator); /** Modifiers */ /** * @notice Throws if called by any account that does not have access to set attributes */ modifier onlyValidator() { require (isValidator(msg.sender), "Sender must be validator"); _; } /** * @notice Sets a permission within the list of permissions. * @param _methodsignature Signature of the method that this permission controls. * @param _permissionName A "slug" name for this permission (e.g. "canMint"). * @param _permissionDescription A lengthier description for this permission (e.g. "Allows user to mint tokens"). * @param _contractName Name of the contract that the method belongs to. */ function addPermission( bytes4 _methodsignature, string _permissionName, string _permissionDescription, string _contractName) public onlyValidator { Permission memory p = Permission(_permissionName, _permissionDescription, _contractName, true); permissions[_methodsignature] = p; emit PermissionAdded(_methodsignature); } /** * @notice Removes a permission the list of permissions. * @param _methodsignature Signature of the method that this permission controls. */ function removePermission(bytes4 _methodsignature) public onlyValidator { permissions[_methodsignature].active = false; emit PermissionRemoved(_methodsignature); } /** * @notice Sets a permission in the list of permissions that a user has. * @param _methodsignature Signature of the method that this permission controls. */ function setUserPermission(address _who, bytes4 _methodsignature) public onlyValidator { require(permissions[_methodsignature].active, "Permission being set must be for a valid method signature"); userPermissions[_who][_methodsignature] = true; } /** * @notice Removes a permission from the list of permissions that a user has. * @param _methodsignature Signature of the method that this permission controls. */ function removeUserPermission(address _who, bytes4 _methodsignature) public onlyValidator { require(permissions[_methodsignature].active, "Permission being removed must be for a valid method signature"); userPermissions[_who][_methodsignature] = false; } /** * @notice add a Validator * @param _validator Address of validator to add */ function addValidator(address _validator) public onlyOwner { validators[_validator] = true; emit ValidatorAdded(_validator); } /** * @notice remove a Validator * @param _validator Address of validator to remove */ function removeValidator(address _validator) public onlyOwner { validators[_validator] = false; emit ValidatorRemoved(_validator); } /** * @notice does validator exist? * @return true if yes, false if no **/ function isValidator(address _validator) public view returns (bool) { return validators[_validator]; } /** * @notice does permission exist? * @return true if yes, false if no **/ function isPermission(bytes4 _methodsignature) public view returns (bool) { return permissions[_methodsignature].active; } /** * @notice get Permission structure * @param _methodsignature request to retrieve the Permission struct for this methodsignature * @return Permission **/ function getPermission(bytes4 _methodsignature) public view returns (string name, string description, string contract_name, bool active) { return (permissions[_methodsignature].name, permissions[_methodsignature].description, permissions[_methodsignature].contract_name, permissions[_methodsignature].active); } /** * @notice does permission exist? * @return true if yes, false if no **/ function hasUserPermission(address _who, bytes4 _methodsignature) public view returns (bool) { return userPermissions[_who][_methodsignature]; } }
/** * * @dev Stores permissions and validators and provides setter and getter methods. * Permissions determine which methods users have access to call. Validators * are able to mutate permissions at the Regulator level. * */
NatSpecMultiLine
addPermission
function addPermission( bytes4 _methodsignature, string _permissionName, string _permissionDescription, string _contractName) public onlyValidator { Permission memory p = Permission(_permissionName, _permissionDescription, _contractName, true); permissions[_methodsignature] = p; emit PermissionAdded(_methodsignature); }
/** * @notice Sets a permission within the list of permissions. * @param _methodsignature Signature of the method that this permission controls. * @param _permissionName A "slug" name for this permission (e.g. "canMint"). * @param _permissionDescription A lengthier description for this permission (e.g. "Allows user to mint tokens"). * @param _contractName Name of the contract that the method belongs to. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3
{ "func_code_index": [ 2654, 3052 ] }
58,455
RegulatorProxyFactory
RegulatorProxyFactory.sol
0x8180522f083bf9a1f756745e5decff48e007d370
Solidity
RegulatorStorage
contract RegulatorStorage is Ownable { /** Structs */ /* Contains metadata about a permission to execute a particular method signature. */ struct Permission { string name; // A one-word description for the permission. e.g. "canMint" string description; // A longer description for the permission. e.g. "Allows user to mint tokens." string contract_name; // e.g. "PermissionedToken" bool active; // Permissions can be turned on or off by regulator } /** Constants: stores method signatures. These are potential permissions that a user can have, and each permission gives the user the ability to call the associated PermissionedToken method signature */ bytes4 public constant MINT_SIG = bytes4(keccak256("mint(address,uint256)")); bytes4 public constant MINT_CUSD_SIG = bytes4(keccak256("mintCUSD(address,uint256)")); bytes4 public constant DESTROY_BLACKLISTED_TOKENS_SIG = bytes4(keccak256("destroyBlacklistedTokens(address,uint256)")); bytes4 public constant APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG = bytes4(keccak256("approveBlacklistedAddressSpender(address)")); bytes4 public constant BLACKLISTED_SIG = bytes4(keccak256("blacklisted()")); /** Mappings */ /* each method signature maps to a Permission */ mapping (bytes4 => Permission) public permissions; /* list of validators, either active or inactive */ mapping (address => bool) public validators; /* each user can be given access to a given method signature */ mapping (address => mapping (bytes4 => bool)) public userPermissions; /** Events */ event PermissionAdded(bytes4 methodsignature); event PermissionRemoved(bytes4 methodsignature); event ValidatorAdded(address indexed validator); event ValidatorRemoved(address indexed validator); /** Modifiers */ /** * @notice Throws if called by any account that does not have access to set attributes */ modifier onlyValidator() { require (isValidator(msg.sender), "Sender must be validator"); _; } /** * @notice Sets a permission within the list of permissions. * @param _methodsignature Signature of the method that this permission controls. * @param _permissionName A "slug" name for this permission (e.g. "canMint"). * @param _permissionDescription A lengthier description for this permission (e.g. "Allows user to mint tokens"). * @param _contractName Name of the contract that the method belongs to. */ function addPermission( bytes4 _methodsignature, string _permissionName, string _permissionDescription, string _contractName) public onlyValidator { Permission memory p = Permission(_permissionName, _permissionDescription, _contractName, true); permissions[_methodsignature] = p; emit PermissionAdded(_methodsignature); } /** * @notice Removes a permission the list of permissions. * @param _methodsignature Signature of the method that this permission controls. */ function removePermission(bytes4 _methodsignature) public onlyValidator { permissions[_methodsignature].active = false; emit PermissionRemoved(_methodsignature); } /** * @notice Sets a permission in the list of permissions that a user has. * @param _methodsignature Signature of the method that this permission controls. */ function setUserPermission(address _who, bytes4 _methodsignature) public onlyValidator { require(permissions[_methodsignature].active, "Permission being set must be for a valid method signature"); userPermissions[_who][_methodsignature] = true; } /** * @notice Removes a permission from the list of permissions that a user has. * @param _methodsignature Signature of the method that this permission controls. */ function removeUserPermission(address _who, bytes4 _methodsignature) public onlyValidator { require(permissions[_methodsignature].active, "Permission being removed must be for a valid method signature"); userPermissions[_who][_methodsignature] = false; } /** * @notice add a Validator * @param _validator Address of validator to add */ function addValidator(address _validator) public onlyOwner { validators[_validator] = true; emit ValidatorAdded(_validator); } /** * @notice remove a Validator * @param _validator Address of validator to remove */ function removeValidator(address _validator) public onlyOwner { validators[_validator] = false; emit ValidatorRemoved(_validator); } /** * @notice does validator exist? * @return true if yes, false if no **/ function isValidator(address _validator) public view returns (bool) { return validators[_validator]; } /** * @notice does permission exist? * @return true if yes, false if no **/ function isPermission(bytes4 _methodsignature) public view returns (bool) { return permissions[_methodsignature].active; } /** * @notice get Permission structure * @param _methodsignature request to retrieve the Permission struct for this methodsignature * @return Permission **/ function getPermission(bytes4 _methodsignature) public view returns (string name, string description, string contract_name, bool active) { return (permissions[_methodsignature].name, permissions[_methodsignature].description, permissions[_methodsignature].contract_name, permissions[_methodsignature].active); } /** * @notice does permission exist? * @return true if yes, false if no **/ function hasUserPermission(address _who, bytes4 _methodsignature) public view returns (bool) { return userPermissions[_who][_methodsignature]; } }
/** * * @dev Stores permissions and validators and provides setter and getter methods. * Permissions determine which methods users have access to call. Validators * are able to mutate permissions at the Regulator level. * */
NatSpecMultiLine
removePermission
function removePermission(bytes4 _methodsignature) public onlyValidator { permissions[_methodsignature].active = false; emit PermissionRemoved(_methodsignature); }
/** * @notice Removes a permission the list of permissions. * @param _methodsignature Signature of the method that this permission controls. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3
{ "func_code_index": [ 3219, 3410 ] }
58,456
RegulatorProxyFactory
RegulatorProxyFactory.sol
0x8180522f083bf9a1f756745e5decff48e007d370
Solidity
RegulatorStorage
contract RegulatorStorage is Ownable { /** Structs */ /* Contains metadata about a permission to execute a particular method signature. */ struct Permission { string name; // A one-word description for the permission. e.g. "canMint" string description; // A longer description for the permission. e.g. "Allows user to mint tokens." string contract_name; // e.g. "PermissionedToken" bool active; // Permissions can be turned on or off by regulator } /** Constants: stores method signatures. These are potential permissions that a user can have, and each permission gives the user the ability to call the associated PermissionedToken method signature */ bytes4 public constant MINT_SIG = bytes4(keccak256("mint(address,uint256)")); bytes4 public constant MINT_CUSD_SIG = bytes4(keccak256("mintCUSD(address,uint256)")); bytes4 public constant DESTROY_BLACKLISTED_TOKENS_SIG = bytes4(keccak256("destroyBlacklistedTokens(address,uint256)")); bytes4 public constant APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG = bytes4(keccak256("approveBlacklistedAddressSpender(address)")); bytes4 public constant BLACKLISTED_SIG = bytes4(keccak256("blacklisted()")); /** Mappings */ /* each method signature maps to a Permission */ mapping (bytes4 => Permission) public permissions; /* list of validators, either active or inactive */ mapping (address => bool) public validators; /* each user can be given access to a given method signature */ mapping (address => mapping (bytes4 => bool)) public userPermissions; /** Events */ event PermissionAdded(bytes4 methodsignature); event PermissionRemoved(bytes4 methodsignature); event ValidatorAdded(address indexed validator); event ValidatorRemoved(address indexed validator); /** Modifiers */ /** * @notice Throws if called by any account that does not have access to set attributes */ modifier onlyValidator() { require (isValidator(msg.sender), "Sender must be validator"); _; } /** * @notice Sets a permission within the list of permissions. * @param _methodsignature Signature of the method that this permission controls. * @param _permissionName A "slug" name for this permission (e.g. "canMint"). * @param _permissionDescription A lengthier description for this permission (e.g. "Allows user to mint tokens"). * @param _contractName Name of the contract that the method belongs to. */ function addPermission( bytes4 _methodsignature, string _permissionName, string _permissionDescription, string _contractName) public onlyValidator { Permission memory p = Permission(_permissionName, _permissionDescription, _contractName, true); permissions[_methodsignature] = p; emit PermissionAdded(_methodsignature); } /** * @notice Removes a permission the list of permissions. * @param _methodsignature Signature of the method that this permission controls. */ function removePermission(bytes4 _methodsignature) public onlyValidator { permissions[_methodsignature].active = false; emit PermissionRemoved(_methodsignature); } /** * @notice Sets a permission in the list of permissions that a user has. * @param _methodsignature Signature of the method that this permission controls. */ function setUserPermission(address _who, bytes4 _methodsignature) public onlyValidator { require(permissions[_methodsignature].active, "Permission being set must be for a valid method signature"); userPermissions[_who][_methodsignature] = true; } /** * @notice Removes a permission from the list of permissions that a user has. * @param _methodsignature Signature of the method that this permission controls. */ function removeUserPermission(address _who, bytes4 _methodsignature) public onlyValidator { require(permissions[_methodsignature].active, "Permission being removed must be for a valid method signature"); userPermissions[_who][_methodsignature] = false; } /** * @notice add a Validator * @param _validator Address of validator to add */ function addValidator(address _validator) public onlyOwner { validators[_validator] = true; emit ValidatorAdded(_validator); } /** * @notice remove a Validator * @param _validator Address of validator to remove */ function removeValidator(address _validator) public onlyOwner { validators[_validator] = false; emit ValidatorRemoved(_validator); } /** * @notice does validator exist? * @return true if yes, false if no **/ function isValidator(address _validator) public view returns (bool) { return validators[_validator]; } /** * @notice does permission exist? * @return true if yes, false if no **/ function isPermission(bytes4 _methodsignature) public view returns (bool) { return permissions[_methodsignature].active; } /** * @notice get Permission structure * @param _methodsignature request to retrieve the Permission struct for this methodsignature * @return Permission **/ function getPermission(bytes4 _methodsignature) public view returns (string name, string description, string contract_name, bool active) { return (permissions[_methodsignature].name, permissions[_methodsignature].description, permissions[_methodsignature].contract_name, permissions[_methodsignature].active); } /** * @notice does permission exist? * @return true if yes, false if no **/ function hasUserPermission(address _who, bytes4 _methodsignature) public view returns (bool) { return userPermissions[_who][_methodsignature]; } }
/** * * @dev Stores permissions and validators and provides setter and getter methods. * Permissions determine which methods users have access to call. Validators * are able to mutate permissions at the Regulator level. * */
NatSpecMultiLine
setUserPermission
function setUserPermission(address _who, bytes4 _methodsignature) public onlyValidator { require(permissions[_methodsignature].active, "Permission being set must be for a valid method signature"); userPermissions[_who][_methodsignature] = true; }
/** * @notice Sets a permission in the list of permissions that a user has. * @param _methodsignature Signature of the method that this permission controls. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3
{ "func_code_index": [ 3597, 3871 ] }
58,457
RegulatorProxyFactory
RegulatorProxyFactory.sol
0x8180522f083bf9a1f756745e5decff48e007d370
Solidity
RegulatorStorage
contract RegulatorStorage is Ownable { /** Structs */ /* Contains metadata about a permission to execute a particular method signature. */ struct Permission { string name; // A one-word description for the permission. e.g. "canMint" string description; // A longer description for the permission. e.g. "Allows user to mint tokens." string contract_name; // e.g. "PermissionedToken" bool active; // Permissions can be turned on or off by regulator } /** Constants: stores method signatures. These are potential permissions that a user can have, and each permission gives the user the ability to call the associated PermissionedToken method signature */ bytes4 public constant MINT_SIG = bytes4(keccak256("mint(address,uint256)")); bytes4 public constant MINT_CUSD_SIG = bytes4(keccak256("mintCUSD(address,uint256)")); bytes4 public constant DESTROY_BLACKLISTED_TOKENS_SIG = bytes4(keccak256("destroyBlacklistedTokens(address,uint256)")); bytes4 public constant APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG = bytes4(keccak256("approveBlacklistedAddressSpender(address)")); bytes4 public constant BLACKLISTED_SIG = bytes4(keccak256("blacklisted()")); /** Mappings */ /* each method signature maps to a Permission */ mapping (bytes4 => Permission) public permissions; /* list of validators, either active or inactive */ mapping (address => bool) public validators; /* each user can be given access to a given method signature */ mapping (address => mapping (bytes4 => bool)) public userPermissions; /** Events */ event PermissionAdded(bytes4 methodsignature); event PermissionRemoved(bytes4 methodsignature); event ValidatorAdded(address indexed validator); event ValidatorRemoved(address indexed validator); /** Modifiers */ /** * @notice Throws if called by any account that does not have access to set attributes */ modifier onlyValidator() { require (isValidator(msg.sender), "Sender must be validator"); _; } /** * @notice Sets a permission within the list of permissions. * @param _methodsignature Signature of the method that this permission controls. * @param _permissionName A "slug" name for this permission (e.g. "canMint"). * @param _permissionDescription A lengthier description for this permission (e.g. "Allows user to mint tokens"). * @param _contractName Name of the contract that the method belongs to. */ function addPermission( bytes4 _methodsignature, string _permissionName, string _permissionDescription, string _contractName) public onlyValidator { Permission memory p = Permission(_permissionName, _permissionDescription, _contractName, true); permissions[_methodsignature] = p; emit PermissionAdded(_methodsignature); } /** * @notice Removes a permission the list of permissions. * @param _methodsignature Signature of the method that this permission controls. */ function removePermission(bytes4 _methodsignature) public onlyValidator { permissions[_methodsignature].active = false; emit PermissionRemoved(_methodsignature); } /** * @notice Sets a permission in the list of permissions that a user has. * @param _methodsignature Signature of the method that this permission controls. */ function setUserPermission(address _who, bytes4 _methodsignature) public onlyValidator { require(permissions[_methodsignature].active, "Permission being set must be for a valid method signature"); userPermissions[_who][_methodsignature] = true; } /** * @notice Removes a permission from the list of permissions that a user has. * @param _methodsignature Signature of the method that this permission controls. */ function removeUserPermission(address _who, bytes4 _methodsignature) public onlyValidator { require(permissions[_methodsignature].active, "Permission being removed must be for a valid method signature"); userPermissions[_who][_methodsignature] = false; } /** * @notice add a Validator * @param _validator Address of validator to add */ function addValidator(address _validator) public onlyOwner { validators[_validator] = true; emit ValidatorAdded(_validator); } /** * @notice remove a Validator * @param _validator Address of validator to remove */ function removeValidator(address _validator) public onlyOwner { validators[_validator] = false; emit ValidatorRemoved(_validator); } /** * @notice does validator exist? * @return true if yes, false if no **/ function isValidator(address _validator) public view returns (bool) { return validators[_validator]; } /** * @notice does permission exist? * @return true if yes, false if no **/ function isPermission(bytes4 _methodsignature) public view returns (bool) { return permissions[_methodsignature].active; } /** * @notice get Permission structure * @param _methodsignature request to retrieve the Permission struct for this methodsignature * @return Permission **/ function getPermission(bytes4 _methodsignature) public view returns (string name, string description, string contract_name, bool active) { return (permissions[_methodsignature].name, permissions[_methodsignature].description, permissions[_methodsignature].contract_name, permissions[_methodsignature].active); } /** * @notice does permission exist? * @return true if yes, false if no **/ function hasUserPermission(address _who, bytes4 _methodsignature) public view returns (bool) { return userPermissions[_who][_methodsignature]; } }
/** * * @dev Stores permissions and validators and provides setter and getter methods. * Permissions determine which methods users have access to call. Validators * are able to mutate permissions at the Regulator level. * */
NatSpecMultiLine
removeUserPermission
function removeUserPermission(address _who, bytes4 _methodsignature) public onlyValidator { require(permissions[_methodsignature].active, "Permission being removed must be for a valid method signature"); userPermissions[_who][_methodsignature] = false; }
/** * @notice Removes a permission from the list of permissions that a user has. * @param _methodsignature Signature of the method that this permission controls. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3
{ "func_code_index": [ 4059, 4341 ] }
58,458
RegulatorProxyFactory
RegulatorProxyFactory.sol
0x8180522f083bf9a1f756745e5decff48e007d370
Solidity
RegulatorStorage
contract RegulatorStorage is Ownable { /** Structs */ /* Contains metadata about a permission to execute a particular method signature. */ struct Permission { string name; // A one-word description for the permission. e.g. "canMint" string description; // A longer description for the permission. e.g. "Allows user to mint tokens." string contract_name; // e.g. "PermissionedToken" bool active; // Permissions can be turned on or off by regulator } /** Constants: stores method signatures. These are potential permissions that a user can have, and each permission gives the user the ability to call the associated PermissionedToken method signature */ bytes4 public constant MINT_SIG = bytes4(keccak256("mint(address,uint256)")); bytes4 public constant MINT_CUSD_SIG = bytes4(keccak256("mintCUSD(address,uint256)")); bytes4 public constant DESTROY_BLACKLISTED_TOKENS_SIG = bytes4(keccak256("destroyBlacklistedTokens(address,uint256)")); bytes4 public constant APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG = bytes4(keccak256("approveBlacklistedAddressSpender(address)")); bytes4 public constant BLACKLISTED_SIG = bytes4(keccak256("blacklisted()")); /** Mappings */ /* each method signature maps to a Permission */ mapping (bytes4 => Permission) public permissions; /* list of validators, either active or inactive */ mapping (address => bool) public validators; /* each user can be given access to a given method signature */ mapping (address => mapping (bytes4 => bool)) public userPermissions; /** Events */ event PermissionAdded(bytes4 methodsignature); event PermissionRemoved(bytes4 methodsignature); event ValidatorAdded(address indexed validator); event ValidatorRemoved(address indexed validator); /** Modifiers */ /** * @notice Throws if called by any account that does not have access to set attributes */ modifier onlyValidator() { require (isValidator(msg.sender), "Sender must be validator"); _; } /** * @notice Sets a permission within the list of permissions. * @param _methodsignature Signature of the method that this permission controls. * @param _permissionName A "slug" name for this permission (e.g. "canMint"). * @param _permissionDescription A lengthier description for this permission (e.g. "Allows user to mint tokens"). * @param _contractName Name of the contract that the method belongs to. */ function addPermission( bytes4 _methodsignature, string _permissionName, string _permissionDescription, string _contractName) public onlyValidator { Permission memory p = Permission(_permissionName, _permissionDescription, _contractName, true); permissions[_methodsignature] = p; emit PermissionAdded(_methodsignature); } /** * @notice Removes a permission the list of permissions. * @param _methodsignature Signature of the method that this permission controls. */ function removePermission(bytes4 _methodsignature) public onlyValidator { permissions[_methodsignature].active = false; emit PermissionRemoved(_methodsignature); } /** * @notice Sets a permission in the list of permissions that a user has. * @param _methodsignature Signature of the method that this permission controls. */ function setUserPermission(address _who, bytes4 _methodsignature) public onlyValidator { require(permissions[_methodsignature].active, "Permission being set must be for a valid method signature"); userPermissions[_who][_methodsignature] = true; } /** * @notice Removes a permission from the list of permissions that a user has. * @param _methodsignature Signature of the method that this permission controls. */ function removeUserPermission(address _who, bytes4 _methodsignature) public onlyValidator { require(permissions[_methodsignature].active, "Permission being removed must be for a valid method signature"); userPermissions[_who][_methodsignature] = false; } /** * @notice add a Validator * @param _validator Address of validator to add */ function addValidator(address _validator) public onlyOwner { validators[_validator] = true; emit ValidatorAdded(_validator); } /** * @notice remove a Validator * @param _validator Address of validator to remove */ function removeValidator(address _validator) public onlyOwner { validators[_validator] = false; emit ValidatorRemoved(_validator); } /** * @notice does validator exist? * @return true if yes, false if no **/ function isValidator(address _validator) public view returns (bool) { return validators[_validator]; } /** * @notice does permission exist? * @return true if yes, false if no **/ function isPermission(bytes4 _methodsignature) public view returns (bool) { return permissions[_methodsignature].active; } /** * @notice get Permission structure * @param _methodsignature request to retrieve the Permission struct for this methodsignature * @return Permission **/ function getPermission(bytes4 _methodsignature) public view returns (string name, string description, string contract_name, bool active) { return (permissions[_methodsignature].name, permissions[_methodsignature].description, permissions[_methodsignature].contract_name, permissions[_methodsignature].active); } /** * @notice does permission exist? * @return true if yes, false if no **/ function hasUserPermission(address _who, bytes4 _methodsignature) public view returns (bool) { return userPermissions[_who][_methodsignature]; } }
/** * * @dev Stores permissions and validators and provides setter and getter methods. * Permissions determine which methods users have access to call. Validators * are able to mutate permissions at the Regulator level. * */
NatSpecMultiLine
addValidator
function addValidator(address _validator) public onlyOwner { validators[_validator] = true; emit ValidatorAdded(_validator); }
/** * @notice add a Validator * @param _validator Address of validator to add */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3
{ "func_code_index": [ 4445, 4599 ] }
58,459
RegulatorProxyFactory
RegulatorProxyFactory.sol
0x8180522f083bf9a1f756745e5decff48e007d370
Solidity
RegulatorStorage
contract RegulatorStorage is Ownable { /** Structs */ /* Contains metadata about a permission to execute a particular method signature. */ struct Permission { string name; // A one-word description for the permission. e.g. "canMint" string description; // A longer description for the permission. e.g. "Allows user to mint tokens." string contract_name; // e.g. "PermissionedToken" bool active; // Permissions can be turned on or off by regulator } /** Constants: stores method signatures. These are potential permissions that a user can have, and each permission gives the user the ability to call the associated PermissionedToken method signature */ bytes4 public constant MINT_SIG = bytes4(keccak256("mint(address,uint256)")); bytes4 public constant MINT_CUSD_SIG = bytes4(keccak256("mintCUSD(address,uint256)")); bytes4 public constant DESTROY_BLACKLISTED_TOKENS_SIG = bytes4(keccak256("destroyBlacklistedTokens(address,uint256)")); bytes4 public constant APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG = bytes4(keccak256("approveBlacklistedAddressSpender(address)")); bytes4 public constant BLACKLISTED_SIG = bytes4(keccak256("blacklisted()")); /** Mappings */ /* each method signature maps to a Permission */ mapping (bytes4 => Permission) public permissions; /* list of validators, either active or inactive */ mapping (address => bool) public validators; /* each user can be given access to a given method signature */ mapping (address => mapping (bytes4 => bool)) public userPermissions; /** Events */ event PermissionAdded(bytes4 methodsignature); event PermissionRemoved(bytes4 methodsignature); event ValidatorAdded(address indexed validator); event ValidatorRemoved(address indexed validator); /** Modifiers */ /** * @notice Throws if called by any account that does not have access to set attributes */ modifier onlyValidator() { require (isValidator(msg.sender), "Sender must be validator"); _; } /** * @notice Sets a permission within the list of permissions. * @param _methodsignature Signature of the method that this permission controls. * @param _permissionName A "slug" name for this permission (e.g. "canMint"). * @param _permissionDescription A lengthier description for this permission (e.g. "Allows user to mint tokens"). * @param _contractName Name of the contract that the method belongs to. */ function addPermission( bytes4 _methodsignature, string _permissionName, string _permissionDescription, string _contractName) public onlyValidator { Permission memory p = Permission(_permissionName, _permissionDescription, _contractName, true); permissions[_methodsignature] = p; emit PermissionAdded(_methodsignature); } /** * @notice Removes a permission the list of permissions. * @param _methodsignature Signature of the method that this permission controls. */ function removePermission(bytes4 _methodsignature) public onlyValidator { permissions[_methodsignature].active = false; emit PermissionRemoved(_methodsignature); } /** * @notice Sets a permission in the list of permissions that a user has. * @param _methodsignature Signature of the method that this permission controls. */ function setUserPermission(address _who, bytes4 _methodsignature) public onlyValidator { require(permissions[_methodsignature].active, "Permission being set must be for a valid method signature"); userPermissions[_who][_methodsignature] = true; } /** * @notice Removes a permission from the list of permissions that a user has. * @param _methodsignature Signature of the method that this permission controls. */ function removeUserPermission(address _who, bytes4 _methodsignature) public onlyValidator { require(permissions[_methodsignature].active, "Permission being removed must be for a valid method signature"); userPermissions[_who][_methodsignature] = false; } /** * @notice add a Validator * @param _validator Address of validator to add */ function addValidator(address _validator) public onlyOwner { validators[_validator] = true; emit ValidatorAdded(_validator); } /** * @notice remove a Validator * @param _validator Address of validator to remove */ function removeValidator(address _validator) public onlyOwner { validators[_validator] = false; emit ValidatorRemoved(_validator); } /** * @notice does validator exist? * @return true if yes, false if no **/ function isValidator(address _validator) public view returns (bool) { return validators[_validator]; } /** * @notice does permission exist? * @return true if yes, false if no **/ function isPermission(bytes4 _methodsignature) public view returns (bool) { return permissions[_methodsignature].active; } /** * @notice get Permission structure * @param _methodsignature request to retrieve the Permission struct for this methodsignature * @return Permission **/ function getPermission(bytes4 _methodsignature) public view returns (string name, string description, string contract_name, bool active) { return (permissions[_methodsignature].name, permissions[_methodsignature].description, permissions[_methodsignature].contract_name, permissions[_methodsignature].active); } /** * @notice does permission exist? * @return true if yes, false if no **/ function hasUserPermission(address _who, bytes4 _methodsignature) public view returns (bool) { return userPermissions[_who][_methodsignature]; } }
/** * * @dev Stores permissions and validators and provides setter and getter methods. * Permissions determine which methods users have access to call. Validators * are able to mutate permissions at the Regulator level. * */
NatSpecMultiLine
removeValidator
function removeValidator(address _validator) public onlyOwner { validators[_validator] = false; emit ValidatorRemoved(_validator); }
/** * @notice remove a Validator * @param _validator Address of validator to remove */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3
{ "func_code_index": [ 4709, 4869 ] }
58,460