-
Notifications
You must be signed in to change notification settings - Fork 1
/
ERC721Mintable.sol
561 lines (469 loc) Β· 22.9 KB
/
ERC721Mintable.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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
// REAL ESTATE TOKEN NAME: IntREstellarToken
pragma solidity >=0.5.0;
// originally was 'openzeppelin-solidity/contracts/utils/Address.sol'
// Need to make it '../../node_modules...' or "./File" if linking to file speficially"
import '../../node_modules/openzeppelin-solidity/contracts/utils/Address.sol';
import '../../node_modules/openzeppelin-solidity/contracts/drafts/Counters.sol';
import '../../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol';
import '../../node_modules/openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol';
import "./Oraclize.sol";
contract Ownable {
// TODO's
// 1) create a private '_owner' variable of type address with a public getter function
address public _owner;
// 2) create an internal constructor that sets the _owner var to the creater of the contract --- it's listed under `address public _owner` within `contract Ownable`
constructor () public {
// establish owner as creator: "message sender"
_owner = msg.sender;
}
// 3) create an 'onlyOwner' modifier that throws if called by any account other than the owner.
modifier onlyOwner () {
require(msg.sender == _owner, "Only the owenrs can actually access this function here");
_;
}
// 4) fill out the transferOwnership function
function transferOwnership(address newOwner) public onlyOwner {
// TODO add functionality to transfer control of the contract to a newOwner.
// make sure the new owner is a real address
require(newOwner != address(0), "This address is an invalid one for the new owenr here");
emit OwnershipTransfered(_owner, newOwner);
_owner = newOwner;
}
// 5) create an event that emits anytime ownerShip is transfered (including in the constructor)
event OwnershipTransfered(address indexed oldOwner, address indexed newOwner);
}
// TODO's: Create a Pausable contract that inherits from the Ownable contract
contract Pausable is Ownable {
// 1) create a private '_paused' variable of type bool
bool private _paused;
// 2) create a public setter using the inherited onlyOwner modifier
// function part 1 of 2: pause - get it to stop
function pause()
public
onlyOwner
whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
// function part 2 of 2: unpause - get it to start again
function unpause()
public
onlyOwner
paused {
_paused = false;
emit Unpaused(msg.sender);
}
// 3) create an internal constructor that sets the _paused variable to false
constructor()
internal {
_paused = false;
}
// 4) create 'whenNotPaused' & 'paused' modifier that throws in the appropriate situation
modifier whenNotPaused() {
require(_paused == false, "This contract here is paused");
_;
}
modifier paused() {
require(_paused == true, "This contract here is not paused");
_;
}
// 5) create a Paused & Unpaused event that emits the address that triggered the event
event Paused(address sender);
event Unpaused(address sender);
}
contract ERC165 {
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/*
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor () internal {
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev internal method for registering an interface
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
contract ERC721 is Pausable, ERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
// IMPORTANT: this mapping uses Counters lib which is used to protect overflow when incrementing/decrementing a uint
// use the following functions when interacting with Counters: increment(), decrement(), and current() to get the value
// see: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/drafts/Counters.sol
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
}
function balanceOf(address owner) public view returns (uint256) {
// TODO return the token balance of given address
// TIP: remember the functions to use for Counters. you can refresh yourself with the link above
return _ownedTokensCount[owner].current();
}
function ownerOf(uint256 tokenId) public view returns (address) {
// TODO return the owner of the given tokenId
return _tokenOwner[tokenId];
}
// @dev Approves another address to transfer the given token ID
function approve(address to, uint256 tokenId) public {
// TODO require the given address to not be the owner of the tokenId
address owner = ownerOf(tokenId);
require(to != ownerOf(tokenId), "This address is the owner's address");
// TODO require the msg sender to be the owner of the contract or isApprovedForAll() to be true
require(ownerOf(tokenId) == msg.sender, "Only the owner is allowed to aprove this request");
// TODO add 'to' address to token approvals
_tokenApprovals[tokenId] = to;
// TODO emit Approval Event
emit Approval(owner, to, tokenId);
}
function getApproved(uint256 tokenId) public view returns (address) {
// TODO return token approval if it exists
require(_exists(tokenId));
return _tokenApprovals[tokenId];
// does the token exist - check:
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(to != msg.sender);
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
function transferFrom(address from, address to, uint256 tokenId) public {
require(_isApprovedOrOwner(msg.sender, tokenId));
_transferFrom(from, to, tokenId);
}
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data));
}
/**
* @dev Returns whether the specified token exists
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
// @dev Internal function to mint a new token
// TIP: remember the functions to use for Counters. you can refresh yourself with the link above
function _mint(address to, uint256 tokenId) internal {
// TODO revert if given tokenId already exists or given address is invalid
require(_exists(tokenId) == false, "The specified Token ID already exists!");
// invalid
require(to != address(0), "The given address is invalid!");
// TODO mint tokenId to given address & increase token count of owner
_tokenOwner[tokenId] = to;
// increase token count of owner with increment
_ownedTokensCount[to].increment();
// TODO emit Transfer event
emit Transfer(msg.sender, to, tokenId);
}
// @dev Internal function to transfer ownership of a given token ID to another address.
// TIP: remember the functions to use for Counters. you can refresh yourself with the link above
function _transferFrom(address from, address to, uint256 tokenId) internal {
// TODO: require from address is the owner of the given token
require(from == ownerOf(tokenId), "The from address must be the owner of the given token");
// TODO: require token is being transfered to valid address
require(to != address(0), "Invalid address used here");
// TODO: clear approval
delete _tokenApprovals[tokenId];
// TODO: update token counts & transfer ownership of the token ID
_tokenOwner[tokenId] = to;
_ownedTokensCount[from].decrement;
_ownedTokensCount[to].increment;
// TODO: emit correct event
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* The call is not executed if the target address is not a contract
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
// @dev Private function to clear current approval of a given token ID
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
contract ERC721Enumerable is ERC165, ERC721 {
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/*
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
/**
* @dev Constructor function
*/
constructor () public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
require(index < balanceOf(owner));
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply());
return _allTokens[index];
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
super._transferFrom(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
_addTokenToAllTokensEnumeration(tokenId);
}
/**
* @dev Gets the list of token IDs of the requested owner
* @param owner address owning the tokens
* @return uint256[] List of token IDs owned by the requested address
*/
function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
return _ownedTokens[owner];
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the _ownedTokensIndex mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length.sub(1);
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
contract ERC721Metadata is ERC721Enumerable, usingOraclize {
// TODO: Create private vars for token _name, _symbol, and _baseTokenURI (string)
string private _name;
string private _symbol;
string private _baseTokenURI;
// TODO: create private mapping of tokenId's to token uri's called '_tokenURIs'
mapping (uint256 => string) private _tokenURIs;
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
constructor (string memory name, string memory symbol, string memory baseTokenURI) public {
// TODO: set instance var values
_name = name;
_symbol = symbol;
_baseTokenURI = baseTokenURI;
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
// TODO: create external getter functions for name, symbol, and baseTokenURI
function name() external view returns(string memory) {
return _name;
}
function symbol() external view returns(string memory) {
return _symbol;
}
function baseTokenURI() external view returns(string memory) {
return _baseTokenURI;
}
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId));
return _tokenURIs[tokenId];
}
// TODO: Create an internal function to set the tokenURI of a specified tokenId
// It should be the _baseTokenURI + the tokenId in string form
// TIP #1: use strConcat() from the imported oraclizeAPI lib to set the complete token URI
// TIP #2: you can also use uint2str() to convert a uint to a string
// see https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol for strConcat()
// require the token exists before setting
function setTokenURI(uint256 tokenId)
internal {
require(tokenId != 0, "The Token ID is required here");
_tokenURIs[tokenId] = strConcat(_baseTokenURI, uint2str(tokenId));
}
}
// TODO's: Create CustomERC721Token contract that inherits from the ERC721Metadata contract. You can name this contract as you please
// 1) Pass in appropriate values for the inherited ERC721Metadata contract
// - make the base token uri: https://s3-us-west-2.amazonaws.com/udacity-blockchain/capstone/
// contract CustomERC721Token is ERC721Metadata("Real Estate Marketplace", "CAPSTONE", "https://s3-us-west-2.amazonaws.com/udacity-blockchain/capstone/") {
contract IntREstellarToken is ERC721Metadata("Real Estate Marketplace", "CAPSTONE", "https://s3-us-west-2.amazonaws.com/udacity-blockchain/capstone/") {
// 2) create a public mint() that does the following:
// -can only be executed by the contract owner
// -takes in a 'to' address, tokenId, and tokenURI as parameters
// -returns a true boolean upon completion of the function
// -calls the superclass mint and setTokenURI functions
function mint(address to, uint256 tokenId) public onlyOwner returns (bool){
super._mint(to, tokenId);
super.setTokenURI(tokenId);
return true;
}
}