-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUpdates
548 lines (458 loc) · 19.7 KB
/
Updates
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
---> (5.2)
As we updated this course with latest version of truffle, openzeppelin and ipfs, we no more need to clone the project directory from the github link shown in the video. Proceed as follows:
1. install truffle, ganache-cli and solidity compiler:
-->npm install -g truffle ganache-cli solc
2. create new project directory
-->mkdir nft-dapp-starter-project
-->cd nft-dapp-starter-project
-->truffle unbox webpack
-->ls
-->cd contracts
-->rm ConvertLib.sol MetaCoin.sol
3. Now we include following files in the app/src directory
-->cd app/src
--> Sir here, give links to the following files:
app.css
bootstrap.min.css
create-nft.html
flask-loader.svg
random-graph.js
svg-crowbar.js
---> (5.4)
00:22 - The course has been updated to use solidity version 0.5.3. You can specify the contract version like below instead of 0.4.24.
pragma solidity >=0.5.0 <0.6.0;
01:06 - Now we are using updated version of openzeppelin. So there are some changes in it, like ERC721Token file changed to ERC721Full. So inherit it like below.
contract RandomGraphToken is ERC721Full {
}
01:14 - import ERC721Full file like below given.
import "./../app/node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol";
01:31 - declare constructor like this.
constructor() public ERC721Full("Graph Art Token", "GAT") {
}
---> (5.6)
01:05 - Add the memory keyword to the _graphAttributes in the createUniqueArt function because the solidity compiler now requires that you explicitly specify it. It should look like this: uint[9] memory _graphAttributes.
02:39 - There is a typo here. It should be: abi.encodePacked.
---> (5.9)
01:28 - truffle webpack box has changed now. So there is a file truffle-config.js instead of truffle.js. Your truffle-config.js should looks like below: Sir display/add file here. We also need to configure truffle to use solidity compiler >= v0.5.3, which you can see in truffle-config.js.
Truffle console commands:
> RandomGraphToken.deployed().then((f) => f.createUniqueArt(web3.utils.asciiToHex('BalancedTree'), 50, 20, [2,5,0,0,0,0,0,0,0]).then((f) => {console.log(f)}))
> RandomGraphToken.deployed().then((f) => f.ownerOf.call(1).then((f) => {console.log(f)}))
> var accounts;
> web3.eth.getAccounts((err, res) => {accounts = res;})
> var account1 = accounts[0]
> account1
> RandomGraphToken.deployed().then((f) => f.balanceOf.call(account1).then((f) => {console.log(f.toNumber())}))
> RandomGraphToken.deployed().then((f) => f.createUniqueArt(web3.utils.asciiToHex('BalancedTree'), 50, 20, [2,5,0,0,0,0,0,0,0]).then((f) => {console.log(f)}))
>RandomGraphToken.deployed().then((f) => f.createUniqueArt(web3.utils.asciiToHex('BalancedTree'), 70, 20, [2,5,0,0,0,0,0,0,0]).then((f) => {console.log(f)}))
---> (6.1)
00:06 - Go into app and then run npm run dev
00.57 - The webpack.config.js file should looks like this now:
-->Sir add updated webpack.config.js file here to copy/paste.
---> (6.3)
-->The code is significantly simpler now because we don't have to use then() method chaining. Instead, we can use await to wait for calls to complete and return values.
import "./app.css";
import Web3 from "web3";
import randomGraphTokenArtifact from "../../build/contracts/RandomGraphToken.json";
const ipfsAPI = require('ipfs-api');
const ipfs = ipfsAPI({host: 'ipfs.infura.io', port: '5001', protocol: 'https'});
const App = {
web3: null,
account: null,
randomGraphToken: null,
contractAddress: null,
start: async function() {
const { web3 } = this;
try {
// get contract instance
const networkId = await web3.eth.net.getId();
const deployedNetwork = randomGraphTokenArtifact.networks[networkId];
this.contractAddress = deployedNetwork.address;
this.randomGraphToken = new web3.eth.Contract(
randomGraphTokenArtifact.abi,
deployedNetwork.address,
);
// get accounts
const accounts = await web3.eth.getAccounts();
this.account = accounts[0];
} catch (error) {
console.log(error);
console.error("Could not connect to contract or chain.");
}
},
createNFT: async function() {
var blob = saveSVG();
console.log(blob);
var reader = new window.FileReader();
reader.readAsArrayBuffer(blob);
setTimeout(function() {
var val = Buffer.from(reader.result);
const data = {path: 'graph.svg', content: val}
ipfs.add(data, {wrapWithDirectory: true})
.then((response) => {
console.log(response);
})
}, 5000);
},
};
window.App = App;
window.addEventListener("load", function() {
if (window.ethereum) {
// use MetaMask's provider
App.web3 = new Web3(window.ethereum);
window.ethereum.enable(); // get permission to access accounts
} else {
console.warn(
"No web3 detected. Falling back to http://127.0.0.1:9545. You should remove this fallback when you deploy live",
);
// fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
App.web3 = new Web3(
new Web3.providers.HttpProvider("http://127.0.0.1:8545"),
);
}
App.start();
});
---> (6.4)
-->You can find the relevant functions with modifications below
createNFT: async function() {
var blob = saveSVG();
console.log(blob);
var reader = new window.FileReader();
reader.readAsArrayBuffer(blob);
setTimeout(function() {
var val = Buffer.from(reader.result);
const data = {path: 'graph.svg', content: val}
ipfs.add(data, {wrapWithDirectory: true})
.then((response) => {
console.log(response);
App.uploadJSONMetaData("https://ipfs.io/ipfs/" + response[1].hash + "/graph.svg");
})
}, 5000);
},
uploadJSONMetaData: async function(imageURL) {
let jsonData = {
"title": "Asset Metadata",
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Random Graph Token"
},
"description": {
"type": "string",
"description": "NFT to represent Random Graph"
},
"image": {
"type": "string",
"description": imageURL
}
}
}
ipfs.add(Buffer.from(JSON.stringify(jsonData))).then(function(value) {
console.log("hash",value);
});
},
---> (6.5)
00:09 - Add the memory keyword to the _tokenURI in the createUniqueArt function because the solidity compiler now requires that you explicitly specify it. It should look like this: string memory _tokenURI.
uploadJSONMetaData: async function(imageURL) {
let jsonData = {
"title": "Asset Metadata",
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Random Graph Token"
},
"description": {
"type": "string",
"description": "NFT to represent Random Graph"
},
"image": {
"type": "string",
"description": imageURL
}
}
}
ipfs.add(Buffer.from(JSON.stringify(jsonData))).then(function(value) {
console.log("hash",value);
App.createToken("https://ipfs.io/ipfs/" + value[0].hash);
});
},
createToken: async function(metaDataURL) {
const { web3 } = this;
var attributes = App.parseGraphAttributes();
const { createUniqueArt } = this.randomGraphToken.methods;
createUniqueArt(web3.utils.asciiToHex(attributes.graphType), attributes.charge, attributes.linkDistance,
attributes.graphVars, metaDataURL).send({gas: 4700000, from: this.account});
console.log("Token successfully created");
},
parseGraphAttributes: function() {
var e = document.getElementById("graph-type");
var graphType = e.options[e.selectedIndex].value;
var charge = $("#charge-dist").html();
var linkDistance = $("#link-dist").html();
var textFields = $("#params input");
var r = 0; //Sir I initialized all 9 of these variable with Zero because i got error with null
var h = 0;
var n = 0;
var mo = 0;
var m = 0;
var p = 0;
var k = 0;
var alpha = 0;
var beta = 0;
if (graphType == 'BalancedTree') {
r = parseInt(textFields[0].value); //then finally parse it as integer because in our contract it takes unit[9] as argument
h = parseInt(textFields[1].value);
} else if (graphType == 'BarabasiAlbert') {
n = parseInt(textFields[0].value);
mo = parseInt(textFields[1].value);
m = parseInt(textFields[2].value);
} else if (graphType == 'ErdosRenyi.np') {
n = parseInt(textFields[0].value);
p = parseInt(textFields[1].value);
} else if (graphType == 'ErdosRenyi.nm') {
n = parseInt(textFields[0].value);
m = parseInt(textFields[1].value);
} else if (graphType == 'WattsStrogatz.alpha') {
n = parseInt(textFields[0].value);
k = parseInt(textFields[1].value);
alpha = parseInt(textFields[2].value);
} else if (graphType == 'WattsStrogatz.beta') {
n = parseInt(textFields[0].value);
k = parseInt(textFields[1].value);
beta = parseInt(textFields[2].value);
}
return {
graphType: graphType,
charge: charge,
linkDistance: linkDistance,
graphVars: [r, h, n, mo, m, p, k, alpha, beta]
}
}
---> (6.7)
-->add this line in the try block at the end:
await this.renderToken();
renderToken: async function() {
const { web3 } = this;
const { totalSupply } = this.randomGraphToken.methods;
var numberOfNFTs = await totalSupply().call();
for(var i=0; i<numberOfNFTs; i++) {
const { tokenByIndex } = this.randomGraphToken.methods;
var id = await tokenByIndex(i).call();
const { tokenURI } = this.randomGraphToken.methods;
var uri = await tokenURI(id).call();
setTimeout(function() {
$.getJSON(uri, function(data) {
App.displayToken(id, data, uri);
});
}, 10000); //here i give 10 sec because it is taking long time to load the image from ipfs
}
},
displayToken: async function(tokenId, metaData, uri) {
var node = $("<div/>");
node.addClass("col-sm-3 text-center col-margin-bottom-1 product");
node.append("<img src='" + metaData.properties.image.description + "' />");
node.append("<a href='" + metaData.properties.image.description + "' target='_blank'>Full Size</a>");
node.append("<br>");
node.append("<a href='" + uri + "' target='_blank'>Metadata</a>");
$("#nft-list").append(node);
},
---> (7.2)
00:40 - constructor should look like this:
constructor(address _tokenAddress) public {
token = ERC721Full(_tokenAddress);
}
01:01 - pragma solidity >=0.5.0 <0.6.0;
import "./../app/node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol";
01:05 - ERC721Full public token;
02:33 - require(token.isApprovedForAll(owner, address(this))); // we have to explicitly convert 'this' into address. I refered this - https://ethereum.stackexchange.com/questions/64868/typeerror-invalid-type-for-argument-in-function-call-invalid-implicit-conversi
---> (7.3)
function buyToken(uint _tokenId) public payable {
//validate the purchase order
//transfer money to token owner
//transfer token to buyer
require(validBuyOrder(_tokenId, msg.value));
address owner = token.ownerOf(_tokenId); //this also changed. i refered this*.
address payable payalableOwner = address(uint160(owner));
payalableOwner.transfer(msg.value);
token.safeTransferFrom(owner, msg.sender, _tokenId);
markTokenAsSold(_tokenId);
emit TokenSold(_tokenId, msg.value);
}
* https://ethereum.stackexchange.com/questions/62222/address-payable-type-store-address-and-send-later-using-solidity-0-5-0/65609#65609
---> (7.5)
renderToken: async function() {
const { web3 } = this;
if(new URLSearchParams(window.location.search).get('filter') === 'owned') {
const { balanceOf } = this.randomGraphToken.methods;
var balance = await balanceOf(this.account).call();
if(balance == 0) {
$("#nft-list").addClass("alert alert-danger").html("You don't have any tokens. Create one now!");
} else {
for(var i=0; i < balance; i++) {
const { tokenOfOwnerByIndex } = this.randomGraphToken.methods;
var id = await tokenOfOwnerByIndex(this.account, i).call();
const { tokenURI } = this.randomGraphToken.methods;
var uri = await tokenURI(id).call();
setTimeout(function() {
$.getJSON(uri, function(data) {
App.displayToken(id, data, uri);
});
}, 10000);
}
}
} else {
const { totalSupply } = this.randomGraphToken.methods;
var numberOfNFTs = await totalSupply().call();
for(var i=0; i<numberOfNFTs; i++) {
const { tokenByIndex } = this.randomGraphToken.methods;
var id = await tokenByIndex(i).call();
const { tokenURI } = this.randomGraphToken.methods;
var uri = await tokenURI(id).call();
setTimeout(function() {
$.getJSON(uri, function(data) {
App.displayToken(id, data, uri);
});
}, 10000);
}
}
},
---> (7.6)
--> To create instance of simpleExchange to as follow:
1. import it - import simpleExchangeArtifact from "../../build/contracts/SimpleExchange.json";
2. initialize the variables - simpleExchange: null,
contractAddress1:null,
3. create contract instance by adding following above "//get accounts" comment in the try block:
const deployedNetwork1 = simpleExchangeArtifact.networks[networkId];
this.contractAddress1 = deployedNetwork1.address;
this.simpleExchange = new web3.eth.Contract(
simpleExchangeArtifact.abi,
deployedNetwork1.address,
);
renderToken: async function() {
const { web3 } = this;
if(new URLSearchParams(window.location.search).get('filter') === 'owned') {
await App.renderExchangeDetails(); //changes
const { balanceOf } = this.randomGraphToken.methods;
var balance = await balanceOf(this.account).call();
if(balance == 0) {
$("#nft-list").addClass("alert alert-danger").html("You don't have any tokens. Create one now!");
} else {
for(var i=0; i < balance; i++) {
const { tokenOfOwnerByIndex } = this.randomGraphToken.methods;
var id = await tokenOfOwnerByIndex(this.account, i).call();
const { tokenURI } = this.randomGraphToken.methods;
var uri = await tokenURI(id).call();
setTimeout(function() {
$.getJSON(uri, function(data) {
App.displayToken(id, data, uri);
});
}, 10000);
}
}
} else {
$("#approve-div").hide(); //changes
const { totalSupply } = this.randomGraphToken.methods;
var numberOfNFTs = await totalSupply().call();
for(var i=0; i<numberOfNFTs; i++) {
const { tokenByIndex } = this.randomGraphToken.methods;
var id = await tokenByIndex(i).call();
const { tokenURI } = this.randomGraphToken.methods;
var uri = await tokenURI(id).call();
setTimeout(function() {
$.getJSON(uri, function(data) {
App.displayToken(id, data, uri);
});
}, 10000);
}
}
},
renderExchangeDetails: async function() {
const { web3 } = this;
const { isApprovedForAll } = this.randomGraphToken.methods;
var approved = await isApprovedForAll(this.account, App.simpleExchange._address).call();
if(approved == true) {
$("#msg").addClass("alert alert-success").html("You have approved the exchange to sell tokens on your behalf!");
$("#approve-div").hide();
} else {
$("#msg").addClass("alert alert-danger").html("Approve the exchange to sell tokens on your behalf");
}
},
setApproval: async function() {
const { web3 } = this;
const { setApprovalForAll } = this.randomGraphToken.methods;
await setApprovalForAll(App.simpleExchange._address, true).send({gas: 4700000, from: this.account});
alert("You have successfully approved the exchange to sell tokens on your behalf!");
location.reload();
},
---> (7.7)
displayToken: async function(tokenId, metaData, uri) {
const { web3 } = this;
var node = $("<div/>");
node.addClass("col-sm-3 text-center col-margin-bottom-1 product");
node.append("<img src='" + metaData.properties.image.description + "' />");
node.append("<a href='" + metaData.properties.image.description + "' target='_blank'>Full Size</a>");
node.append("<br>");
node.append("<a href='" + uri + "' target='_blank'>Metadata</a>");
const { isApprovedForAll } = this.randomGraphToken.methods;
var approved = await isApprovedForAll(this.account, App.simpleExchange._address).call();
if(approved == true) {
await App.renderPriceBox(tokenId, node);
}
$("#nft-list").append(node);
},
renderPriceBox: async function(tokenId, node) {
const { web3 } = this;
const { listingPrice } = this.simpleExchange.methods;
var result = await listingPrice(tokenId).call();
if(result > 0) {
var price = await listingPrice(tokenId).call();
node.append("<div>Token sale for " + web3.utils.fromWei(price, 'ether') + " Ether</div>");
} else {
node.append("<div><input id='token-" + tokenId + "' placeholder='0.1'><a href='#' class='btn btn-primary list-token' onclick='App.listingToken(" + tokenId + "); return false;' data-token='" + tokenId + "'>List for Sale</a></div>");
}
},
listingToken: async function(tokenId) {
const { web3 } = this;
const { listToken } = App.simpleExchange.methods;
var price = $("#token-" + tokenId).val();
await listToken(tokenId, web3.utils.toWei(price, 'ether')).send({gas: 4700000, from: this.account});
alert("Your NFT has been listed for sale!");
location.reload("/");
},
---> (7.8)
displayToken: async function(tokenId, metaData, uri) {
const { web3 } = this;
var node = $("<div/>");
node.addClass("col-sm-3 text-center col-margin-bottom-1 product");
node.append("<img src='" + metaData.properties.image.description + "' />");
node.append("<a href='" + metaData.properties.image.description + "' target='_blank'>Full Size</a>");
node.append("<br>");
node.append("<a href='" + uri + "' target='_blank'>Metadata</a>");
const { isApprovedForAll } = this.randomGraphToken.methods;
var approved = await isApprovedForAll(this.account, App.simpleExchange._address).call();
if(approved == true) {
await App.renderPriceBox(tokenId, node);
} else {
const { listingPrice } = this.simpleExchange.methods;
var result = await listingPrice(tokenId).call();
if(result > 0) {
await App.renderPurchaseButton(tokenId, node);
}
}
$("#nft-list").append(node);
},
renderPurchaseButton: async function(tokenId, node) {
const { web3 } = this;
const { listingPrice } = this.simpleExchange.methods;
var price = await listingPrice(tokenId).call();
var etherPrice = web3.utils.fromWei(price, 'ether');
node.append("<div><a href='#' class='btn btn-primary buy-token' onclick='App.buyingToken(" + tokenId + ", " + price + "); return false;' data-token='" + tokenId + "' data-price='" + price + "'>Buy for " + etherPrice + "Ether </a></div>");
},
buyingToken: async function(tokenId, price) {
const { web3 } = this;
const { buyToken } = this.simpleExchange.methods;
await buyToken(tokenId).send({gas: 4700000, value: price,from: this.account});
alert("You have successfully purchased the NFT!");
location.reload("/");
},