ERC721.sol 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. pragma solidity ^0.6.0;
  2. import "../../GSN/Context.sol";
  3. import "./IERC721.sol";
  4. import "./IERC721Metadata.sol";
  5. import "./IERC721Enumerable.sol";
  6. import "./IERC721Receiver.sol";
  7. import "../../introspection/ERC165.sol";
  8. import "../../math/SafeMath.sol";
  9. import "../../utils/Address.sol";
  10. import "../../utils/Counters.sol";
  11. /**
  12. * @title ERC721 Non-Fungible Token Standard basic implementation
  13. * @dev see https://eips.ethereum.org/EIPS/eip-721
  14. */
  15. contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
  16. using SafeMath for uint256;
  17. using Address for address;
  18. using Counters for Counters.Counter;
  19. // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
  20. // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
  21. bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
  22. // Mapping from token ID to owner
  23. mapping (uint256 => address) private _tokenOwner;
  24. // Mapping from token ID to approved address
  25. mapping (uint256 => address) private _tokenApprovals;
  26. // Mapping from owner to number of owned token
  27. mapping (address => Counters.Counter) private _ownedTokensCount;
  28. // Mapping from owner to operator approvals
  29. mapping (address => mapping (address => bool)) private _operatorApprovals;
  30. // Token name
  31. string private _name;
  32. // Token symbol
  33. string private _symbol;
  34. // Optional mapping for token URIs
  35. mapping(uint256 => string) private _tokenURIs;
  36. // Base URI
  37. string private _baseURI;
  38. // Mapping from owner to list of owned token IDs
  39. mapping(address => uint256[]) private _ownedTokens;
  40. // Mapping from token ID to index of the owner tokens list
  41. mapping(uint256 => uint256) private _ownedTokensIndex;
  42. // Array with all token ids, used for enumeration
  43. uint256[] private _allTokens;
  44. // Mapping from token id to position in the allTokens array
  45. mapping(uint256 => uint256) private _allTokensIndex;
  46. /*
  47. * bytes4(keccak256('balanceOf(address)')) == 0x70a08231
  48. * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
  49. * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
  50. * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
  51. * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
  52. * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
  53. * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
  54. * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
  55. * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
  56. *
  57. * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
  58. * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
  59. */
  60. bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
  61. /*
  62. * bytes4(keccak256('name()')) == 0x06fdde03
  63. * bytes4(keccak256('symbol()')) == 0x95d89b41
  64. * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
  65. *
  66. * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
  67. */
  68. bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
  69. /*
  70. * bytes4(keccak256('totalSupply()')) == 0x18160ddd
  71. * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
  72. * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
  73. *
  74. * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
  75. */
  76. bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
  77. constructor (string memory name, string memory symbol) public {
  78. _name = name;
  79. _symbol = symbol;
  80. // register the supported interfaces to conform to ERC721 via ERC165
  81. _registerInterface(_INTERFACE_ID_ERC721);
  82. _registerInterface(_INTERFACE_ID_ERC721_METADATA);
  83. _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
  84. }
  85. /**
  86. * @dev Gets the balance of the specified address.
  87. * @param owner address to query the balance of
  88. * @return uint256 representing the amount owned by the passed address
  89. */
  90. function balanceOf(address owner) public view override returns (uint256) {
  91. require(owner != address(0), "ERC721: balance query for the zero address");
  92. return _ownedTokensCount[owner].current();
  93. }
  94. /**
  95. * @dev Gets the owner of the specified token ID.
  96. * @param tokenId uint256 ID of the token to query the owner of
  97. * @return address currently marked as the owner of the given token ID
  98. */
  99. function ownerOf(uint256 tokenId) public view override returns (address) {
  100. address owner = _tokenOwner[tokenId];
  101. require(owner != address(0), "ERC721: owner query for nonexistent token");
  102. return owner;
  103. }
  104. /**
  105. * @dev Gets the token name.
  106. * @return string representing the token name
  107. */
  108. function name() public view override returns (string memory) {
  109. return _name;
  110. }
  111. /**
  112. * @dev Gets the token symbol.
  113. * @return string representing the token symbol
  114. */
  115. function symbol() public view override returns (string memory) {
  116. return _symbol;
  117. }
  118. /**
  119. * @dev Returns the URI for a given token ID. May return an empty string.
  120. *
  121. * If the token's URI is non-empty and a base URI was set (via
  122. * {_setBaseURI}), it will be added to the token ID's URI as a prefix.
  123. *
  124. * Reverts if the token ID does not exist.
  125. */
  126. function tokenURI(uint256 tokenId) public view override returns (string memory) {
  127. require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
  128. string memory _tokenURI = _tokenURIs[tokenId];
  129. // Even if there is a base URI, it is only appended to non-empty token-specific URIs
  130. if (bytes(_tokenURI).length == 0) {
  131. return "";
  132. } else {
  133. // abi.encodePacked is being used to concatenate strings
  134. return string(abi.encodePacked(_baseURI, _tokenURI));
  135. }
  136. }
  137. /**
  138. * @dev Returns the base URI set via {_setBaseURI}. This will be
  139. * automatically added as a preffix in {tokenURI} to each token's URI, when
  140. * they are non-empty.
  141. */
  142. function baseURI() public view returns (string memory) {
  143. return _baseURI;
  144. }
  145. /**
  146. * @dev Gets the token ID at a given index of the tokens list of the requested owner.
  147. * @param owner address owning the tokens list to be accessed
  148. * @param index uint256 representing the index to be accessed of the requested tokens list
  149. * @return uint256 token ID at the given index of the tokens list owned by the requested address
  150. */
  151. function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
  152. require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
  153. return _ownedTokens[owner][index];
  154. }
  155. /**
  156. * @dev Gets the total amount of tokens stored by the contract.
  157. * @return uint256 representing the total amount of tokens
  158. */
  159. function totalSupply() public view override returns (uint256) {
  160. return _allTokens.length;
  161. }
  162. /**
  163. * @dev Gets the token ID at a given index of all the tokens in this contract
  164. * Reverts if the index is greater or equal to the total number of tokens.
  165. * @param index uint256 representing the index to be accessed of the tokens list
  166. * @return uint256 token ID at the given index of the tokens list
  167. */
  168. function tokenByIndex(uint256 index) public view override returns (uint256) {
  169. require(index < totalSupply(), "ERC721Enumerable: global index out of bounds");
  170. return _allTokens[index];
  171. }
  172. /**
  173. * @dev Approves another address to transfer the given token ID
  174. * The zero address indicates there is no approved address.
  175. * There can only be one approved address per token at a given time.
  176. * Can only be called by the token owner or an approved operator.
  177. * @param to address to be approved for the given token ID
  178. * @param tokenId uint256 ID of the token to be approved
  179. */
  180. function approve(address to, uint256 tokenId) public virtual override {
  181. address owner = ownerOf(tokenId);
  182. require(to != owner, "ERC721: approval to current owner");
  183. require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
  184. "ERC721: approve caller is not owner nor approved for all"
  185. );
  186. _approve(to, tokenId);
  187. }
  188. /**
  189. * @dev Gets the approved address for a token ID, or zero if no address set
  190. * Reverts if the token ID does not exist.
  191. * @param tokenId uint256 ID of the token to query the approval of
  192. * @return address currently approved for the given token ID
  193. */
  194. function getApproved(uint256 tokenId) public view override returns (address) {
  195. require(_exists(tokenId), "ERC721: approved query for nonexistent token");
  196. return _tokenApprovals[tokenId];
  197. }
  198. /**
  199. * @dev Sets or unsets the approval of a given operator
  200. * An operator is allowed to transfer all tokens of the sender on their behalf.
  201. * @param operator operator address to set the approval
  202. * @param approved representing the status of the approval to be set
  203. */
  204. function setApprovalForAll(address operator, bool approved) public virtual override {
  205. require(operator != _msgSender(), "ERC721: approve to caller");
  206. _operatorApprovals[_msgSender()][operator] = approved;
  207. emit ApprovalForAll(_msgSender(), operator, approved);
  208. }
  209. /**
  210. * @dev Tells whether an operator is approved by a given owner.
  211. * @param owner owner address which you want to query the approval of
  212. * @param operator operator address which you want to query the approval of
  213. * @return bool whether the given operator is approved by the given owner
  214. */
  215. function isApprovedForAll(address owner, address operator) public view override returns (bool) {
  216. return _operatorApprovals[owner][operator];
  217. }
  218. /**
  219. * @dev Transfers the ownership of a given token ID to another address.
  220. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
  221. * Requires the msg.sender to be the owner, approved, or operator.
  222. * @param from current owner of the token
  223. * @param to address to receive the ownership of the given token ID
  224. * @param tokenId uint256 ID of the token to be transferred
  225. */
  226. function transferFrom(address from, address to, uint256 tokenId) public virtual override {
  227. //solhint-disable-next-line max-line-length
  228. require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
  229. _transfer(from, to, tokenId);
  230. }
  231. /**
  232. * @dev Safely transfers the ownership of a given token ID to another address
  233. * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
  234. * which is called upon a safe transfer, and return the magic value
  235. * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
  236. * the transfer is reverted.
  237. * Requires the msg.sender to be the owner, approved, or operator
  238. * @param from current owner of the token
  239. * @param to address to receive the ownership of the given token ID
  240. * @param tokenId uint256 ID of the token to be transferred
  241. */
  242. function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
  243. safeTransferFrom(from, to, tokenId, "");
  244. }
  245. /**
  246. * @dev Safely transfers the ownership of a given token ID to another address
  247. * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
  248. * which is called upon a safe transfer, and return the magic value
  249. * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
  250. * the transfer is reverted.
  251. * Requires the _msgSender() to be the owner, approved, or operator
  252. * @param from current owner of the token
  253. * @param to address to receive the ownership of the given token ID
  254. * @param tokenId uint256 ID of the token to be transferred
  255. * @param _data bytes data to send along with a safe transfer check
  256. */
  257. function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
  258. require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
  259. _safeTransfer(from, to, tokenId, _data);
  260. }
  261. /**
  262. * @dev Safely transfers the ownership of a given token ID to another address
  263. * If the target address is a contract, it must implement `onERC721Received`,
  264. * which is called upon a safe transfer, and return the magic value
  265. * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
  266. * the transfer is reverted.
  267. * Requires the msg.sender to be the owner, approved, or operator
  268. * @param from current owner of the token
  269. * @param to address to receive the ownership of the given token ID
  270. * @param tokenId uint256 ID of the token to be transferred
  271. * @param _data bytes data to send along with a safe transfer check
  272. */
  273. function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
  274. _transfer(from, to, tokenId);
  275. require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
  276. }
  277. /**
  278. * @dev Returns whether the specified token exists.
  279. * @param tokenId uint256 ID of the token to query the existence of
  280. * @return bool whether the token exists
  281. */
  282. function _exists(uint256 tokenId) internal view returns (bool) {
  283. address owner = _tokenOwner[tokenId];
  284. return owner != address(0);
  285. }
  286. /**
  287. * @dev Returns whether the given spender can transfer a given token ID.
  288. * @param spender address of the spender to query
  289. * @param tokenId uint256 ID of the token to be transferred
  290. * @return bool whether the msg.sender is approved for the given token ID,
  291. * is an operator of the owner, or is the owner of the token
  292. */
  293. function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
  294. require(_exists(tokenId), "ERC721: operator query for nonexistent token");
  295. address owner = ownerOf(tokenId);
  296. return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
  297. }
  298. /**
  299. * @dev Internal function to safely mint a new token.
  300. * Reverts if the given token ID already exists.
  301. * If the target address is a contract, it must implement `onERC721Received`,
  302. * which is called upon a safe transfer, and return the magic value
  303. * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
  304. * the transfer is reverted.
  305. * @param to The address that will own the minted token
  306. * @param tokenId uint256 ID of the token to be minted
  307. */
  308. function _safeMint(address to, uint256 tokenId) internal virtual {
  309. _safeMint(to, tokenId, "");
  310. }
  311. /**
  312. * @dev Internal function to safely mint a new token.
  313. * Reverts if the given token ID already exists.
  314. * If the target address is a contract, it must implement `onERC721Received`,
  315. * which is called upon a safe transfer, and return the magic value
  316. * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
  317. * the transfer is reverted.
  318. * @param to The address that will own the minted token
  319. * @param tokenId uint256 ID of the token to be minted
  320. * @param _data bytes data to send along with a safe transfer check
  321. */
  322. function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
  323. _mint(to, tokenId);
  324. require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
  325. }
  326. /**
  327. * @dev Internal function to mint a new token.
  328. * Reverts if the given token ID already exists.
  329. * @param to The address that will own the minted token
  330. * @param tokenId uint256 ID of the token to be minted
  331. */
  332. function _mint(address to, uint256 tokenId) internal virtual {
  333. require(to != address(0), "ERC721: mint to the zero address");
  334. require(!_exists(tokenId), "ERC721: token already minted");
  335. _beforeTokenTransfer(address(0), to, tokenId);
  336. _addTokenToOwnerEnumeration(to, tokenId);
  337. _addTokenToAllTokensEnumeration(tokenId);
  338. _tokenOwner[tokenId] = to;
  339. _ownedTokensCount[to].increment();
  340. emit Transfer(address(0), to, tokenId);
  341. }
  342. /**
  343. * @dev Internal function to burn a specific token.
  344. * Reverts if the token does not exist.
  345. * @param tokenId uint256 ID of the token being burned
  346. */
  347. function _burn(uint256 tokenId) internal virtual {
  348. address owner = ownerOf(tokenId);
  349. _beforeTokenTransfer(owner, address(0), tokenId);
  350. // Clear metadata (if any)
  351. if (bytes(_tokenURIs[tokenId]).length != 0) {
  352. delete _tokenURIs[tokenId];
  353. }
  354. _removeTokenFromOwnerEnumeration(owner, tokenId);
  355. // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
  356. _ownedTokensIndex[tokenId] = 0;
  357. _removeTokenFromAllTokensEnumeration(tokenId);
  358. // Clear approvals
  359. _approve(address(0), tokenId);
  360. _ownedTokensCount[owner].decrement();
  361. _tokenOwner[tokenId] = address(0);
  362. emit Transfer(owner, address(0), tokenId);
  363. }
  364. /**
  365. * @dev Internal function to transfer ownership of a given token ID to another address.
  366. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
  367. * @param from current owner of the token
  368. * @param to address to receive the ownership of the given token ID
  369. * @param tokenId uint256 ID of the token to be transferred
  370. */
  371. function _transfer(address from, address to, uint256 tokenId) internal virtual {
  372. require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
  373. require(to != address(0), "ERC721: transfer to the zero address");
  374. _beforeTokenTransfer(from, to, tokenId);
  375. _removeTokenFromOwnerEnumeration(from, tokenId);
  376. _addTokenToOwnerEnumeration(to, tokenId);
  377. // Clear approvals
  378. _approve(address(0), tokenId);
  379. _ownedTokensCount[from].decrement();
  380. _ownedTokensCount[to].increment();
  381. _tokenOwner[tokenId] = to;
  382. emit Transfer(from, to, tokenId);
  383. }
  384. /**
  385. * @dev Internal function to set the token URI for a given token.
  386. *
  387. * Reverts if the token ID does not exist.
  388. *
  389. * TIP: If all token IDs share a prefix (for example, if your URIs look like
  390. * `https://api.myproject.com/token/<id>`), use {_setBaseURI} to store
  391. * it and save gas.
  392. */
  393. function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
  394. require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
  395. _tokenURIs[tokenId] = _tokenURI;
  396. }
  397. /**
  398. * @dev Internal function to set the base URI for all token IDs. It is
  399. * automatically added as a prefix to the value returned in {tokenURI}.
  400. */
  401. function _setBaseURI(string memory baseURI_) internal virtual {
  402. _baseURI = baseURI_;
  403. }
  404. /**
  405. * @dev Gets the list of token IDs of the requested owner.
  406. * @param owner address owning the tokens
  407. * @return uint256[] List of token IDs owned by the requested address
  408. */
  409. function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
  410. return _ownedTokens[owner];
  411. }
  412. /**
  413. * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
  414. * The call is not executed if the target address is not a contract.
  415. *
  416. * @param from address representing the previous owner of the given token ID
  417. * @param to target address that will receive the tokens
  418. * @param tokenId uint256 ID of the token to be transferred
  419. * @param _data bytes optional data to send along with the call
  420. * @return bool whether the call correctly returned the expected magic value
  421. */
  422. function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
  423. private returns (bool)
  424. {
  425. if (!to.isContract()) {
  426. return true;
  427. }
  428. // solhint-disable-next-line avoid-low-level-calls
  429. (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector(
  430. IERC721Receiver(to).onERC721Received.selector,
  431. _msgSender(),
  432. from,
  433. tokenId,
  434. _data
  435. ));
  436. if (!success) {
  437. if (returndata.length > 0) {
  438. // solhint-disable-next-line no-inline-assembly
  439. assembly {
  440. let returndata_size := mload(returndata)
  441. revert(add(32, returndata), returndata_size)
  442. }
  443. } else {
  444. revert("ERC721: transfer to non ERC721Receiver implementer");
  445. }
  446. } else {
  447. bytes4 retval = abi.decode(returndata, (bytes4));
  448. return (retval == _ERC721_RECEIVED);
  449. }
  450. }
  451. function _approve(address to, uint256 tokenId) private {
  452. _tokenApprovals[tokenId] = to;
  453. emit Approval(ownerOf(tokenId), to, tokenId);
  454. }
  455. /**
  456. * @dev Private function to add a token to this extension's ownership-tracking data structures.
  457. * @param to address representing the new owner of the given token ID
  458. * @param tokenId uint256 ID of the token to be added to the tokens list of the given address
  459. */
  460. function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
  461. _ownedTokensIndex[tokenId] = _ownedTokens[to].length;
  462. _ownedTokens[to].push(tokenId);
  463. }
  464. /**
  465. * @dev Private function to add a token to this extension's token tracking data structures.
  466. * @param tokenId uint256 ID of the token to be added to the tokens list
  467. */
  468. function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
  469. _allTokensIndex[tokenId] = _allTokens.length;
  470. _allTokens.push(tokenId);
  471. }
  472. /**
  473. * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
  474. * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
  475. * gas optimizations e.g. when performing a transfer operation (avoiding double writes).
  476. * This has O(1) time complexity, but alters the order of the _ownedTokens array.
  477. * @param from address representing the previous owner of the given token ID
  478. * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
  479. */
  480. function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
  481. // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
  482. // then delete the last slot (swap and pop).
  483. uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
  484. uint256 tokenIndex = _ownedTokensIndex[tokenId];
  485. // When the token to delete is the last token, the swap operation is unnecessary
  486. if (tokenIndex != lastTokenIndex) {
  487. uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
  488. _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
  489. _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
  490. }
  491. // Deletes the contents at the last position of the array
  492. _ownedTokens[from].pop();
  493. // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
  494. // lastTokenId, or just over the end of the array if the token was the last one).
  495. }
  496. /**
  497. * @dev Private function to remove a token from this extension's token tracking data structures.
  498. * This has O(1) time complexity, but alters the order of the _allTokens array.
  499. * @param tokenId uint256 ID of the token to be removed from the tokens list
  500. */
  501. function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
  502. // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
  503. // then delete the last slot (swap and pop).
  504. uint256 lastTokenIndex = _allTokens.length.sub(1);
  505. uint256 tokenIndex = _allTokensIndex[tokenId];
  506. // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
  507. // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
  508. // an 'if' statement (like in _removeTokenFromOwnerEnumeration)
  509. uint256 lastTokenId = _allTokens[lastTokenIndex];
  510. _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
  511. _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
  512. // Delete the contents at the last position of the array
  513. _allTokens.pop();
  514. _allTokensIndex[tokenId] = 0;
  515. }
  516. /**
  517. * @dev Hook that is called before any token transfer. This includes minting
  518. * and burning.
  519. *
  520. * Calling conditions:
  521. *
  522. * - when `from` and `to` are both non-zero, `from`'s `tokenId` will be
  523. * transferred to `to`.
  524. * - when `from` is zero, `tokenId` will be minted for `to`.
  525. * - when `to` is zero, `from`'s `tokenId` will be burned.
  526. * - `from` and `to` are never both zero.
  527. *
  528. * To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks].
  529. */
  530. function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
  531. }