github.com/diadata-org/diadata@v1.4.593/config/nftContracts/sorare/sorare.sol (about) 1 /** 2 *Submitted for verification at Etherscan.io on 2020-05-14 3 */ 4 5 pragma solidity 0.6.6; 6 7 8 contract Context { 9 // Empty internal constructor, to prevent people from mistakenly deploying 10 // an instance of this contract, which should be used via inheritance. 11 constructor () internal { } 12 13 function _msgSender() internal view virtual returns (address payable) { 14 return msg.sender; 15 } 16 17 function _msgData() internal view virtual returns (bytes memory) { 18 this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 19 return msg.data; 20 } 21 } 22 23 interface IERC165 { 24 /** 25 * @dev Returns true if this contract implements the interface defined by 26 * `interfaceId`. See the corresponding 27 * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] 28 * to learn more about how these ids are created. 29 * 30 * This function call must use less than 30 000 gas. 31 */ 32 function supportsInterface(bytes4 interfaceId) external view returns (bool); 33 } 34 35 interface IERC721 is IERC165 { 36 event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); 37 event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); 38 event ApprovalForAll(address indexed owner, address indexed operator, bool approved); 39 40 /** 41 * @dev Returns the number of NFTs in ``owner``'s account. 42 */ 43 function balanceOf(address owner) external view returns (uint256 balance); 44 45 /** 46 * @dev Returns the owner of the NFT specified by `tokenId`. 47 */ 48 function ownerOf(uint256 tokenId) external view returns (address owner); 49 50 /** 51 * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to 52 * another (`to`). 53 * 54 * 55 * 56 * Requirements: 57 * - `from`, `to` cannot be zero. 58 * - `tokenId` must be owned by `from`. 59 * - If the caller is not `from`, it must be have been allowed to move this 60 * NFT by either {approve} or {setApprovalForAll}. 61 */ 62 function safeTransferFrom(address from, address to, uint256 tokenId) external; 63 /** 64 * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to 65 * another (`to`). 66 * 67 * Requirements: 68 * - If the caller is not `from`, it must be approved to move this NFT by 69 * either {approve} or {setApprovalForAll}. 70 */ 71 function transferFrom(address from, address to, uint256 tokenId) external; 72 function approve(address to, uint256 tokenId) external; 73 function getApproved(uint256 tokenId) external view returns (address operator); 74 75 function setApprovalForAll(address operator, bool _approved) external; 76 function isApprovedForAll(address owner, address operator) external view returns (bool); 77 78 79 function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; 80 } 81 82 interface IERC721Metadata is IERC721 { 83 function name() external view returns (string memory); 84 function symbol() external view returns (string memory); 85 function tokenURI(uint256 tokenId) external view returns (string memory); 86 } 87 88 interface IERC721Enumerable is IERC721 { 89 function totalSupply() external view returns (uint256); 90 function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); 91 92 function tokenByIndex(uint256 index) external view returns (uint256); 93 } 94 95 contract ERC165 is IERC165 { 96 /* 97 * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 98 */ 99 bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; 100 101 /** 102 * @dev Mapping of interface ids to whether or not it's supported. 103 */ 104 mapping(bytes4 => bool) private _supportedInterfaces; 105 106 constructor () internal { 107 // Derived contracts need only register support for their own interfaces, 108 // we register support for ERC165 itself here 109 _registerInterface(_INTERFACE_ID_ERC165); 110 } 111 112 /** 113 * @dev See {IERC165-supportsInterface}. 114 * 115 * Time complexity O(1), guaranteed to always use less than 30 000 gas. 116 */ 117 function supportsInterface(bytes4 interfaceId) public view override returns (bool) { 118 return _supportedInterfaces[interfaceId]; 119 } 120 121 /** 122 * @dev Registers the contract as an implementer of the interface defined by 123 * `interfaceId`. Support of the actual ERC165 interface is automatic and 124 * registering its interface id is not required. 125 * 126 * See {IERC165-supportsInterface}. 127 * 128 * Requirements: 129 * 130 * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). 131 */ 132 function _registerInterface(bytes4 interfaceId) internal virtual { 133 require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); 134 _supportedInterfaces[interfaceId] = true; 135 } 136 } 137 138 library SafeMath { 139 /** 140 * @dev Returns the addition of two unsigned integers, reverting on 141 * overflow. 142 * 143 * Counterpart to Solidity's `+` operator. 144 * 145 * Requirements: 146 * - Addition cannot overflow. 147 */ 148 function add(uint256 a, uint256 b) internal pure returns (uint256) { 149 uint256 c = a + b; 150 require(c >= a, "SafeMath: addition overflow"); 151 152 return c; 153 } 154 155 /** 156 * @dev Returns the subtraction of two unsigned integers, reverting on 157 * overflow (when the result is negative). 158 * 159 * Counterpart to Solidity's `-` operator. 160 * 161 * Requirements: 162 * - Subtraction cannot overflow. 163 */ 164 function sub(uint256 a, uint256 b) internal pure returns (uint256) { 165 return sub(a, b, "SafeMath: subtraction overflow"); 166 } 167 168 /** 169 * @dev Returns the subtraction of two unsigned integers, reverting with custom message on 170 * overflow (when the result is negative). 171 * 172 * Counterpart to Solidity's `-` operator. 173 * 174 * Requirements: 175 * - Subtraction cannot overflow. 176 */ 177 function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 178 require(b <= a, errorMessage); 179 uint256 c = a - b; 180 181 return c; 182 } 183 184 /** 185 * @dev Returns the multiplication of two unsigned integers, reverting on 186 * overflow. 187 * 188 * Counterpart to Solidity's `*` operator. 189 * 190 * Requirements: 191 * - Multiplication cannot overflow. 192 */ 193 function mul(uint256 a, uint256 b) internal pure returns (uint256) { 194 // Gas optimization: this is cheaper than requiring 'a' not being zero, but the 195 // benefit is lost if 'b' is also tested. 196 // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 197 if (a == 0) { 198 return 0; 199 } 200 201 uint256 c = a * b; 202 require(c / a == b, "SafeMath: multiplication overflow"); 203 204 return c; 205 } 206 207 /** 208 * @dev Returns the integer division of two unsigned integers. Reverts on 209 * division by zero. The result is rounded towards zero. 210 * 211 * Counterpart to Solidity's `/` operator. Note: this function uses a 212 * `revert` opcode (which leaves remaining gas untouched) while Solidity 213 * uses an invalid opcode to revert (consuming all remaining gas). 214 * 215 * Requirements: 216 * - The divisor cannot be zero. 217 */ 218 function div(uint256 a, uint256 b) internal pure returns (uint256) { 219 return div(a, b, "SafeMath: division by zero"); 220 } 221 222 /** 223 * @dev Returns the integer division of two unsigned integers. Reverts with custom message on 224 * division by zero. The result is rounded towards zero. 225 * 226 * Counterpart to Solidity's `/` operator. Note: this function uses a 227 * `revert` opcode (which leaves remaining gas untouched) while Solidity 228 * uses an invalid opcode to revert (consuming all remaining gas). 229 * 230 * Requirements: 231 * - The divisor cannot be zero. 232 */ 233 function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 234 // Solidity only automatically asserts when dividing by 0 235 require(b > 0, errorMessage); 236 uint256 c = a / b; 237 // assert(a == b * c + a % b); // There is no case in which this doesn't hold 238 239 return c; 240 } 241 242 /** 243 * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), 244 * Reverts when dividing by zero. 245 * 246 * Counterpart to Solidity's `%` operator. This function uses a `revert` 247 * opcode (which leaves remaining gas untouched) while Solidity uses an 248 * invalid opcode to revert (consuming all remaining gas). 249 * 250 * Requirements: 251 * - The divisor cannot be zero. 252 */ 253 function mod(uint256 a, uint256 b) internal pure returns (uint256) { 254 return mod(a, b, "SafeMath: modulo by zero"); 255 } 256 257 /** 258 * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), 259 * Reverts with custom message when dividing by zero. 260 * 261 * Counterpart to Solidity's `%` operator. This function uses a `revert` 262 * opcode (which leaves remaining gas untouched) while Solidity uses an 263 * invalid opcode to revert (consuming all remaining gas). 264 * 265 * Requirements: 266 * - The divisor cannot be zero. 267 */ 268 function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 269 require(b != 0, errorMessage); 270 return a % b; 271 } 272 } 273 274 library EnumerableSet { 275 // To implement this library for multiple types with as little code 276 // repetition as possible, we write it in terms of a generic Set type with 277 // bytes32 values. 278 // The Set implementation uses private functions, and user-facing 279 // implementations (such as AddressSet) are just wrappers around the 280 // underlying Set. 281 // This means that we can only create new EnumerableSets for types that fit 282 // in bytes32. 283 284 struct Set { 285 // Storage of set values 286 bytes32[] _values; 287 288 // Position of the value in the `values` array, plus 1 because index 0 289 // means a value is not in the set. 290 mapping (bytes32 => uint256) _indexes; 291 } 292 293 /** 294 * @dev Add a value to a set. O(1). 295 * 296 * Returns true if the value was added to the set, that is if it was not 297 * already present. 298 */ 299 function _add(Set storage set, bytes32 value) private returns (bool) { 300 if (!_contains(set, value)) { 301 set._values.push(value); 302 // The value is stored at length-1, but we add 1 to all indexes 303 // and use 0 as a sentinel value 304 set._indexes[value] = set._values.length; 305 return true; 306 } else { 307 return false; 308 } 309 } 310 311 /** 312 * @dev Removes a value from a set. O(1). 313 * 314 * Returns true if the value was removed from the set, that is if it was 315 * present. 316 */ 317 function _remove(Set storage set, bytes32 value) private returns (bool) { 318 // We read and store the value's index to prevent multiple reads from the same storage slot 319 uint256 valueIndex = set._indexes[value]; 320 321 if (valueIndex != 0) { // Equivalent to contains(set, value) 322 // To delete an element from the _values array in O(1), we swap the element to delete with the last one in 323 // the array, and then remove the last element (sometimes called as 'swap and pop'). 324 // This modifies the order of the array, as noted in {at}. 325 326 uint256 toDeleteIndex = valueIndex - 1; 327 uint256 lastIndex = set._values.length - 1; 328 329 // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs 330 // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. 331 332 bytes32 lastvalue = set._values[lastIndex]; 333 334 // Move the last value to the index where the value to delete is 335 set._values[toDeleteIndex] = lastvalue; 336 // Update the index for the moved value 337 set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based 338 339 // Delete the slot where the moved value was stored 340 set._values.pop(); 341 342 // Delete the index for the deleted slot 343 delete set._indexes[value]; 344 345 return true; 346 } else { 347 return false; 348 } 349 } 350 351 /** 352 * @dev Returns true if the value is in the set. O(1). 353 */ 354 function _contains(Set storage set, bytes32 value) private view returns (bool) { 355 return set._indexes[value] != 0; 356 } 357 358 /** 359 * @dev Returns the number of values on the set. O(1). 360 */ 361 function _length(Set storage set) private view returns (uint256) { 362 return set._values.length; 363 } 364 365 /** 366 * @dev Returns the value stored at position `index` in the set. O(1). 367 * 368 * Note that there are no guarantees on the ordering of values inside the 369 * array, and it may change when more values are added or removed. 370 * 371 * Requirements: 372 * 373 * - `index` must be strictly less than {length}. 374 */ 375 function _at(Set storage set, uint256 index) private view returns (bytes32) { 376 require(set._values.length > index, "EnumerableSet: index out of bounds"); 377 return set._values[index]; 378 } 379 380 // AddressSet 381 382 struct AddressSet { 383 Set _inner; 384 } 385 386 /** 387 * @dev Add a value to a set. O(1). 388 * 389 * Returns true if the value was added to the set, that is if it was not 390 * already present. 391 */ 392 function add(AddressSet storage set, address value) internal returns (bool) { 393 return _add(set._inner, bytes32(uint256(value))); 394 } 395 396 /** 397 * @dev Removes a value from a set. O(1). 398 * 399 * Returns true if the value was removed from the set, that is if it was 400 * present. 401 */ 402 function remove(AddressSet storage set, address value) internal returns (bool) { 403 return _remove(set._inner, bytes32(uint256(value))); 404 } 405 406 /** 407 * @dev Returns true if the value is in the set. O(1). 408 */ 409 function contains(AddressSet storage set, address value) internal view returns (bool) { 410 return _contains(set._inner, bytes32(uint256(value))); 411 } 412 413 /** 414 * @dev Returns the number of values in the set. O(1). 415 */ 416 function length(AddressSet storage set) internal view returns (uint256) { 417 return _length(set._inner); 418 } 419 420 /** 421 * @dev Returns the value stored at position `index` in the set. O(1). 422 * 423 * Note that there are no guarantees on the ordering of values inside the 424 * array, and it may change when more values are added or removed. 425 * 426 * Requirements: 427 * 428 * - `index` must be strictly less than {length}. 429 */ 430 function at(AddressSet storage set, uint256 index) internal view returns (address) { 431 return address(uint256(_at(set._inner, index))); 432 } 433 434 435 // UintSet 436 437 struct UintSet { 438 Set _inner; 439 } 440 441 /** 442 * @dev Add a value to a set. O(1). 443 * 444 * Returns true if the value was added to the set, that is if it was not 445 * already present. 446 */ 447 function add(UintSet storage set, uint256 value) internal returns (bool) { 448 return _add(set._inner, bytes32(value)); 449 } 450 451 /** 452 * @dev Removes a value from a set. O(1). 453 * 454 * Returns true if the value was removed from the set, that is if it was 455 * present. 456 */ 457 function remove(UintSet storage set, uint256 value) internal returns (bool) { 458 return _remove(set._inner, bytes32(value)); 459 } 460 461 /** 462 * @dev Returns true if the value is in the set. O(1). 463 */ 464 function contains(UintSet storage set, uint256 value) internal view returns (bool) { 465 return _contains(set._inner, bytes32(value)); 466 } 467 468 /** 469 * @dev Returns the number of values on the set. O(1). 470 */ 471 function length(UintSet storage set) internal view returns (uint256) { 472 return _length(set._inner); 473 } 474 475 /** 476 * @dev Returns the value stored at position `index` in the set. O(1). 477 * 478 * Note that there are no guarantees on the ordering of values inside the 479 * array, and it may change when more values are added or removed. 480 * 481 * Requirements: 482 * 483 * - `index` must be strictly less than {length}. 484 */ 485 function at(UintSet storage set, uint256 index) internal view returns (uint256) { 486 return uint256(_at(set._inner, index)); 487 } 488 } 489 490 library EnumerableMap { 491 // To implement this library for multiple types with as little code 492 // repetition as possible, we write it in terms of a generic Map type with 493 // bytes32 keys and values. 494 // The Map implementation uses private functions, and user-facing 495 // implementations (such as Uint256ToAddressMap) are just wrappers around 496 // the underlying Map. 497 // This means that we can only create new EnumerableMaps for types that fit 498 // in bytes32. 499 500 struct MapEntry { 501 bytes32 _key; 502 bytes32 _value; 503 } 504 505 struct Map { 506 // Storage of map keys and values 507 MapEntry[] _entries; 508 509 // Position of the entry defined by a key in the `entries` array, plus 1 510 // because index 0 means a key is not in the map. 511 mapping (bytes32 => uint256) _indexes; 512 } 513 514 /** 515 * @dev Adds a key-value pair to a map, or updates the value for an existing 516 * key. O(1). 517 * 518 * Returns true if the key was added to the map, that is if it was not 519 * already present. 520 */ 521 function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { 522 // We read and store the key's index to prevent multiple reads from the same storage slot 523 uint256 keyIndex = map._indexes[key]; 524 525 if (keyIndex == 0) { // Equivalent to !contains(map, key) 526 map._entries.push(MapEntry({ _key: key, _value: value })); 527 // The entry is stored at length-1, but we add 1 to all indexes 528 // and use 0 as a sentinel value 529 map._indexes[key] = map._entries.length; 530 return true; 531 } else { 532 map._entries[keyIndex - 1]._value = value; 533 return false; 534 } 535 } 536 537 /** 538 * @dev Removes a key-value pair from a map. O(1). 539 * 540 * Returns true if the key was removed from the map, that is if it was present. 541 */ 542 function _remove(Map storage map, bytes32 key) private returns (bool) { 543 // We read and store the key's index to prevent multiple reads from the same storage slot 544 uint256 keyIndex = map._indexes[key]; 545 546 if (keyIndex != 0) { // Equivalent to contains(map, key) 547 // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one 548 // in the array, and then remove the last entry (sometimes called as 'swap and pop'). 549 // This modifies the order of the array, as noted in {at}. 550 551 uint256 toDeleteIndex = keyIndex - 1; 552 uint256 lastIndex = map._entries.length - 1; 553 554 // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs 555 // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. 556 557 MapEntry storage lastEntry = map._entries[lastIndex]; 558 559 // Move the last entry to the index where the entry to delete is 560 map._entries[toDeleteIndex] = lastEntry; 561 // Update the index for the moved entry 562 map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based 563 564 // Delete the slot where the moved entry was stored 565 map._entries.pop(); 566 567 // Delete the index for the deleted slot 568 delete map._indexes[key]; 569 570 return true; 571 } else { 572 return false; 573 } 574 } 575 576 /** 577 * @dev Returns true if the key is in the map. O(1). 578 */ 579 function _contains(Map storage map, bytes32 key) private view returns (bool) { 580 return map._indexes[key] != 0; 581 } 582 583 /** 584 * @dev Returns the number of key-value pairs in the map. O(1). 585 */ 586 function _length(Map storage map) private view returns (uint256) { 587 return map._entries.length; 588 } 589 590 /** 591 * @dev Returns the key-value pair stored at position `index` in the map. O(1). 592 * 593 * Note that there are no guarantees on the ordering of entries inside the 594 * array, and it may change when more entries are added or removed. 595 * 596 * Requirements: 597 * 598 * - `index` must be strictly less than {length}. 599 */ 600 function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { 601 require(map._entries.length > index, "EnumerableMap: index out of bounds"); 602 603 MapEntry storage entry = map._entries[index]; 604 return (entry._key, entry._value); 605 } 606 607 /** 608 * @dev Returns the value associated with `key`. O(1). 609 * 610 * Requirements: 611 * 612 * - `key` must be in the map. 613 */ 614 function _get(Map storage map, bytes32 key) private view returns (bytes32) { 615 return _get(map, key, "EnumerableMap: nonexistent key"); 616 } 617 618 /** 619 * @dev Same as {_get}, with a custom error message when `key` is not in the map. 620 */ 621 function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { 622 uint256 keyIndex = map._indexes[key]; 623 require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) 624 return map._entries[keyIndex - 1]._value; // All indexes are 1-based 625 } 626 627 // UintToAddressMap 628 629 struct UintToAddressMap { 630 Map _inner; 631 } 632 633 /** 634 * @dev Adds a key-value pair to a map, or updates the value for an existing 635 * key. O(1). 636 * 637 * Returns true if the key was added to the map, that is if it was not 638 * already present. 639 */ 640 function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { 641 return _set(map._inner, bytes32(key), bytes32(uint256(value))); 642 } 643 644 /** 645 * @dev Removes a value from a set. O(1). 646 * 647 * Returns true if the key was removed from the map, that is if it was present. 648 */ 649 function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { 650 return _remove(map._inner, bytes32(key)); 651 } 652 653 /** 654 * @dev Returns true if the key is in the map. O(1). 655 */ 656 function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { 657 return _contains(map._inner, bytes32(key)); 658 } 659 660 /** 661 * @dev Returns the number of elements in the map. O(1). 662 */ 663 function length(UintToAddressMap storage map) internal view returns (uint256) { 664 return _length(map._inner); 665 } 666 667 /** 668 * @dev Returns the element stored at position `index` in the set. O(1). 669 * Note that there are no guarantees on the ordering of values inside the 670 * array, and it may change when more values are added or removed. 671 * 672 * Requirements: 673 * 674 * - `index` must be strictly less than {length}. 675 */ 676 function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { 677 (bytes32 key, bytes32 value) = _at(map._inner, index); 678 return (uint256(key), address(uint256(value))); 679 } 680 681 /** 682 * @dev Returns the value associated with `key`. O(1). 683 * 684 * Requirements: 685 * 686 * - `key` must be in the map. 687 */ 688 function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { 689 return address(uint256(_get(map._inner, bytes32(key)))); 690 } 691 692 /** 693 * @dev Same as {get}, with a custom error message when `key` is not in the map. 694 */ 695 function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { 696 return address(uint256(_get(map._inner, bytes32(key), errorMessage))); 697 } 698 } 699 700 library Strings { 701 /** 702 * @dev Converts a `uint256` to its ASCII `string` representation. 703 */ 704 function toString(uint256 value) internal pure returns (string memory) { 705 // Inspired by OraclizeAPI's implementation - MIT licence 706 // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol 707 708 if (value == 0) { 709 return "0"; 710 } 711 uint256 temp = value; 712 uint256 digits; 713 while (temp != 0) { 714 digits++; 715 temp /= 10; 716 } 717 bytes memory buffer = new bytes(digits); 718 uint256 index = digits - 1; 719 temp = value; 720 while (temp != 0) { 721 buffer[index--] = byte(uint8(48 + temp % 10)); 722 temp /= 10; 723 } 724 return string(buffer); 725 } 726 } 727 728 /** 729 * @dev Collection of functions related to the address type 730 */ 731 library Address { 732 /** 733 * @dev Returns true if `account` is a contract. 734 * 735 * [IMPORTANT] 736 * ==== 737 * It is unsafe to assume that an address for which this function returns 738 * false is an externally-owned account (EOA) and not a contract. 739 * 740 * Among others, `isContract` will return false for the following 741 * types of addresses: 742 * 743 * - an externally-owned account 744 * - a contract in construction 745 * - an address where a contract will be created 746 * - an address where a contract lived, but was destroyed 747 * ==== 748 */ 749 function isContract(address account) internal view returns (bool) { 750 // According to EIP-1052, 0x0 is the value returned for not-yet created accounts 751 // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned 752 // for accounts without code, i.e. `keccak256('')` 753 bytes32 codehash; 754 bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; 755 // solhint-disable-next-line no-inline-assembly 756 assembly { codehash := extcodehash(account) } 757 return (codehash != accountHash && codehash != 0x0); 758 } 759 760 /** 761 * @dev Replacement for Solidity's `transfer`: sends `amount` wei to 762 * `recipient`, forwarding all available gas and reverting on errors. 763 * 764 * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost 765 * of certain opcodes, possibly making contracts go over the 2300 gas limit 766 * imposed by `transfer`, making them unable to receive funds via 767 * `transfer`. {sendValue} removes this limitation. 768 * 769 * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. 770 * 771 * IMPORTANT: because control is transferred to `recipient`, care must be 772 * taken to not create reentrancy vulnerabilities. Consider using 773 * {ReentrancyGuard} or the 774 * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. 775 */ 776 function sendValue(address payable recipient, uint256 amount) internal { 777 require(address(this).balance >= amount, "Address: insufficient balance"); 778 779 // solhint-disable-next-line avoid-low-level-calls, avoid-call-value 780 (bool success, ) = recipient.call{ value: amount }(""); 781 require(success, "Address: unable to send value, recipient may have reverted"); 782 } 783 } 784 785 /** 786 * @dev Contract module that allows children to implement role-based access 787 * control mechanisms. 788 * 789 * Roles are referred to by their `bytes32` identifier. These should be exposed 790 * in the external API and be unique. The best way to achieve this is by 791 * using `public constant` hash digests: 792 * 793 * ``` 794 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); 795 * ``` 796 * 797 * Roles can be used to represent a set of permissions. To restrict access to a 798 * function call, use {hasRole}: 799 * 800 * ``` 801 * function foo() public { 802 * require(hasRole(MY_ROLE, _msgSender())); 803 * ... 804 * } 805 * ``` 806 * 807 * Roles can be granted and revoked dynamically via the {grantRole} and 808 * {revokeRole} functions. Each role has an associated admin role, and only 809 * accounts that have a role's admin role can call {grantRole} and {revokeRole}. 810 * 811 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means 812 * that only accounts with this role will be able to grant or revoke other 813 * roles. More complex role relationships can be created by using 814 * {_setRoleAdmin}. 815 */ 816 abstract contract AccessControl is Context { 817 using EnumerableSet for EnumerableSet.AddressSet; 818 using Address for address; 819 820 struct RoleData { 821 EnumerableSet.AddressSet members; 822 bytes32 adminRole; 823 } 824 825 mapping (bytes32 => RoleData) private _roles; 826 827 bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; 828 829 /** 830 * @dev Emitted when `account` is granted `role`. 831 * 832 * `sender` is the account that originated the contract call, an admin role 833 * bearer except when using {_setupRole}. 834 */ 835 event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); 836 837 /** 838 * @dev Emitted when `account` is revoked `role`. 839 * 840 * `sender` is the account that originated the contract call: 841 * - if using `revokeRole`, it is the admin role bearer 842 * - if using `renounceRole`, it is the role bearer (i.e. `account`) 843 */ 844 event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); 845 846 /** 847 * @dev Returns `true` if `account` has been granted `role`. 848 */ 849 function hasRole(bytes32 role, address account) public view returns (bool) { 850 return _roles[role].members.contains(account); 851 } 852 853 /** 854 * @dev Returns the number of accounts that have `role`. Can be used 855 * together with {getRoleMember} to enumerate all bearers of a role. 856 */ 857 function getRoleMemberCount(bytes32 role) public view returns (uint256) { 858 return _roles[role].members.length(); 859 } 860 861 /** 862 * @dev Returns one of the accounts that have `role`. `index` must be a 863 * value between 0 and {getRoleMemberCount}, non-inclusive. 864 * 865 * Role bearers are not sorted in any particular way, and their ordering may 866 * change at any point. 867 * 868 * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure 869 * you perform all queries on the same block. See the following 870 * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] 871 * for more information. 872 */ 873 function getRoleMember(bytes32 role, uint256 index) public view returns (address) { 874 return _roles[role].members.at(index); 875 } 876 877 /** 878 * @dev Returns the admin role that controls `role`. See {grantRole} and 879 * {revokeRole}. 880 * 881 * To change a role's admin, use {_setRoleAdmin}. 882 */ 883 function getRoleAdmin(bytes32 role) public view returns (bytes32) { 884 return _roles[role].adminRole; 885 } 886 887 /** 888 * @dev Grants `role` to `account`. 889 * 890 * If `account` had not been already granted `role`, emits a {RoleGranted} 891 * event. 892 * 893 * Requirements: 894 * 895 * - the caller must have ``role``'s admin role. 896 */ 897 function grantRole(bytes32 role, address account) public virtual { 898 require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); 899 900 _grantRole(role, account); 901 } 902 903 /** 904 * @dev Revokes `role` from `account`. 905 * 906 * If `account` had been granted `role`, emits a {RoleRevoked} event. 907 * 908 * Requirements: 909 * 910 * - the caller must have ``role``'s admin role. 911 */ 912 function revokeRole(bytes32 role, address account) public virtual { 913 require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); 914 915 _revokeRole(role, account); 916 } 917 918 /** 919 * @dev Revokes `role` from the calling account. 920 * 921 * Roles are often managed via {grantRole} and {revokeRole}: this function's 922 * purpose is to provide a mechanism for accounts to lose their privileges 923 * if they are compromised (such as when a trusted device is misplaced). 924 * 925 * If the calling account had been granted `role`, emits a {RoleRevoked} 926 * event. 927 * 928 * Requirements: 929 * 930 * - the caller must be `account`. 931 */ 932 function renounceRole(bytes32 role, address account) public virtual { 933 require(account == _msgSender(), "AccessControl: can only renounce roles for self"); 934 935 _revokeRole(role, account); 936 } 937 938 /** 939 * @dev Grants `role` to `account`. 940 * 941 * If `account` had not been already granted `role`, emits a {RoleGranted} 942 * event. Note that unlike {grantRole}, this function doesn't perform any 943 * checks on the calling account. 944 * 945 * [WARNING] 946 * ==== 947 * This function should only be called from the constructor when setting 948 * up the initial roles for the system. 949 * 950 * Using this function in any other way is effectively circumventing the admin 951 * system imposed by {AccessControl}. 952 * ==== 953 */ 954 function _setupRole(bytes32 role, address account) internal virtual { 955 _grantRole(role, account); 956 } 957 958 /** 959 * @dev Sets `adminRole` as ``role``'s admin role. 960 */ 961 function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { 962 _roles[role].adminRole = adminRole; 963 } 964 965 function _grantRole(bytes32 role, address account) private { 966 if (_roles[role].members.add(account)) { 967 emit RoleGranted(role, account, _msgSender()); 968 } 969 } 970 971 function _revokeRole(bytes32 role, address account) private { 972 if (_roles[role].members.remove(account)) { 973 emit RoleRevoked(role, account, _msgSender()); 974 } 975 } 976 } 977 978 /** 979 * @title ERC721 token receiver interface 980 * @dev Interface for any contract that wants to support safeTransfers 981 * from ERC721 asset contracts. 982 */ 983 abstract contract IERC721Receiver { 984 /** 985 * @notice Handle the receipt of an NFT 986 * @dev The ERC721 smart contract calls this function on the recipient 987 * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, 988 * otherwise the caller will revert the transaction. The selector to be 989 * returned can be obtained as `this.onERC721Received.selector`. This 990 * function MAY throw to revert and reject the transfer. 991 * Note: the ERC721 contract address is always the message sender. 992 * @param operator The address which called `safeTransferFrom` function 993 * @param from The address which previously owned the token 994 * @param tokenId The NFT identifier which is being transferred 995 * @param data Additional data with no specified format 996 * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` 997 */ 998 function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) 999 public virtual returns (bytes4); 1000 } 1001 1002 contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 1003 using SafeMath for uint256; 1004 using Address for address; 1005 using EnumerableSet for EnumerableSet.UintSet; 1006 using EnumerableMap for EnumerableMap.UintToAddressMap; 1007 using Strings for uint256; 1008 1009 // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` 1010 // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` 1011 bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; 1012 1013 // Mapping from holder address to their (enumerable) set of owned tokens 1014 mapping (address => EnumerableSet.UintSet) private _holderTokens; 1015 1016 // Enumerable mapping from token ids to their owners 1017 EnumerableMap.UintToAddressMap private _tokenOwners; 1018 1019 // Mapping from token ID to approved address 1020 mapping (uint256 => address) private _tokenApprovals; 1021 1022 // Mapping from owner to operator approvals 1023 mapping (address => mapping (address => bool)) private _operatorApprovals; 1024 1025 // Token name 1026 string private _name; 1027 1028 // Token symbol 1029 string private _symbol; 1030 1031 // Optional mapping for token URIs 1032 mapping(uint256 => string) private _tokenURIs; 1033 1034 // Base URI 1035 string private _baseURI; 1036 1037 /* 1038 * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 1039 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e 1040 * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 1041 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc 1042 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 1043 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 1044 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd 1045 * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e 1046 * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde 1047 * 1048 * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ 1049 * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd 1050 */ 1051 bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; 1052 1053 /* 1054 * bytes4(keccak256('name()')) == 0x06fdde03 1055 * bytes4(keccak256('symbol()')) == 0x95d89b41 1056 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd 1057 * 1058 * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f 1059 */ 1060 bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; 1061 1062 /* 1063 * bytes4(keccak256('totalSupply()')) == 0x18160ddd 1064 * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 1065 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 1066 * 1067 * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 1068 */ 1069 bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; 1070 1071 constructor (string memory name, string memory symbol) public { 1072 _name = name; 1073 _symbol = symbol; 1074 1075 // register the supported interfaces to conform to ERC721 via ERC165 1076 _registerInterface(_INTERFACE_ID_ERC721); 1077 _registerInterface(_INTERFACE_ID_ERC721_METADATA); 1078 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); 1079 } 1080 1081 /** 1082 * @dev Gets the balance of the specified address. 1083 * @param owner address to query the balance of 1084 * @return uint256 representing the amount owned by the passed address 1085 */ 1086 function balanceOf(address owner) public view override returns (uint256) { 1087 require(owner != address(0), "ERC721: balance query for the zero address"); 1088 1089 return _holderTokens[owner].length(); 1090 } 1091 1092 /** 1093 * @dev Gets the owner of the specified token ID. 1094 * @param tokenId uint256 ID of the token to query the owner of 1095 * @return address currently marked as the owner of the given token ID 1096 */ 1097 function ownerOf(uint256 tokenId) public view override returns (address) { 1098 return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); 1099 } 1100 1101 /** 1102 * @dev Gets the token name. 1103 * @return string representing the token name 1104 */ 1105 function name() public view override returns (string memory) { 1106 return _name; 1107 } 1108 1109 /** 1110 * @dev Gets the token symbol. 1111 * @return string representing the token symbol 1112 */ 1113 function symbol() public view override returns (string memory) { 1114 return _symbol; 1115 } 1116 1117 /** 1118 * @dev Returns the URI for a given token ID. May return an empty string. 1119 * 1120 * If a base URI is set (via {_setBaseURI}), it is added as a prefix to the 1121 * token's own URI (via {_setTokenURI}). 1122 * 1123 * If there is a base URI but no token URI, the token's ID will be used as 1124 * its URI when appending it to the base URI. This pattern for autogenerated 1125 * token URIs can lead to large gas savings. 1126 * 1127 * .Examples 1128 * |=== 1129 * |`_setBaseURI()` |`_setTokenURI()` |`tokenURI()` 1130 * | "" 1131 * | "" 1132 * | "" 1133 * | "" 1134 * | "token.uri/123" 1135 * | "token.uri/123" 1136 * | "token.uri/" 1137 * | "123" 1138 * | "token.uri/123" 1139 * | "token.uri/" 1140 * | "" 1141 * | "token.uri/<tokenId>" 1142 * |=== 1143 * 1144 * Requirements: 1145 * 1146 * - `tokenId` must exist. 1147 */ 1148 function tokenURI(uint256 tokenId) public view override returns (string memory) { 1149 require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); 1150 1151 string memory _tokenURI = _tokenURIs[tokenId]; 1152 1153 // If there is no base URI, return the token URI. 1154 if (bytes(_baseURI).length == 0) { 1155 return _tokenURI; 1156 } 1157 // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). 1158 if (bytes(_tokenURI).length > 0) { 1159 return string(abi.encodePacked(_baseURI, _tokenURI)); 1160 } 1161 // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. 1162 return string(abi.encodePacked(_baseURI, tokenId.toString())); 1163 } 1164 1165 /** 1166 * @dev Returns the base URI set via {_setBaseURI}. This will be 1167 * automatically added as a prefix in {tokenURI} to each token's URI, or 1168 * to the token ID if no specific URI is set for that token ID. 1169 */ 1170 function baseURI() public view returns (string memory) { 1171 return _baseURI; 1172 } 1173 1174 /** 1175 * @dev Gets the token ID at a given index of the tokens list of the requested owner. 1176 * @param owner address owning the tokens list to be accessed 1177 * @param index uint256 representing the index to be accessed of the requested tokens list 1178 * @return uint256 token ID at the given index of the tokens list owned by the requested address 1179 */ 1180 function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { 1181 return _holderTokens[owner].at(index); 1182 } 1183 1184 /** 1185 * @dev Gets the total amount of tokens stored by the contract. 1186 * @return uint256 representing the total amount of tokens 1187 */ 1188 function totalSupply() public view override returns (uint256) { 1189 // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds 1190 return _tokenOwners.length(); 1191 } 1192 1193 /** 1194 * @dev Gets the token ID at a given index of all the tokens in this contract 1195 * Reverts if the index is greater or equal to the total number of tokens. 1196 * @param index uint256 representing the index to be accessed of the tokens list 1197 * @return uint256 token ID at the given index of the tokens list 1198 */ 1199 function tokenByIndex(uint256 index) public view override returns (uint256) { 1200 (uint256 tokenId, ) = _tokenOwners.at(index); 1201 return tokenId; 1202 } 1203 1204 /** 1205 * @dev Approves another address to transfer the given token ID 1206 * The zero address indicates there is no approved address. 1207 * There can only be one approved address per token at a given time. 1208 * Can only be called by the token owner or an approved operator. 1209 * @param to address to be approved for the given token ID 1210 * @param tokenId uint256 ID of the token to be approved 1211 */ 1212 function approve(address to, uint256 tokenId) public virtual override { 1213 address owner = ownerOf(tokenId); 1214 require(to != owner, "ERC721: approval to current owner"); 1215 1216 require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), 1217 "ERC721: approve caller is not owner nor approved for all" 1218 ); 1219 1220 _approve(to, tokenId); 1221 } 1222 1223 /** 1224 * @dev Gets the approved address for a token ID, or zero if no address set 1225 * Reverts if the token ID does not exist. 1226 * @param tokenId uint256 ID of the token to query the approval of 1227 * @return address currently approved for the given token ID 1228 */ 1229 function getApproved(uint256 tokenId) public view override returns (address) { 1230 require(_exists(tokenId), "ERC721: approved query for nonexistent token"); 1231 1232 return _tokenApprovals[tokenId]; 1233 } 1234 1235 /** 1236 * @dev Sets or unsets the approval of a given operator 1237 * An operator is allowed to transfer all tokens of the sender on their behalf. 1238 * @param operator operator address to set the approval 1239 * @param approved representing the status of the approval to be set 1240 */ 1241 function setApprovalForAll(address operator, bool approved) public virtual override { 1242 require(operator != _msgSender(), "ERC721: approve to caller"); 1243 1244 _operatorApprovals[_msgSender()][operator] = approved; 1245 emit ApprovalForAll(_msgSender(), operator, approved); 1246 } 1247 1248 /** 1249 * @dev Tells whether an operator is approved by a given owner. 1250 * @param owner owner address which you want to query the approval of 1251 * @param operator operator address which you want to query the approval of 1252 * @return bool whether the given operator is approved by the given owner 1253 */ 1254 function isApprovedForAll(address owner, address operator) public view override returns (bool) { 1255 return _operatorApprovals[owner][operator]; 1256 } 1257 1258 /** 1259 * @dev Transfers the ownership of a given token ID to another address. 1260 * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. 1261 * Requires the msg.sender to be the owner, approved, or operator. 1262 * @param from current owner of the token 1263 * @param to address to receive the ownership of the given token ID 1264 * @param tokenId uint256 ID of the token to be transferred 1265 */ 1266 function transferFrom(address from, address to, uint256 tokenId) public virtual override { 1267 //solhint-disable-next-line max-line-length 1268 require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); 1269 1270 _transfer(from, to, tokenId); 1271 } 1272 1273 /** 1274 * @dev Safely transfers the ownership of a given token ID to another address 1275 * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, 1276 * which is called upon a safe transfer, and return the magic value 1277 * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, 1278 * the transfer is reverted. 1279 * Requires the msg.sender to be the owner, approved, or operator 1280 * @param from current owner of the token 1281 * @param to address to receive the ownership of the given token ID 1282 * @param tokenId uint256 ID of the token to be transferred 1283 */ 1284 function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { 1285 safeTransferFrom(from, to, tokenId, ""); 1286 } 1287 1288 /** 1289 * @dev Safely transfers the ownership of a given token ID to another address 1290 * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, 1291 * which is called upon a safe transfer, and return the magic value 1292 * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, 1293 * the transfer is reverted. 1294 * Requires the _msgSender() to be the owner, approved, or operator 1295 * @param from current owner of the token 1296 * @param to address to receive the ownership of the given token ID 1297 * @param tokenId uint256 ID of the token to be transferred 1298 * @param _data bytes data to send along with a safe transfer check 1299 */ 1300 function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { 1301 require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); 1302 _safeTransfer(from, to, tokenId, _data); 1303 } 1304 1305 /** 1306 * @dev Safely transfers the ownership of a given token ID to another address 1307 * If the target address is a contract, it must implement `onERC721Received`, 1308 * which is called upon a safe transfer, and return the magic value 1309 * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, 1310 * the transfer is reverted. 1311 * Requires the msg.sender to be the owner, approved, or operator 1312 * @param from current owner of the token 1313 * @param to address to receive the ownership of the given token ID 1314 * @param tokenId uint256 ID of the token to be transferred 1315 * @param _data bytes data to send along with a safe transfer check 1316 */ 1317 function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { 1318 _transfer(from, to, tokenId); 1319 require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); 1320 } 1321 1322 /** 1323 * @dev Returns whether the specified token exists. 1324 * @param tokenId uint256 ID of the token to query the existence of 1325 * @return bool whether the token exists 1326 */ 1327 function _exists(uint256 tokenId) internal view returns (bool) { 1328 return _tokenOwners.contains(tokenId); 1329 } 1330 1331 /** 1332 * @dev Returns whether the given spender can transfer a given token ID. 1333 * @param spender address of the spender to query 1334 * @param tokenId uint256 ID of the token to be transferred 1335 * @return bool whether the msg.sender is approved for the given token ID, 1336 * is an operator of the owner, or is the owner of the token 1337 */ 1338 function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { 1339 require(_exists(tokenId), "ERC721: operator query for nonexistent token"); 1340 address owner = ownerOf(tokenId); 1341 return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); 1342 } 1343 1344 /** 1345 * @dev Internal function to safely mint a new token. 1346 * Reverts if the given token ID already exists. 1347 * If the target address is a contract, it must implement `onERC721Received`, 1348 * which is called upon a safe transfer, and return the magic value 1349 * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, 1350 * the transfer is reverted. 1351 * @param to The address that will own the minted token 1352 * @param tokenId uint256 ID of the token to be minted 1353 */ 1354 function _safeMint(address to, uint256 tokenId) internal virtual { 1355 _safeMint(to, tokenId, ""); 1356 } 1357 1358 /** 1359 * @dev Internal function to safely mint a new token. 1360 * Reverts if the given token ID already exists. 1361 * If the target address is a contract, it must implement `onERC721Received`, 1362 * which is called upon a safe transfer, and return the magic value 1363 * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, 1364 * the transfer is reverted. 1365 * @param to The address that will own the minted token 1366 * @param tokenId uint256 ID of the token to be minted 1367 * @param _data bytes data to send along with a safe transfer check 1368 */ 1369 function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { 1370 _mint(to, tokenId); 1371 require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); 1372 } 1373 1374 /** 1375 * @dev Internal function to mint a new token. 1376 * Reverts if the given token ID already exists. 1377 * @param to The address that will own the minted token 1378 * @param tokenId uint256 ID of the token to be minted 1379 */ 1380 function _mint(address to, uint256 tokenId) internal virtual { 1381 require(to != address(0), "ERC721: mint to the zero address"); 1382 require(!_exists(tokenId), "ERC721: token already minted"); 1383 1384 _beforeTokenTransfer(address(0), to, tokenId); 1385 1386 _holderTokens[to].add(tokenId); 1387 1388 _tokenOwners.set(tokenId, to); 1389 1390 emit Transfer(address(0), to, tokenId); 1391 } 1392 1393 /** 1394 * @dev Internal function to burn a specific token. 1395 * Reverts if the token does not exist. 1396 * @param tokenId uint256 ID of the token being burned 1397 */ 1398 function _burn(uint256 tokenId) internal virtual { 1399 address owner = ownerOf(tokenId); 1400 1401 _beforeTokenTransfer(owner, address(0), tokenId); 1402 1403 // Clear approvals 1404 _approve(address(0), tokenId); 1405 1406 // Clear metadata (if any) 1407 if (bytes(_tokenURIs[tokenId]).length != 0) { 1408 delete _tokenURIs[tokenId]; 1409 } 1410 1411 _holderTokens[owner].remove(tokenId); 1412 1413 _tokenOwners.remove(tokenId); 1414 1415 emit Transfer(owner, address(0), tokenId); 1416 } 1417 1418 /** 1419 * @dev Internal function to transfer ownership of a given token ID to another address. 1420 * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. 1421 * @param from current owner of the token 1422 * @param to address to receive the ownership of the given token ID 1423 * @param tokenId uint256 ID of the token to be transferred 1424 */ 1425 function _transfer(address from, address to, uint256 tokenId) internal virtual { 1426 require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); 1427 require(to != address(0), "ERC721: transfer to the zero address"); 1428 1429 _beforeTokenTransfer(from, to, tokenId); 1430 1431 // Clear approvals from the previous owner 1432 _approve(address(0), tokenId); 1433 1434 _holderTokens[from].remove(tokenId); 1435 _holderTokens[to].add(tokenId); 1436 1437 _tokenOwners.set(tokenId, to); 1438 1439 emit Transfer(from, to, tokenId); 1440 } 1441 1442 /** 1443 * @dev Internal function to set the token URI for a given token. 1444 * 1445 * Reverts if the token ID does not exist. 1446 * 1447 * TIP: If all token IDs share a prefix (for example, if your URIs look like 1448 * `https://api.myproject.com/token/<id>`), use {_setBaseURI} to store 1449 * it and save gas. 1450 */ 1451 function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { 1452 require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); 1453 _tokenURIs[tokenId] = _tokenURI; 1454 } 1455 1456 /** 1457 * @dev Internal function to set the base URI for all token IDs. It is 1458 * automatically added as a prefix to the value returned in {tokenURI}, 1459 * or to the token ID if {tokenURI} is empty. 1460 */ 1461 function _setBaseURI(string memory baseURI_) internal virtual { 1462 _baseURI = baseURI_; 1463 } 1464 1465 /** 1466 * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. 1467 * The call is not executed if the target address is not a contract. 1468 * 1469 * @param from address representing the previous owner of the given token ID 1470 * @param to target address that will receive the tokens 1471 * @param tokenId uint256 ID of the token to be transferred 1472 * @param _data bytes optional data to send along with the call 1473 * @return bool whether the call correctly returned the expected magic value 1474 */ 1475 function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) 1476 private returns (bool) 1477 { 1478 if (!to.isContract()) { 1479 return true; 1480 } 1481 // solhint-disable-next-line avoid-low-level-calls 1482 (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector( 1483 IERC721Receiver(to).onERC721Received.selector, 1484 _msgSender(), 1485 from, 1486 tokenId, 1487 _data 1488 )); 1489 if (!success) { 1490 if (returndata.length > 0) { 1491 // solhint-disable-next-line no-inline-assembly 1492 assembly { 1493 let returndata_size := mload(returndata) 1494 revert(add(32, returndata), returndata_size) 1495 } 1496 } else { 1497 revert("ERC721: transfer to non ERC721Receiver implementer"); 1498 } 1499 } else { 1500 bytes4 retval = abi.decode(returndata, (bytes4)); 1501 return (retval == _ERC721_RECEIVED); 1502 } 1503 } 1504 1505 function _approve(address to, uint256 tokenId) private { 1506 _tokenApprovals[tokenId] = to; 1507 emit Approval(ownerOf(tokenId), to, tokenId); 1508 } 1509 1510 /** 1511 * @dev Hook that is called before any token transfer. This includes minting 1512 * and burning. 1513 * 1514 * Calling conditions: 1515 * 1516 * - when `from` and `to` are both non-zero, ``from``'s `tokenId` will be 1517 * transferred to `to`. 1518 * - when `from` is zero, `tokenId` will be minted for `to`. 1519 * - when `to` is zero, ``from``'s `tokenId` will be burned. 1520 * - `from` and `to` are never both zero. 1521 * 1522 * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. 1523 */ 1524 function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } 1525 } 1526 1527 contract Ownable is Context { 1528 address private _owner; 1529 1530 event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); 1531 1532 /** 1533 * @dev Initializes the contract setting the deployer as the initial owner. 1534 */ 1535 constructor () internal { 1536 address msgSender = _msgSender(); 1537 _owner = msgSender; 1538 emit OwnershipTransferred(address(0), msgSender); 1539 } 1540 1541 /** 1542 * @dev Returns the address of the current owner. 1543 */ 1544 function owner() public view returns (address) { 1545 return _owner; 1546 } 1547 1548 /** 1549 * @dev Throws if called by any account other than the owner. 1550 */ 1551 modifier onlyOwner() { 1552 require(_owner == _msgSender(), "Ownable: caller is not the owner"); 1553 _; 1554 } 1555 1556 /** 1557 * @dev Leaves the contract without owner. It will not be possible to call 1558 * `onlyOwner` functions anymore. Can only be called by the current owner. 1559 * 1560 * NOTE: Renouncing ownership will leave the contract without an owner, 1561 * thereby removing any functionality that is only available to the owner. 1562 */ 1563 function renounceOwnership() public virtual onlyOwner { 1564 emit OwnershipTransferred(_owner, address(0)); 1565 _owner = address(0); 1566 } 1567 1568 /** 1569 * @dev Transfers ownership of the contract to a new account (`newOwner`). 1570 * Can only be called by the current owner. 1571 */ 1572 function transferOwnership(address newOwner) public virtual onlyOwner { 1573 require(newOwner != address(0), "Ownable: new owner is the zero address"); 1574 emit OwnershipTransferred(_owner, newOwner); 1575 _owner = newOwner; 1576 } 1577 } 1578 1579 contract MinterAccess is Ownable, AccessControl { 1580 bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); 1581 1582 modifier onlyMinter { 1583 require(hasRole(MINTER_ROLE, _msgSender()), "Sender is not a minter"); 1584 _; 1585 } 1586 1587 constructor() public { 1588 _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); 1589 _setupRole(MINTER_ROLE, msg.sender); 1590 } 1591 1592 function addMinter(address account) external { 1593 grantRole(MINTER_ROLE, account); 1594 } 1595 1596 function renounceMinter(address account) external { 1597 renounceRole(MINTER_ROLE, account); 1598 } 1599 1600 function revokeMinter(address account) external { 1601 revokeRole(MINTER_ROLE, account); 1602 } 1603 } 1604 1605 interface ISorareCards { 1606 function createCard( 1607 uint256 playerId, 1608 uint16 season, 1609 uint8 scarcity, 1610 uint16 serialNumber, 1611 bytes32 metadata, 1612 uint16 clubId 1613 ) external returns (uint256); 1614 1615 function getCard(uint256 _cardId) 1616 external 1617 view 1618 returns ( 1619 uint256 playerId, 1620 uint16 season, 1621 uint256 scarcity, 1622 uint16 serialNumber, 1623 bytes memory metadata, 1624 uint16 clubId 1625 ); 1626 1627 function getPlayer(uint256 playerId) 1628 external 1629 view 1630 returns ( 1631 string memory name, 1632 uint16 yearOfBirth, 1633 uint8 monthOfBirth, 1634 uint8 dayOfBirth 1635 ); 1636 1637 function getClub(uint16 clubId) 1638 external 1639 view 1640 returns ( 1641 string memory name, 1642 string memory country, 1643 string memory city, 1644 uint16 yearFounded 1645 ); 1646 1647 function cardExists(uint256 cardId) external view returns (bool); 1648 } 1649 1650 contract RelayRecipient is Ownable { 1651 address private _relayAddress; 1652 1653 constructor(address relayAddress) public { 1654 require(relayAddress != address(0), "Custom relay address is required"); 1655 _relayAddress = relayAddress; 1656 } 1657 1658 function blockRelay() public onlyOwner { 1659 _relayAddress = address(this); 1660 } 1661 1662 function getRelayAddress() public view returns (address) { 1663 return _relayAddress; 1664 } 1665 1666 /** 1667 * @dev Replacement for msg.sender. Returns the actual sender of a transaction: msg.sender for regular transactions, 1668 * and the end-user for relayed calls (where msg.sender is actually `Relay` contract). 1669 * 1670 * IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.sender`, and use {_msgSender} instead. 1671 */ 1672 // prettier-ignore 1673 function _msgSender() internal override virtual view returns (address payable) { 1674 if (msg.sender != _relayAddress) { 1675 return msg.sender; 1676 } else { 1677 return _getRelayedCallSender(); 1678 } 1679 } 1680 1681 /** 1682 * @dev Replacement for msg.data. Returns the actual calldata of a transaction: msg.data for regular transactions, 1683 * and a reduced version for relayed calls (where msg.data contains additional information). 1684 * 1685 * IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.data`, and use {_msgData} instead. 1686 */ 1687 // prettier-ignore 1688 function _msgData() internal override virtual view returns (bytes memory) { 1689 if (msg.sender != _relayAddress) { 1690 return msg.data; 1691 } else { 1692 return _getRelayedCallData(); 1693 } 1694 } 1695 1696 function _getRelayedCallSender() 1697 private 1698 pure 1699 returns (address payable result) 1700 { 1701 // We need to read 20 bytes (an address) located at array index msg.data.length - 20. In memory, the array 1702 // is prefixed with a 32-byte length value, so we first add 32 to get the memory read index. However, doing 1703 // so would leave the address in the upper 20 bytes of the 32-byte word, which is inconvenient and would 1704 // require bit shifting. We therefore subtract 12 from the read index so the address lands on the lower 20 1705 // bytes. This can always be done due to the 32-byte prefix. 1706 1707 // The final memory read index is msg.data.length - 20 + 32 - 12 = msg.data.length. Using inline assembly is the 1708 // easiest/most-efficient way to perform this operation. 1709 1710 // These fields are not accessible from assembly 1711 bytes memory array = msg.data; 1712 uint256 index = msg.data.length; 1713 1714 // solhint-disable-next-line no-inline-assembly 1715 assembly { 1716 // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. 1717 result := and( 1718 mload(add(array, index)), 1719 0xffffffffffffffffffffffffffffffffffffffff 1720 ) 1721 } 1722 return result; 1723 } 1724 1725 function _getRelayedCallData() private pure returns (bytes memory) { 1726 // RelayHub appends the sender address at the end of the calldata, so in order to retrieve the actual msg.data, 1727 // we must strip the last 20 bytes (length of an address type) from it. 1728 1729 uint256 actualDataLength = msg.data.length - 20; 1730 bytes memory actualData = new bytes(actualDataLength); 1731 1732 for (uint256 i = 0; i < actualDataLength; ++i) { 1733 actualData[i] = msg.data[i]; 1734 } 1735 1736 return actualData; 1737 } 1738 } 1739 1740 library NFTClient { 1741 bytes4 public constant interfaceIdERC721 = 0x80ac58cd; 1742 1743 function requireERC721(address _candidate) public view { 1744 require( 1745 IERC721Enumerable(_candidate).supportsInterface(interfaceIdERC721), 1746 "IS_NOT_721_TOKEN" 1747 ); 1748 } 1749 1750 function transferTokens( 1751 IERC721Enumerable _nftContract, 1752 address _from, 1753 address _to, 1754 uint256[] memory _tokenIds 1755 ) public { 1756 for (uint256 index = 0; index < _tokenIds.length; index++) { 1757 if (_tokenIds[index] == 0) { 1758 break; 1759 } 1760 1761 _nftContract.safeTransferFrom(_from, _to, _tokenIds[index]); 1762 } 1763 } 1764 1765 function transferAll( 1766 IERC721Enumerable _nftContract, 1767 address _sender, 1768 address _receiver 1769 ) public { 1770 uint256 balance = _nftContract.balanceOf(_sender); 1771 while (balance > 0) { 1772 _nftContract.safeTransferFrom( 1773 _sender, 1774 _receiver, 1775 _nftContract.tokenOfOwnerByIndex(_sender, balance - 1) 1776 ); 1777 balance--; 1778 } 1779 } 1780 1781 // /// @dev Pagination of owner tokens 1782 // /// @param owner - address of the token owner 1783 // /// @param page - page number 1784 // /// @param rows - number of rows per page 1785 function tokensOfOwner( 1786 address _nftContract, 1787 address owner, 1788 uint8 page, 1789 uint8 rows 1790 ) public view returns (uint256[] memory) { 1791 requireERC721(_nftContract); 1792 1793 IERC721Enumerable nftContract = IERC721Enumerable(_nftContract); 1794 1795 uint256 tokenCount = nftContract.balanceOf(owner); 1796 uint256 offset = page * rows; 1797 uint256 range = offset > tokenCount 1798 ? 0 1799 : min(tokenCount - offset, rows); 1800 uint256[] memory tokens = new uint256[](range); 1801 for (uint256 index = 0; index < range; index++) { 1802 tokens[index] = nftContract.tokenOfOwnerByIndex( 1803 owner, 1804 offset + index 1805 ); 1806 } 1807 return tokens; 1808 } 1809 1810 function min(uint256 a, uint256 b) private pure returns (uint256) { 1811 return a > b ? b : a; 1812 } 1813 } 1814 1815 interface ISorareTokens { 1816 function createCardAndMintToken( 1817 uint256 playerId, 1818 uint16 season, 1819 uint8 scarcity, 1820 uint16 serialNumber, 1821 bytes32 metadata, 1822 uint16 clubId, 1823 address to 1824 ) external returns (uint256); 1825 1826 function mintToken(uint256 cardId, address to) external returns (uint256); 1827 } 1828 1829 interface INextContract { 1830 function migrateTokens(uint256[] calldata tokenIds, address to) external; 1831 } 1832 1833 contract SorareTokens is 1834 MinterAccess, 1835 RelayRecipient, 1836 ERC721("Sorare", "SOR"), 1837 ISorareTokens 1838 { 1839 ISorareCards public sorareCards; 1840 INextContract public nextContract; 1841 1842 constructor(address sorareCardsAddress, address relayAddress) 1843 public 1844 RelayRecipient(relayAddress) 1845 { 1846 require( 1847 sorareCardsAddress != address(0), 1848 "SorareCards address is required" 1849 ); 1850 sorareCards = ISorareCards(sorareCardsAddress); 1851 } 1852 1853 /// @dev Set the prefix for the tokenURIs. 1854 function setTokenURIPrefix(string memory prefix) public onlyOwner { 1855 _setBaseURI(prefix); 1856 } 1857 1858 /// @dev Set the potential next version contract 1859 function setNextContract(address nextContractAddress) public onlyOwner { 1860 require( 1861 address(nextContract) == address(0), 1862 "NextContract already set" 1863 ); 1864 nextContract = INextContract(nextContractAddress); 1865 } 1866 1867 /// @dev Creates a new card in the Cards contract and mints the token 1868 // prettier-ignore 1869 function createCardAndMintToken( 1870 uint256 playerId, 1871 uint16 season, 1872 uint8 scarcity, 1873 uint16 serialNumber, 1874 bytes32 metadata, 1875 uint16 clubId, 1876 address to 1877 ) public onlyMinter override returns (uint256) { 1878 uint256 cardId = sorareCards.createCard( 1879 playerId, 1880 season, 1881 scarcity, 1882 serialNumber, 1883 metadata, 1884 clubId 1885 ); 1886 1887 _mint(to, cardId); 1888 return cardId; 1889 } 1890 1891 /// @dev Mints a token for an existing card 1892 // prettier-ignore 1893 function mintToken(uint256 cardId, address to) 1894 public 1895 override 1896 onlyMinter 1897 returns (uint256) 1898 { 1899 require(sorareCards.cardExists(cardId), "Card does not exist"); 1900 1901 _mint(to, cardId); 1902 return cardId; 1903 } 1904 1905 /// @dev Migrates tokens to a potential new version of this contract 1906 /// @param tokenIds - list of tokens to transfer 1907 function migrateTokens(uint256[] calldata tokenIds) external { 1908 require(address(nextContract) != address(0), "Next contract not set"); 1909 1910 for (uint256 index = 0; index < tokenIds.length; index++) { 1911 transferFrom(_msgSender(), address(this), tokenIds[index]); 1912 } 1913 1914 nextContract.migrateTokens(tokenIds, _msgSender()); 1915 } 1916 1917 /// @dev Pagination of owner tokens 1918 /// @param owner - address of the token owner 1919 /// @param page - page number 1920 /// @param rows - number of rows per page 1921 function tokensOfOwner(address owner, uint8 page, uint8 rows) 1922 public 1923 view 1924 returns (uint256[] memory) 1925 { 1926 return NFTClient.tokensOfOwner(address(this), owner, page, rows); 1927 } 1928 1929 function getCard(uint256 tokenId) 1930 public 1931 view 1932 returns ( 1933 uint256 playerId, 1934 uint16 season, 1935 uint256 scarcity, 1936 uint16 serialNumber, 1937 bytes memory metadata, 1938 uint16 clubId 1939 ) 1940 { 1941 ( 1942 playerId, 1943 season, 1944 scarcity, 1945 serialNumber, 1946 metadata, 1947 clubId 1948 ) = sorareCards.getCard(tokenId); 1949 } 1950 1951 function getPlayer(uint256 playerId) 1952 external 1953 view 1954 returns ( 1955 string memory name, 1956 uint16 yearOfBirth, 1957 uint8 monthOfBirth, 1958 uint8 dayOfBirth 1959 ) 1960 { 1961 (name, yearOfBirth, monthOfBirth, dayOfBirth) = sorareCards.getPlayer( 1962 playerId 1963 ); 1964 } 1965 1966 // prettier-ignore 1967 function getClub(uint16 clubId) 1968 external 1969 view 1970 returns ( 1971 string memory name, 1972 string memory country, 1973 string memory city, 1974 uint16 yearFounded 1975 ) 1976 { 1977 (name, country, city, yearFounded) = sorareCards.getClub(clubId); 1978 } 1979 1980 // prettier-ignore 1981 function _msgSender() internal view override(RelayRecipient, Context) returns (address payable) { 1982 return RelayRecipient._msgSender(); 1983 } 1984 1985 // prettier-ignore 1986 function _msgData() internal view override(RelayRecipient, Context) returns (bytes memory) { 1987 return RelayRecipient._msgData(); 1988 } 1989 }