-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
1769 lines (1432 loc) · 61.5 KB
/
app.js
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*********************************************************************************
* The MIT License (MIT) *
* *
* Copyright (c) 2021 KMi, The Open University UK *
* *
* Permission is hereby granted, free of charge, to any person obtaining *
* a copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the Software *
* is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN *
* THE SOFTWARE. *
* *
**********************************************************************************/
let quadsFinal = "";
let metadata = ""
let metadata2 = ""
let linkchains = {}
let ethereum = {}
let account = "";
let provider = {};
let signer = {};
let ipfscache = {};
let tokencache = {};
let contractcache = {};
/**
* Initialise buttons clicks, metmask / ethereum etc.
*/
async function initLinkchain() {
totalTabs = document.getElementById("thedemotabs").getElementsByTagName("li").length;
// reference linkchains
linkchains = window.linkchains();
console.log(linkchains);
// connect this webpage to ethereum through metamask
setUpEthereumAndMetamask();
// prepopulate the network selection
const networkSelect = document.getElementById('networks');
const availableNetworks = cfg.tokenContractAddresses;
let option, next;
let count = availableNetworks.length;
option = document.createElement('option');
option.setAttribute('value', 'none');
option.appendChild(document.createTextNode("Select which network to publish to"));
networkSelect.appendChild(option);
for (let i=0; i < count; i++) {
next = availableNetworks[i];
option = document.createElement('option');
option.setAttribute('value', next.tokenContractAddress);
option.appendChild(document.createTextNode(next.network));
networkSelect.appendChild(option);
}
await selectNetwork();
// prepopulate the token icon with the default
document.getElementById('tokenImageURL').value = cfg.tokenIconURL;
// detect change of solid pod url and update various urls stubs and local storage
const podURLInput = document.getElementById("PodURL");
podURLInput.onchange = function() {
let data = this.value;
if (data == "") {
data = '<span style="color:gray">Please add Solid Pod URL on tab 1</span>';
}
document.getElementById("verificationMetadataStub").innerHTML = data;
document.getElementById("anchorMetadataStub").innerHTML = data;
document.getElementById("anchorMetadataTokenStub").innerHTML = data;
document.getElementById("granularVerificationMetadataStub").innerHTML = data;
localStorage.setItem("podurl", data);
};
// pull out of storage the previously saved podurl
if (localStorage.getItem("podurl")) {
podURLInput.value = localStorage.getItem("podurl");
podURLInput.onchange();
}
/**** WIRE UP BUTTON ON CLICK FUNCTIONS *****/
const ethereumButton = document.getElementById('enableEthereumButton');
ethereumButton.onclick = async function() {
loginToMetaMask();
};
/* BUTTONS THAT READ IN A LOCAL FILE */
const readFileDataButton = document.querySelector("#readFileDataButton");
readFileDataButton.onclick = function() {
readLocalInputData('fileoftriples', 'inputarea', ['anchoredRDFInputArea', 'validateRDFInputArea', 'validateGranularRDFInputArea']);
};
// merql contract anchoring
const readVerificationMetadataFileButton = document.querySelector("#readVerificationMetadataFileButton");
readVerificationMetadataFileButton.onclick = async function() {
readLocalInputData('verificationMetadataFile', 'verificationMetadataInputArea', []);
};
// token contract anchoring
const readVerificationMetadataTokenFileButton = document.querySelector("#readVerificationMetadataTokenFileButton");
readVerificationMetadataTokenFileButton.onclick = async function() {
readLocalInputData('verificationMetadataTokenFile', 'verificationMetadataTokenInputArea', []);
};
// Granular
const granularRDFInputFileButton = document.querySelector("#granularRDFInputFileButton");
granularRDFInputFileButton.onclick = async function() {
readLocalInputData('granularRDFInputFile', 'anchoredRDFInputArea', []);
};
const anchoredMetadataInputAreaButton = document.querySelector("#anchoredMetadataInputAreaButton");
anchoredMetadataInputAreaButton.onclick = async function() {
readLocalInputData('anchoredMetadataInputAreaFile', 'anchoredMetadataInputArea', []);
};
// Validation
const validateRDFInputFileButton = document.querySelector("#validateRDFInputFileButton");
validateRDFInputFileButton.onclick = async function() {
readLocalInputData('validateRDFInputFile', 'validateRDFInputArea', []);
};
const validateAnchoredMetadataInputFileButton = document.querySelector("#validateAnchoredMetadataInputFileButton");
validateAnchoredMetadataInputFileButton.onclick = async function() {
readLocalInputData('validateAnchoredMetadataInputFile', 'anchoredMetadataValidationInputArea', []);
};
// Granular Validation
const validateGranularRDFInputButton = document.querySelector("#validateGranularRDFInputButton");
validateGranularRDFInputButton.onclick = async function() {
readLocalInputData('validateGranularRDFInputFile', 'validateGranularRDFInputArea', []);
};
const granularMetadataValidationInputButton = document.querySelector("#granularMetadataValidationInputButton");
granularMetadataValidationInputButton.onclick = async function() {
readLocalInputData('granularMetadataValidationInputFile', 'granularMetadataValidationInputArea', []);
};
/* BUTTONS THAT SAVE TO A LOCAL FILE */
const storeLocallyVerificationMetadataButton = document.querySelector("#storeLocallyVerificationMetadataButton");
storeLocallyVerificationMetadataButton.onclick = async function() {
saveToFile('verificationMetadataResult');
};
const storeLocallyAnchorMetadataButton = document.querySelector("#storeLocallyAnchorMetadataButton");
storeLocallyAnchorMetadataButton.onclick = async function() {
saveToFile('anchorMetadataResult');
};
const storeLocallyAnchorMetadataTokenButton = document.querySelector("#storeLocallyAnchorMetadataTokenButton");
storeLocallyAnchorMetadataTokenButton.onclick = async function() {
saveToFile('anchorMetadataTokenResult');
};
const storeLocallyGanularMetadataButton = document.querySelector("#storeLocallyGanularMetadataButton");
storeLocallyGanularMetadataButton.onclick = async function() {
saveToFile('granularVerificationMetadataResult');
};
/* LINKCHAIN RELATED BUTTONS */
const verificationMetaDataButton = document.getElementById('verificationMetadataButton');
verificationMetaDataButton.onclick = function() {
getVerificationMetadata();
};
const anchorMetadataButton = document.getElementById('anchorMetadataButton');
anchorMetadataButton.onclick = function() {
anchorMetadata();
};
const anchorMetadataTokenButton = document.getElementById('anchorMetadataTokenButton');
anchorMetadataTokenButton.onclick = function() {
anchorMetadataWithToken();
};
const granularVerificationMetaDataButton = document.getElementById('granularVerificationMetadataButton');
granularVerificationMetaDataButton.onclick = function() {
getGranularVerificationMetadata();
};
const validateButton = document.getElementById('validateButton');
validateButton.onclick = function() {
validate();
};
const validateGranularButton = document.getElementById('validateGranularButton');
validateGranularButton.onclick = function() {
validateGranular();
};
// ADMIN - ISSUE TOKEN CONTRACT INSTANCE
const tokenContractButton = document.getElementById('tokenContractButton');
tokenContractButton.onclick = async function() {
let result = await deployTokenAnchorContract('tokenContractOutput');
document.getElementById('tokenContractOutput').value = JSON.stringify(result, null, 2);
};
//const clearButton = document.getElementById('clearButton');
//clearButton.onclick = function() {
// clearAll();
//};
/* NAVIGATION BUTTONS */
const nextButton = document.getElementById('ntxbtn');
nextButton.onclick = function(e) {
try {
e.preventDefault();
const acollection = document.getElementsByClassName("nav-link active"); // currently active tab anchor - should only be 1
const currentLi = acollection[0].parentElement;
const nextLi = currentLi.nextElementSibling;
const nodes = Array.prototype.slice.call( document.getElementById('thedemotabs').children );
currentTab = nodes.indexOf(currentLi);
currentTab +=1;
if (nextLi != null) {
nextLi.firstElementChild.click();
}
showHideControls();
} catch (error) {
console.log(e);
}
};
const previousButton = document.getElementById('prevbtn');
previousButton.onclick = function(e) {
try {
e.preventDefault();
const acollection = document.getElementsByClassName("nav-link active"); // currently active tab anchor - should only be 1
const currentLi = acollection[0].parentElement;
const previousLi = currentLi.previousElementSibling;
const nodes = Array.prototype.slice.call( document.getElementById('thedemotabs').children );
currentTab = nodes.indexOf(previousLi);
currentTab -=1;
if (previousLi != null) {
previousLi.firstElementChild.click();
}
showHideControls();
} catch (error) {
console.log(e);
}
};
/* INRUPT/SOLID RELATED BUTTONS */
/* Tab to connect to Solid and view files */
const solidLoginButton = document.querySelector("#solidLoginButton");
solidLoginButton.onclick = function() {
const oidcIssuerUrl = document.getElementById("oidcIssuer").value;
if (oidcIssuerUrl == null || oidcIssuerUrl == "") {
alert("Please add the url of where to login to your Solid pod");
} else {
Inrupt.startSolidLogin(oidcIssuerUrl, "ISWS Summer School Demo - 2022");
}
};
const solidLogoutButton = document.querySelector("#solidLogoutButton");
solidLogoutButton.onclick = function() {
Inrupt.solidLogout();
};
const readFileFromSolidButton = document.querySelector("#readFileFromSolidButton");
readFileFromSolidButton.onclick = async function() {
try {
const podUrl = document.getElementById("PodURL").value;
const allFolderArray = await Inrupt.loadFolderContentList(podUrl);
const filesArea = document.getElementById("filesArea");
let allFiles = ""
allFolderArray.forEach(function(filename) {
allFiles += filename+'\n';
});
filesArea.value = allFiles;
} catch (error) {
console.log(error);
alert(error.message);
}
};
/* Tab to get Verification Metadata for some RDF Input */
const readSolidDataButton = document.querySelector("#readSolidDataButton");
readSolidDataButton.onclick = async function() {
const fileURL = document.getElementById("solidFileURL").value;
const file = await Inrupt.readFileFromPod(fileURL);
//console.log(file);
let reader = new FileReader();
reader.readAsText(file);
reader.onload = function() {
//console.log(reader.result);
const inputarea = document.getElementById('inputarea');
inputarea.value = reader.result;
};
};
const saveFileDataButton = document.querySelector("#saveFileDataButton");
saveFileDataButton.onclick = async function() {
try {
const podUrl = document.getElementById("PodURL").value;
const file = document.getElementById('fileoftriples').files[0];
if (file) {
const filePodURL = podUrl+file.name;
await Inrupt.writeFileToPod(file, `${filePodURL}`);
const solidFileURLField = document.getElementById("solidFileURL").value = filePodURL;
}
} catch (error) {
console.log(error);
alert(error.message);
}
}
const storeVerificationMetadataButton = document.querySelector("#storeVerificationMetadataButton");
storeVerificationMetadataButton.onclick = async function() {
try {
const data = document.getElementById("verificationMetadataResult").value;
if (data == "") {
alert("Please load some data into the textarea to store to solid");
return;
}
const title = document.getElementById("verificationMetadataTitle").value;
if (title == "") {
alert("Please give this dataset a title to use in Solid");
return;
}
const filename = title.replace(/[^\-a-z0-9]/gi, '_').toLowerCase();
const pathToStore = document.getElementById("PodURL").value+filename+'.jsonld';
const filetype = 'text/plain'; // must be this or fails - no idea why
const blob = new Blob([data], { type: filetype });
const file = new File([blob], filename, { type: filetype });
const fileurl = await Inrupt.writeFileToPod(file, pathToStore);
document.getElementById("verificationMetadataSolidURLResult").innerHTML = fileurl;
document.getElementById("verificationMetadataInputURL").value = fileurl;
document.getElementById("verificationMetadataTokenInputURL").value = fileurl;
} catch (error) {
console.log(error);
alert(error.message);
}
};
/* Tab to Anchor Verification Metadata to the Blockchain */
const saveVerificationMetadataFileButton = document.querySelector("#saveVerificationMetadataFileButton");
saveVerificationMetadataFileButton.onclick = async function() {
try {
const podUrl = document.getElementById("PodURL").value;
const file = document.getElementById('verificationMetadataFile').files[0];
if (file) {
const filePodURL = podUrl+file.name;
await Inrupt.writeFileToPod(file, `${filePodURL}`);
const solidFileURLField = document.getElementById("verificationMetadataInputURL").value = filePodURL;
}
} catch (error) {
console.log(error);
alert(error.message);
}
}
const readVerificationMetadataButton = document.querySelector("#readVerificationMetadataButton");
readVerificationMetadataButton.onclick = async function() {
const fileURL = document.getElementById("verificationMetadataInputURL").value;
const file = await Inrupt.readFileFromPod(fileURL);
let reader = new FileReader();
reader.readAsText(file);
reader.onload = function() {
const inputarea = document.getElementById('verificationMetadataInputArea');
inputarea.value = reader.result;
};
}
const storeAnchorMetadataButton = document.querySelector("#storeAnchorMetadataButton");
storeAnchorMetadataButton.onclick = async function() {
try {
const data = document.getElementById("anchorMetadataResult").value;
if (data == "") {
alert("Please load some data into the textarea to store to solid");
return;
}
const title = document.getElementById("anchorMetadataTitle").value;
if (title == "") {
alert("Please give this dataset a title to use in Solid");
return;
}
const filename = title.replace(/[^\-a-z0-9]/gi, '_').toLowerCase();
const pathToStore = document.getElementById("PodURL").value+filename+'.jsonld';
const filetype = 'text/plain'; // must be this or fails - no idea why
const blob = new Blob([data], { type: filetype });
const file = new File([blob], filename, { type: filetype });
const fileurl = await Inrupt.writeFileToPod(file, pathToStore);
document.getElementById("anchorMetadataSolidURLResult").innerHTML = fileurl;
document.getElementById("anchoredMetadataInputURL").value = fileurl;
} catch (error) {
console.log(error);
alert(error.message);
}
};
/* Tab to Anchor Verification Metadata to the Blockchain with Tokens */
const saveVerificationMetadataTokenFileButton = document.querySelector("#saveVerificationMetadataTokenFileButton");
saveVerificationMetadataTokenFileButton.onclick = async function() {
try {
const podUrl = document.getElementById("PodURL").value;
const file = document.getElementById('verificationMetadataTokenFile').files[0];
if (file) {
const filePodURL = podUrl+file.name;
await Inrupt.writeFileToPod(file, `${filePodURL}`);
const solidFileURLField = document.getElementById("verificationMetadataTokenInputURL").value = filePodURL;
}
} catch (error) {
console.log(error);
alert(error.message);
}
}
const readVerificationMetadataTokenButton = document.querySelector("#readVerificationMetadataTokenButton");
readVerificationMetadataTokenButton.onclick = async function() {
const fileURL = document.getElementById("verificationMetadataTokenInputURL").value;
const file = await Inrupt.readFileFromPod(fileURL);
let reader = new FileReader();
reader.readAsText(file);
reader.onload = function() {
const inputarea = document.getElementById('verificationMetadataTokenInputArea');
inputarea.value = reader.result;
};
}
const storeAnchorMetadataTokenButton = document.querySelector("#storeAnchorMetadataTokenButton");
storeAnchorMetadataTokenButton.onclick = async function() {
try {
const data = document.getElementById("anchorMetadataTokenResult").value;
if (data == "") {
alert("Please load some data into the textarea to store to solid");
return;
}
const title = document.getElementById("anchorMetadataTokenTitle").value;
if (title == "") {
alert("Please give this dataset a title to use in Solid");
return;
}
const filename = title.replace(/[^\-a-z0-9]/gi, '_').toLowerCase();
const pathToStore = document.getElementById("PodURL").value+filename+'.jsonld';
const filetype = 'text/plain'; // must be this or fails - no idea why
const blob = new Blob([data], { type: filetype });
const file = new File([blob], filename, { type: filetype });
const fileurl = await Inrupt.writeFileToPod(file, pathToStore);
document.getElementById("anchorMetadataTokenSolidURLResult").innerHTML = fileurl;
document.getElementById("anchoredMetadataInputURL").value = fileurl;
} catch (error) {
console.log(error);
alert(error.message);
}
};
/* Tab to get Granular Metadata to allow per triple/quad verification */
const readAnchoredRDFInputButton = document.querySelector("#readAnchoredRDFInputButton");
readAnchoredRDFInputButton.onclick = async function() {
const fileURL = document.getElementById("anchoredRDFInputURL").value;
const file = await Inrupt.readFileFromPod(fileURL);
let reader = new FileReader();
reader.readAsText(file);
reader.onload = function() {
const inputarea = document.getElementById('anchoredRDFInputArea');
inputarea.value = reader.result;
};
}
const readAnchoredMetadataButton = document.querySelector("#readAnchoredMetadataButton");
readAnchoredMetadataButton.onclick = async function() {
const fileURL = document.getElementById("anchoredMetadataInputURL").value;
const file = await Inrupt.readFileFromPod(fileURL);
let reader = new FileReader();
reader.readAsText(file);
reader.onload = function() {
const inputarea = document.getElementById('anchoredMetadataInputArea');
inputarea.value = reader.result;
};
}
const storeGanularMetadataButton = document.querySelector("#storeGanularMetadataButton");
storeGanularMetadataButton.onclick = async function() {
try {
const data = document.getElementById("granularVerificationMetadataResult").value;
if (data == "") {
alert("Please load some data into the textarea to store to solid");
return;
}
const title = document.getElementById("granularVerificationMetadataTitle").value;
if (title == "") {
alert("Please give this dataset a title to use in Solid");
return;
}
let filename = title.replace(/[^\-a-z0-9]/gi, '_').toLowerCase();
filename = filename+'.jsonld';
const pathToStore = document.getElementById("PodURL").value+filename;
const filetype = 'text/plain'; // must be this or fails - no idea why
const blob = new Blob([data], { type: filetype });
const file = new File([blob], filename, { type: filetype });
const fileurl = await Inrupt.writeFileToPod(file, pathToStore);
document.getElementById("granularVerificationMetadataSolidURLResult").innerHTML = fileurl;
} catch (error) {
console.log(error);
alert(error.message);
}
};
/* Tab to Validate with anchored metadata */
const readValidateRDFInputButton = document.querySelector("#readValidateRDFInputButton");
readValidateRDFInputButton.onclick = async function() {
const fileURL = document.getElementById("validateRDFInputURL").value;
const file = await Inrupt.readFileFromPod(fileURL);
let reader = new FileReader();
reader.readAsText(file);
reader.onload = function() {
const inputarea = document.getElementById('validateRDFInputArea');
inputarea.value = reader.result;
};
}
const readAnchoredMetadataValidationButton = document.querySelector("#readAnchoredMetadataValidationButton");
readAnchoredMetadataValidationButton.onclick = async function() {
const fileURL = document.getElementById("validateAnchoredMetadataInputURL").value;
const file = await Inrupt.readFileFromPod(fileURL);
let reader = new FileReader();
reader.readAsText(file);
reader.onload = function() {
const inputarea = document.getElementById('anchoredMetadataValidationInputArea');
inputarea.value = reader.result;
};
}
/* Tab to Validate with Granular metadata */
const readValidateGranularRDFInputButton = document.querySelector("#readValidateGranularRDFInputButton");
readValidateGranularRDFInputButton.onclick = async function() {
const fileURL = document.getElementById("validateGranularRDFInputURL").value;
const file = await Inrupt.readFileFromPod(fileURL);
let reader = new FileReader();
reader.readAsText(file);
reader.onload = function() {
const inputarea = document.getElementById('validateGranularRDFInputArea');
inputarea.value = reader.result;
};
}
const readGranularMetadataValidationButton = document.querySelector("#readGranularMetadataValidationButton");
readGranularMetadataValidationButton.onclick = async function() {
const fileURL = document.getElementById("validateGranularMetadataInputURL").value;
const file = await Inrupt.readFileFromPod(fileURL);
let reader = new FileReader();
reader.readAsText(file);
reader.onload = function() {
const inputarea = document.getElementById('granularMetadataValidationInputArea');
inputarea.value = reader.result;
};
}
}
/**
* Setup ethereum and metmask.
*/
async function setUpEthereumAndMetamask() {
try {
ethereum = window.ethereum;
// A Web3Provider wraps a standard Web3 provider, which is
// what MetaMask injects as window.ethereum into each page
provider = new ethers.providers.Web3Provider(window.ethereum)
console.log('provider:', provider);
// The MetaMask plugin also allows signing transactions to
// send ether and pay to change state within the blockchain.
// For this, you need the account signer...
signer = provider.getSigner();
console.log('signer:', signer);
// Check if logged into MetaMask already
if (typeof ethereum !== 'undefined') {
// detect Network change and reassign provider and signer, and reselect contract
ethereum.on('chainChanged', async function() {
provider = new ethers.providers.Web3Provider(window.ethereum)
console.log('provider:', provider);
signer = provider.getSigner();
console.log('signer:', signer);
await selectNetwork();
});
// detect an account change
ethereum.on("accountsChanged", () => {
if (account != ethereum.selectedAddress) {
account = ethereum.selectedAddress;
document.getElementById('ethereumaccount').innerHTML = account;
}
});
if (ethereum.isMetaMask) {
console.log('MetaMask is installed');
}
console.log("ethereum.networkVersion: " + ethereum.networkVersion);
console.log("ethereum.selectedAddress: " + ethereum.selectedAddress);
if (ethereum.selectedAddress == "" || ethereum.selectedAddress == null) {
const button = document.getElementById('enableEthereumButton');
button.disabled = false;
} else {
const button = document.getElementById('enableEthereumButton');
button.disabled = true;
enableMetaMaskButtons();
account = ethereum.selectedAddress;
document.getElementById('ethereumaccount').innerHTML = account;
}
} else {
const button = document.getElementById('enableEthereumButton');
button.disabled = false;
console.log('MetaMask needs to be installed');
}
} catch (e) {
throw e;
}
}
/**
* Start the metamask extension for user to login.
*/
async function loginToMetaMask() {
let reply = await ethereum.request({ method: 'eth_requestAccounts' });
if (ethereum.selectedAddress) {
const button = document.getElementById('enableEthereumButton');
button.disabled = true;
enableMetaMaskButtons();
await selectNetwork();
account = ethereum.selectedAddress;
document.getElementById('ethereumaccount').innerHTML = account;
} else {
alert("Please select a MetaMask account to use with this page");
}
}
/**
* Change the selected network on the Token issuing tab selection menu.
*/
async function selectNetwork() {
try {
const networkSelect = document.getElementById('networks');
const currentNetwork = await getNetwork();
const networkName = currentNetwork.name;
const matchName = networkName.charAt(0).toUpperCase() + networkName.slice(1);
for(var i=0; i<networkSelect.options.length; i++) {
if ( networkSelect.options[i].text == matchName ) {
networkSelect.selectedIndex = i;
break;
}
}
} catch (e) {
// just show the two there are, with non selected.
console.log(e);
}
}
/**
* Ask MetaMask for the details of the current network selected.
*/
async function getNetwork() {
try {
// get the chain id of the current blockchain your wallet is pointing at.
const chainId = await signer.getChainId();
//console.log(chainId);
// get the network details for the given chain id.
const network = await provider.getNetwork(chainId);
//console.log(network);
return network;
} catch (e) {
throw e;
}
}
/**
* Ask MetaMask to switch to the network in the networkObj passed in.
*/
async function switchNetwork(networkObj) {
try {
let chainId = networkObj.chainId;
chainId = parseInt(chainId);
const hexChainId = ethers.utils.hexValue(chainId);
await ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: hexChainId}],
});
provider = new ethers.providers.Web3Provider(window.ethereum)
console.log('provider:', provider);
signer = provider.getSigner();
console.log('signer:', signer);
await selectNetwork();
} catch (switchError) {
// This error code indicates that the chain has not been added to MetaMask.
console.log(switchError);
if (switchError.code === 4902) {
throw new Error("The required network is not available in your MetaMask, please add: "+networkObj.name);
} else {
throw new Error("Failed to switch to the network");
}
}
}
/**
* Load RDF data from select file
*/
async function readLocalInputData(filefieldname, inputareaname, prefillAreasArray) {
var filefield = document.getElementById(filefieldname);
if (filefield) {
var file = filefield.files[0];
if (file) {
var reader = new FileReader();
reader.addEventListener("load", async () => {
let input = reader.result;
const inputarea = document.getElementById(inputareaname);
inputarea.value = input;
prefillAreasArray.forEach(function(elementname) {
const nextelement = document.getElementById(elementname);
nextelement.value = input;
});
}, false);
reader.addEventListener('error', () => {
console.error(`Error occurred reading file: ${file.name}`);
});
reader.readAsText(file);
} else {
alert("Please select a file first");
}
} else {
alert("Please select a file first");
}
}
async function saveToFile(inputareaname) {
const inputarea = document.getElementById(inputareaname);
const textToSave = inputarea.value;
const opts = {
types: [{
description: 'Json file',
accept: {'application/json': ['.json']},
}],
};
const fileHandle = await window.showSaveFilePicker(opts);
const fileStream = await fileHandle.createWritable();
await fileStream.write(new Blob([textToSave], {type: 'application/json'}));
await fileStream.close();
}
/**
* Call linkchains passing some triples and get back the verification metadata object for those triples
*/
async function getVerificationMetadata() {
try {
const inputarea = document.getElementById('inputarea');
quadsFinal = inputarea.value;
if (quadsFinal != "" && quadsFinal != null) {
metadata = await linkchains.getVerificationMetadata(quadsFinal, {});
const verificationMetadataResult = document.getElementById('verificationMetadataResult');
verificationMetadataResult.value = JSON.stringify(metadata, null, 2);
// also add to next stage for non solid workflow
const verificationMetadata = document.getElementById('verificationMetadataInputArea');
verificationMetadata.value = JSON.stringify(metadata, null, 2);
// also add to next stage for non solid workflow
const verificationMetadataTokenInputArea = document.getElementById('verificationMetadataTokenInputArea');
verificationMetadataTokenInputArea.value = JSON.stringify(metadata, null, 2);
} else {
alert("Please select a file of RDF first");
}
} catch (e) {
console.log(e);
}
}
/**
* Create the Token Contract on Rinkby - should just be done once - then the address stored in the config
*/
async function deployTokenAnchorContract(resultAreaName) {
const resultAreaNameElement = document.getElementById(resultAreaName);
const abi = cfg.RDFTokenContract.abi;
const bytecode = cfg.RDFTokenContract.bytecode;
try {
// Create an instance of a Contract Factory
const factory = new ethers.ContractFactory(abi, bytecode, signer);
// Pass parameters to the constructor and deploy
const contract = await factory.deploy();
// The address the Contract WILL have once mined
// See: https://ropsten.etherscan.io/address/0x2bd9aaa2953f988153c8629926d22a6a5f69b14e
console.log(contract.address);
// The transaction that was sent to the network to deploy the Contract
// See: https://ropsten.etherscan.io/tx/0x159b76843662a15bd67e482dcfbee55e8e44efad26c5a614245e12a00d4b1a51
console.log(contract.deployTransaction.hash);
resultAreaNameElement.value = "Waiting to be mined....";
// The contract is NOT deployed yet; we must wait until it is mined
await contract.deployed();
// get the transaction receipt from MetaMask
const receipt = await provider.getTransactionReceipt(contract.deployTransaction.hash);
console.log(receipt);
return receipt;
} catch (e) {
console.log(e);
resultAreaNameElement.value = e;
}
}
/**
* This uses the NFT.STORAGE platform to store data on the global IPFS
* https://nft.storage/
* Requires an API token - total request body size limit of 100MB and no more than 30 requests with the same API token within a ten second window else 429 returned
*/
function storeToIPFS(content) {
return new Promise(function (resolve, reject) {
let xhr = new XMLHttpRequest();
xhr.open("POST", cfg.NFT_STORAGE_API_UPLOAD_URL, true);
xhr.setRequestHeader('Authorization', 'Bearer ' + cfg.NFT_STORAGE_API_KEY);
xhr.onload = function (oEvent) {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
var blob = new Blob([content], {type: 'application/json'});
xhr.send(blob);
});
}
/**
* Given a URL to some IPFS Token metadata, read in the data.
*/
function readFromIPFS(url) {
return new Promise(function (resolve, reject) {
// pull it from local cache if you can to save calls to NFT.Storage
if (ipfscache[url] !== undefined) {
resolve(ipfscache[url]);
}
let xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function (oEvent) {
if (this.status >= 200 && this.status < 300) {
ipfscache[url] = this.responseText;
resolve(this.responseText);
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send();
});
}
async function readTokenMetadata(anchor, options) {
//anchor.type
//anchor.address
//anchor.account
//anchor.transactionhash
//anchor.tokenid
const currentNetwork = await getNetwork();
delete currentNetwork._defaultProvider; // we don't want that bit
if (anchor.network && anchor.network.name != currentNetwork.name) {
//alert("Please switch networks. This data was anchored on: "+anchor.network.name);
//throw new Error("Wrong network detected to validate against");
await switchNetwork(anchor.network);
}
const validateResult = document.getElementById('validateResult');
const abi = cfg.RDFTokenContract.abi;
const contractAddress = anchor.address;
// check if it cached first
if (tokencache[contractAddress] !== undefined
&& tokencache[contractAddress][anchor.tokenId] !== undefined) {
return tokencache[contractAddress][anchor.tokenId];
}
try {