/
ERC721BaseTokenV2.sol
462 lines (422 loc) · 18.2 KB
/
ERC721BaseTokenV2.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//SPDX-License-Identifier: MIT
/* solhint-disable func-order, code-complexity */
// solhint-disable-next-line compiler-version
pragma solidity 0.8.2;
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "./WithSuperOperatorsV2.sol";
import "../interfaces/IERC721MandatoryTokenReceiver.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
contract ERC721BaseTokenV2 is ContextUpgradeable, IERC721Upgradeable, WithSuperOperatorsV2 {
using AddressUpgradeable for address;
bytes4 internal constant _ERC721_RECEIVED = 0x150b7a02;
bytes4 internal constant _ERC721_BATCH_RECEIVED = 0x4b808c46;
bytes4 internal constant ERC165ID = 0x01ffc9a7;
bytes4 internal constant ERC721_MANDATORY_RECEIVER = 0x5e8bf644;
uint256 internal constant NOT_ADDRESS = 0xFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000000000000;
uint256 internal constant OPERATOR_FLAG = (2**255);
uint256 internal constant NOT_OPERATOR_FLAG = OPERATOR_FLAG - 1;
uint256 internal constant BURNED_FLAG = (2**160);
mapping(address => uint256) internal _numNFTPerAddress;
mapping(uint256 => uint256) internal _owners;
mapping(address => mapping(address => bool)) internal _operatorsForAll;
mapping(uint256 => address) internal _operators;
/// @notice Approve an operator to spend tokens on the senders behalf.
/// @param operator The address receiving the approval.
/// @param id The id of the token.
function approve(address operator, uint256 id) external virtual override {
uint256 ownerData = _owners[_storageId(id)];
address owner = _ownerOf(id);
address msgSender = _msgSender();
require(owner != address(0), "NONEXISTENT_TOKEN");
require(
owner == msgSender || _operatorsForAll[owner][msgSender] || _superOperators[msgSender],
"UNAUTHORIZED_APPROVAL"
);
_approveFor(ownerData, operator, id);
}
/// @notice Approve an operator to spend tokens on the sender behalf.
/// @param sender The address giving the approval.
/// @param operator The address receiving the approval.
/// @param id The id of the token.
function approveFor(
address sender,
address operator,
uint256 id
) external virtual {
uint256 ownerData = _owners[_storageId(id)];
address owner = _ownerOf(id);
address msgSender = _msgSender();
require(sender != address(0), "ZERO_ADDRESS_SENDER");
require(owner != address(0), "NONEXISTENT_TOKEN");
require(
msgSender == sender || _operatorsForAll[sender][msgSender] || _superOperators[msgSender],
"UNAUTHORIZED_APPROVAL"
);
require(address(uint160(ownerData)) == sender, "OWNER_NOT_SENDER");
_approveFor(ownerData, operator, id);
}
/// @notice Transfer a token between 2 addresses.
/// @param from The sender of the token.
/// @param to The recipient of the token.
/// @param id The id of the token.
function transferFrom(
address from,
address to,
uint256 id
) external virtual override {
_checkTransfer(from, to, id);
_transferFrom(from, to, id);
if (to.isContract() && _checkInterfaceWith10000Gas(to, ERC721_MANDATORY_RECEIVER)) {
require(_checkOnERC721Received(_msgSender(), from, to, id, ""), "ERC721_TRANSFER_REJECTED");
}
}
/// @notice Transfer a token between 2 addresses letting the receiver know of the transfer.
/// @param from The send of the token.
/// @param to The recipient of the token.
/// @param id The id of the token.
function safeTransferFrom(
address from,
address to,
uint256 id
) external virtual override {
safeTransferFrom(from, to, id, "");
}
/// @notice Transfer many tokens between 2 addresses.
/// @param from The sender of the token.
/// @param to The recipient of the token.
/// @param ids The ids of the tokens.
/// @param data Additional data.
function batchTransferFrom(
address from,
address to,
uint256[] calldata ids,
bytes calldata data
) public virtual {
_batchTransferFrom(from, to, ids, data, false);
}
/// @notice Transfer many tokens between 2 addresses, while
/// ensuring the receiving contract has a receiver method.
/// @param from The sender of the token.
/// @param to The recipient of the token.
/// @param ids The ids of the tokens.
/// @param data Additional data.
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
bytes calldata data
) external virtual {
_batchTransferFrom(from, to, ids, data, true);
}
/// @notice Set the approval for an operator to manage all the tokens of the sender.
/// @param sender The address giving the approval.
/// @param operator The address receiving the approval.
/// @param approved The determination of the approval.
function setApprovalForAllFor(
address sender,
address operator,
bool approved
) external virtual {
require(sender != address(0), "Invalid sender address");
address msgSender = _msgSender();
require(msgSender == sender || _superOperators[msgSender], "UNAUTHORIZED_APPROVE_FOR_ALL");
_setApprovalForAll(sender, operator, approved);
}
/// @notice Set the approval for an operator to manage all the tokens of the sender.
/// @param operator The address receiving the approval.
/// @param approved The determination of the approval.
function setApprovalForAll(address operator, bool approved) external virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/// @notice Burns token `id`.
/// @param id The token which will be burnt.
function burn(uint256 id) external virtual {
_burn(_msgSender(), _ownerOf(id), id);
}
/// @notice Burn token`id` from `from`.
/// @param from address whose token is to be burnt.
/// @param id The token which will be burnt.
function burnFrom(address from, uint256 id) external virtual {
require(from != address(0), "NOT_FROM_ZEROADDRESS");
(address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id);
address msgSender = _msgSender();
require(
msgSender == from ||
(operatorEnabled && _operators[id] == msgSender) ||
_superOperators[msgSender] ||
_operatorsForAll[from][msgSender],
"UNAUTHORIZED_BURN"
);
_burn(from, owner, id);
}
/// @notice Get the number of tokens owned by an address.
/// @param owner The address to look for.
/// @return The number of tokens owned by the address.
function balanceOf(address owner) external view override returns (uint256) {
require(owner != address(0), "ZERO_ADDRESS_OWNER");
return _numNFTPerAddress[owner];
}
/// @notice Get the owner of a token.
/// @param id The id of the token.
/// @return owner The address of the token owner.
function ownerOf(uint256 id) external view override returns (address owner) {
owner = _ownerOf(id);
require(owner != address(0), "NONEXISTANT_TOKEN");
}
/// @notice Get the approved operator for a specific token.
/// @param id The id of the token.
/// @return The address of the operator.
function getApproved(uint256 id) external view override returns (address) {
(address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id);
require(owner != address(0), "NONEXISTENT_TOKEN");
if (operatorEnabled) {
return _operators[id];
} else {
return address(0);
}
}
/// @notice Check if the sender approved the operator.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return isOperator The status of the approval.
function isApprovedForAll(address owner, address operator) external view override returns (bool isOperator) {
return _operatorsForAll[owner][operator] || _superOperators[operator];
}
/// @notice Transfer a token between 2 addresses letting the receiver knows of the transfer.
/// @param from The sender of the token.
/// @param to The recipient of the token.
/// @param id The id of the token.
/// @param data Additional data.
function safeTransferFrom(
address from,
address to,
uint256 id,
bytes memory data
) public virtual override {
_checkTransfer(from, to, id);
_transferFrom(from, to, id);
if (to.isContract()) {
require(_checkOnERC721Received(_msgSender(), from, to, id, data), "ERC721_TRANSFER_REJECTED");
}
}
/// @notice Check if the contract supports an interface.
/// 0x01ffc9a7 is ERC-165.
/// 0x80ac58cd is ERC-721
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id) public pure virtual override returns (bool) {
return id == 0x01ffc9a7 || id == 0x80ac58cd;
}
/// @dev By overriding this function in an implementation which inherits this contract,
/// you can enable versioned tokenIds without the extra overhead of writing to a new storage slot in _owners each time a version is incremented.
/// See GameToken._storageId() for an example, where the storageId is the tokenId minus the version number.
/// !!! Caution !!! Overriding this function without taking appropriate care could lead to
/// ownerOf() returning an owner for non-existent tokens. Tests should be written to
/// guard against introducing this bug.
/// @param id The id of a token.
/// @return The id used for storage mappings.
function _storageId(uint256 id) internal view virtual returns (uint256) {
return id;
}
function _updateOwnerData(
uint256 id,
uint256 oldData,
address newOwner,
bool hasOperator
) internal virtual {
if (hasOperator) {
_owners[_storageId(id)] = (oldData & NOT_ADDRESS) | OPERATOR_FLAG | uint256(uint160(newOwner));
} else {
_owners[_storageId(id)] = ((oldData & NOT_ADDRESS) & NOT_OPERATOR_FLAG) | uint256(uint160(newOwner));
}
}
function _transferFrom(
address from,
address to,
uint256 id
) internal {
_numNFTPerAddress[from]--;
_numNFTPerAddress[to]++;
_updateOwnerData(id, _owners[_storageId(id)], to, false);
emit Transfer(from, to, id);
}
/// @dev See approveFor.
function _approveFor(
uint256 ownerData,
address operator,
uint256 id
) internal {
address owner = _ownerOf(id);
if (operator == address(0)) {
_updateOwnerData(id, ownerData, owner, false);
} else {
_updateOwnerData(id, ownerData, owner, true);
_operators[id] = operator;
}
emit Approval(owner, operator, id);
}
/// @dev See batchTransferFrom.
function _batchTransferFrom(
address from,
address to,
uint256[] memory ids,
bytes memory data,
bool safe
) internal {
address msgSender = _msgSender();
bool authorized = msgSender == from || _operatorsForAll[from][msgSender] || _superOperators[msgSender];
require(from != address(0), "NOT_FROM_ZEROADDRESS");
require(to != address(0), "NOT_TO_ZEROADDRESS");
uint256 numTokens = ids.length;
for (uint256 i = 0; i < numTokens; i++) {
uint256 id = ids[i];
(address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id);
require(owner == from, "BATCHTRANSFERFROM_NOT_OWNER");
require(authorized || (operatorEnabled && _operators[id] == msgSender), "NOT_AUTHORIZED");
_updateOwnerData(id, _owners[_storageId(id)], to, false);
emit Transfer(from, to, id);
}
if (from != to) {
_numNFTPerAddress[from] -= numTokens;
_numNFTPerAddress[to] += numTokens;
}
if (to.isContract()) {
if (_checkInterfaceWith10000Gas(to, ERC721_MANDATORY_RECEIVER)) {
require(_checkOnERC721BatchReceived(msgSender, from, to, ids, data), "ERC721_BATCH_RECEIVED_REJECTED");
} else if (safe) {
for (uint256 i = 0; i < numTokens; i++) {
require(_checkOnERC721Received(msgSender, from, to, ids[i], data), "ERC721_RECEIVED_REJECTED");
}
}
}
}
/// @dev See setApprovalForAll.
function _setApprovalForAll(
address sender,
address operator,
bool approved
) internal {
require(!_superOperators[operator], "INVALID_APPROVAL_CHANGE");
_operatorsForAll[sender][operator] = approved;
emit ApprovalForAll(sender, operator, approved);
}
/// @dev See burn.
function _burn(
address from,
address owner,
uint256 id
) internal {
require(from == owner, "NOT_OWNER");
uint256 storageId = _storageId(id);
_owners[storageId] = (_owners[storageId] & NOT_OPERATOR_FLAG) | BURNED_FLAG; // record as non owner but keep track of last owner
_numNFTPerAddress[from]--;
emit Transfer(from, address(0), id);
}
/// @dev Check if receiving contract accepts erc721 transfers.
/// @param operator The address of the operator.
/// @param from The from address, may be different from msg.sender.
/// @param to The adddress we want to transfer to.
/// @param tokenId The id of the token we would like to transfer.
/// @param _data Any additional data to send with the transfer.
/// @return Whether the expected value of 0x150b7a02 is returned.
function _checkOnERC721Received(
address operator,
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal returns (bool) {
bytes4 retval = IERC721ReceiverUpgradeable(to).onERC721Received(operator, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
/// @dev Check if receiving contract accepts erc721 batch transfers.
/// @param operator The address of the operator.
/// @param from The from address, may be different from msg.sender.
/// @param to The adddress we want to transfer to.
/// @param ids The ids of the tokens we would like to transfer.
/// @param _data Any additional data to send with the transfer.
/// @return Whether the expected value of 0x4b808c46 is returned.
function _checkOnERC721BatchReceived(
address operator,
address from,
address to,
uint256[] memory ids,
bytes memory _data
) internal returns (bool) {
bytes4 retval = IERC721MandatoryTokenReceiver(to).onERC721BatchReceived(operator, from, ids, _data);
return (retval == _ERC721_BATCH_RECEIVED);
}
/// @dev See ownerOf
function _ownerOf(uint256 id) internal view virtual returns (address) {
uint256 data = _owners[_storageId(id)];
if ((data & BURNED_FLAG) == BURNED_FLAG) {
return address(0);
}
return address(uint160(data));
}
/// @dev Get the owner and operatorEnabled status of a token.
/// @param id The token to query.
/// @return owner The owner of the token.
/// @return operatorEnabled Whether or not operators are enabled for this token.
function _ownerAndOperatorEnabledOf(uint256 id)
internal
view
virtual
returns (address owner, bool operatorEnabled)
{
uint256 data = _owners[_storageId(id)];
if ((data & BURNED_FLAG) == BURNED_FLAG) {
owner = address(0);
} else {
owner = address(uint160(data));
}
operatorEnabled = (data & OPERATOR_FLAG) == OPERATOR_FLAG;
}
/// @dev Check whether a transfer is a meta Transaction or not.
/// @param from The address who initiated the transfer (may differ from msg.sender).
/// @param to The address recieving the token.
/// @param id The token being transferred.
/// @return isMetaTx Whether or not the transaction is a MetaTx.
function _checkTransfer(
address from,
address to,
uint256 id
) internal view returns (bool isMetaTx) {
(address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id);
address msgSender = _msgSender();
require(owner != address(0), "NONEXISTENT_TOKEN");
require(owner == from, "CHECKTRANSFER_NOT_OWNER");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(
msgSender == owner ||
_superOperators[msgSender] ||
_operatorsForAll[from][msgSender] ||
(operatorEnabled && _operators[id] == msgSender),
"UNAUTHORIZED_TRANSFER"
);
return true;
}
/// @dev Check if there was enough gas.
/// @param _contract The address of the contract to check.
/// @param interfaceId The id of the interface we want to test.
/// @return Whether or not this check succeeded.
function _checkInterfaceWith10000Gas(address _contract, bytes4 interfaceId) internal view returns (bool) {
bool success;
bool result;
bytes memory callData = abi.encodeWithSelector(ERC165ID, interfaceId);
// solhint-disable-next-line no-inline-assembly
assembly {
let call_ptr := add(0x20, callData)
let call_size := mload(callData)
let output := mload(0x40) // Find empty storage location using "free memory pointer"
mstore(output, 0x0)
success := staticcall(10000, _contract, call_ptr, call_size, output, 0x20) // 32 bytes
result := mload(output)
}
// (10000 / 63) "not enough for supportsInterface(...)" // consume all gas, so caller can potentially know that there was not enough gas
assert(gasleft() > 158);
return success && result;
}
}