-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1065 lines (929 loc) · 36.9 KB
/
Copy pathapp.js
File metadata and controls
1065 lines (929 loc) · 36.9 KB
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
/**
* CertifyNFT — Main Application Logic
* Pure JavaScript (ES6+), no build tools required.
* Uses Ethers.js v6 via CDN.
*/
// ============================================================
// State
// ============================================================
const state = {
provider: null,
signer: null,
address: null,
chainId: null,
contract: null,
compressedImage: null, // base64 data URL
compressedSizeKB: 0,
isConnected: false,
isMinting: false,
firebaseUser: null,
isAuthenticated: false, // true after wallet signature + Firebase auth
};
// Firebase globals (set during init)
let db = null;
let auth = null;
let firebaseEnabled = false;
// ============================================================
// DOM Elements
// ============================================================
const $ = (sel) => document.querySelector(sel);
const $$ = (sel) => document.querySelectorAll(sel);
// ============================================================
// Init
// ============================================================
document.addEventListener('DOMContentLoaded', async () => {
// Set default issue date to today
const today = new Date().toISOString().split('T')[0];
const dateInput = $('#issue-date');
if (dateInput) dateInput.value = today;
// Initialize Firebase if configured
initFirebase();
// Bind events
bindWalletEvents();
bindUploadEvents();
bindFormEvents();
bindGalleryEvents();
// Check if already connected
await checkExistingConnection();
});
// ============================================================
// Firebase Initialization
// ============================================================
function initFirebase() {
if (!CONFIG.FIREBASE ||
!CONFIG.FIREBASE.apiKey ||
CONFIG.FIREBASE.apiKey === 'YOUR_FIREBASE_API_KEY') {
console.info('Firebase not configured — running in on-chain-only mode.');
return;
}
try {
firebase.initializeApp(CONFIG.FIREBASE);
db = firebase.firestore();
auth = firebase.auth();
firebaseEnabled = true;
console.info('Firebase initialized.');
} catch (err) {
console.warn('Firebase init failed:', err);
}
}
// ============================================================
// Firebase Wallet Authentication
// ============================================================
async function authenticateWithFirebase() {
if (!firebaseEnabled) return;
try {
// Ask the user to sign a message proving wallet ownership
const nonce = Math.floor(Math.random() * 1e9);
const timestamp = Date.now();
const message = [
'Sign in to CertifyNFT',
'',
`Wallet: ${state.address}`,
`Timestamp: ${timestamp}`,
`Nonce: ${nonce}`,
].join('\n');
const signature = await state.signer.signMessage(message);
// Verify the signature client-side
const recovered = window.ethers.verifyMessage(message, signature);
if (recovered.toLowerCase() !== state.address.toLowerCase()) {
throw new Error('Signature verification failed');
}
// Sign in anonymously with Firebase, then tag the user with the wallet address
const userCred = await auth.signInAnonymously();
await userCred.user.updateProfile({
displayName: state.address.toLowerCase()
});
// Force token refresh so displayName propagates to security rules (token.name)
await userCred.user.getIdToken(true);
state.firebaseUser = userCred.user;
state.isAuthenticated = true;
showToast('Signed in to CertifyNFT', 'success');
} catch (err) {
if (err.code === 'ACTION_REJECTED' || err.code === 4001 ||
(err.message && err.message.includes('user rejected'))) {
showToast('Signature declined — gallery will load from blockchain only.', 'warning');
} else {
console.warn('Firebase auth failed:', err);
}
state.isAuthenticated = false;
}
}
function signOutFirebase() {
if (!firebaseEnabled || !auth) return;
state.firebaseUser = null;
state.isAuthenticated = false;
auth.signOut().catch(() => {});
}
// ============================================================
// Wallet Connection
// ============================================================
function bindWalletEvents() {
$('#btn-connect').addEventListener('click', handleConnect);
$('#btn-disconnect').addEventListener('click', handleDisconnect);
}
async function checkExistingConnection() {
if (!window.ethereum) return;
try {
const accounts = await window.ethereum.request({ method: 'eth_accounts' });
if (accounts.length > 0) {
await doConnect(accounts[0]);
}
} catch (err) {
console.warn('Could not check existing connection:', err);
}
}
async function handleConnect() {
if (!window.ethereum) {
showToast('MetaMask is not installed. Please install it from metamask.io', 'error');
return;
}
try {
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
await doConnect(accounts[0]);
} catch (err) {
if (err.code === 4001) {
showToast('Connection rejected by user.', 'warning');
} else {
showToast('Failed to connect wallet: ' + err.message, 'error');
}
}
}
async function doConnect(address) {
state.provider = new window.ethers.BrowserProvider(window.ethereum);
state.signer = await state.provider.getSigner();
state.address = address;
state.isConnected = true;
state.chainId = (await state.provider.getNetwork()).chainId;
// Init contract. Our CertifyNFT is plain ERC721 (not Enumerable), so we
// enumerate owned tokens via Transfer event logs rather than
// tokenOfOwnerByIndex / totalSupply.
if (CONFIG.CONTRACT_ADDRESS && CONFIG.CONTRACT_ADDRESS !== '0x0000000000000000000000000000000000000000') {
state.contract = new window.ethers.Contract(
CONFIG.CONTRACT_ADDRESS,
[
'function mint(address to, string uri) returns (uint256)',
'function balanceOf(address owner) view returns (uint256)',
'function ownerOf(uint256 tokenId) view returns (address)',
'function tokenURI(uint256 tokenId) view returns (string)',
'event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)'
],
state.signer
);
}
updateWalletUI();
updateNetworkUI();
// Listen for account/chain changes
window.ethereum.on('accountsChanged', handleAccountsChanged);
window.ethereum.on('chainChanged', handleChainChanged);
// Auto-prompt network switch if wrong chain (chainChanged event will reload)
if (Number(state.chainId) !== parseInt(CONFIG.CHAIN_ID, 16)) {
await ensureCorrectNetwork();
return; // chainChanged will reload the page
}
// Authenticate with Firebase (sign message to prove wallet ownership)
if (firebaseEnabled) {
await authenticateWithFirebase();
}
// Load gallery (Firestore first if authenticated, else on-chain fallback)
await loadGallery();
showToast('Wallet connected!', 'success');
}
async function handleAccountsChanged(accounts) {
if (accounts.length === 0) {
handleDisconnect();
} else {
await doConnect(accounts[0]);
}
}
async function handleChainChanged() {
// Reload to reset state
window.location.reload();
}
function handleDisconnect() {
signOutFirebase();
state.provider = null;
state.signer = null;
state.address = null;
state.chainId = null;
state.contract = null;
state.isConnected = false;
updateWalletUI();
$('#gallery-grid').innerHTML = '';
$('#gallery-empty').classList.remove('hidden');
}
function updateWalletUI() {
const connectBtn = $('#btn-connect');
const disconnectBtn = $('#btn-disconnect');
const walletInfo = $('#wallet-info');
const shortAddr = $('#short-address');
if (state.isConnected && state.address) {
connectBtn.classList.add('hidden');
disconnectBtn.classList.remove('hidden');
walletInfo.classList.remove('hidden');
shortAddr.textContent = shortAddress(state.address);
$('#mint-section').classList.remove('hidden');
$('#connect-prompt').classList.add('hidden');
$('#gallery').classList.remove('hidden');
} else {
connectBtn.classList.remove('hidden');
disconnectBtn.classList.add('hidden');
walletInfo.classList.add('hidden');
$('#mint-section').classList.add('hidden');
$('#connect-prompt').classList.remove('hidden');
}
}
function updateNetworkUI() {
const badge = $('#network-badge');
// chainId from ethers v6 is a BigInt; coerce before comparing
const targetChain = parseInt(CONFIG.CHAIN_ID, 16);
const isCorrectChain = Number(state.chainId) === targetChain;
const label = CONFIG.NETWORK_LABEL || 'Target network';
if (!state.isConnected) {
badge.innerHTML = `<span class="network-dot"></span> Not connected`;
badge.className = 'network-badge';
badge.onclick = null;
badge.style.cursor = '';
return;
}
if (isCorrectChain) {
badge.innerHTML = `<span class="network-dot"></span> ${label}`;
badge.className = 'network-badge connected';
badge.onclick = null;
badge.style.cursor = '';
} else {
badge.innerHTML = `<span class="network-dot"></span> Wrong network — tap to switch`;
badge.className = 'network-badge wrong-network';
badge.style.cursor = 'pointer';
badge.onclick = () => ensureCorrectNetwork();
showToast(`Please switch to ${label}`, 'warning');
}
}
// ============================================================
// Network Switching
// ============================================================
async function ensureCorrectNetwork() {
if (!window.ethereum) return false;
const currentChainId = await window.ethereum.request({ method: 'eth_chainId' });
const targetChainId = CONFIG.CHAIN_ID;
if (currentChainId !== targetChainId) {
// Use the first (and typically only) network definition in CONFIG.NETWORKS
const targetNetwork = Object.values(CONFIG.NETWORKS)[0];
try {
// Try to switch first — if the chain is already known to MetaMask this is
// a much cleaner UX than prompting to re-add the network.
try {
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: targetChainId }]
});
return true;
} catch (switchErr) {
// 4902 = chain not added to wallet yet → fall through to add
if (switchErr.code !== 4902) throw switchErr;
}
await window.ethereum.request({
method: 'wallet_addEthereumChain',
params: [targetNetwork]
});
// Chain changed, reload to get new state
// Note: metamask emits chainChanged after addEthereumChain
return true;
} catch (err) {
showToast('Failed to switch network: ' + err.message, 'error');
return false;
}
}
return true;
}
// ============================================================
// Image Upload & Compression
// ============================================================
function bindUploadEvents() {
const uploadZone = $('#upload-zone');
const uploadInput = $('#upload-input');
const removeBtn = $('#upload-remove-btn');
// Click to upload
uploadZone.addEventListener('click', (e) => {
if (e.target !== removeBtn && !removeBtn.contains(e.target)) {
uploadInput.click();
}
});
// File selected
uploadInput.addEventListener('change', (e) => {
if (e.target.files.length > 0) {
handleFileSelect(e.target.files[0]);
}
});
// Drag and drop
uploadZone.addEventListener('dragover', (e) => {
e.preventDefault();
uploadZone.classList.add('drag-over');
});
uploadZone.addEventListener('dragleave', (e) => {
e.preventDefault();
uploadZone.classList.remove('drag-over');
});
uploadZone.addEventListener('drop', (e) => {
e.preventDefault();
uploadZone.classList.remove('drag-over');
if (e.dataTransfer.files.length > 0) {
handleFileSelect(e.dataTransfer.files[0]);
}
});
// Remove button
removeBtn.addEventListener('click', (e) => {
e.stopPropagation();
resetUpload();
});
}
function handleFileSelect(file) {
const validTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/webp', 'application/pdf'];
const isPdf = file.type === 'application/pdf' || /\.pdf$/i.test(file.name);
if (!validTypes.includes(file.type) && !isPdf) {
showToast('Please upload a PNG, JPG, WebP, or PDF file.', 'error');
return;
}
const maxSize = 20 * 1024 * 1024; // 20MB raw
if (file.size > maxSize) {
showToast('File is too large. Maximum raw size is 20MB.', 'error');
return;
}
if (isPdf) {
renderPdfFirstPage(file)
.then((dataUrl) => compressImage(dataUrl))
.catch((err) => {
showToast('Failed to read PDF: ' + err.message, 'error');
resetUpload();
});
return;
}
// Read and compress (image path)
const reader = new FileReader();
reader.onload = (e) => {
compressImage(e.target.result);
};
reader.readAsDataURL(file);
}
// Render the first page of a PDF to a high-res PNG data URL using PDF.js.
// PDF.js is loaded from CDN in index.html (pdfjsLib global).
async function renderPdfFirstPage(file) {
if (!window.pdfjsLib) {
throw new Error('PDF library not loaded. Refresh the page and try again.');
}
showToast('Rendering PDF…', 'warning');
const arrayBuffer = await file.arrayBuffer();
const pdf = await window.pdfjsLib.getDocument({ data: arrayBuffer }).promise;
const page = await pdf.getPage(1);
// Render at scale tuned so the longest edge is ≤ 1600px before compression.
const base = page.getViewport({ scale: 1 });
const target = 1600;
const scale = Math.min(target / Math.max(base.width, base.height), 3);
const viewport = page.getViewport({ scale });
const canvas = document.createElement('canvas');
canvas.width = Math.floor(viewport.width);
canvas.height = Math.floor(viewport.height);
const ctx = canvas.getContext('2d');
// White background — PDFs are transparent, JPEG doesn't support alpha.
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, canvas.width, canvas.height);
await page.render({ canvasContext: ctx, viewport, canvas }).promise;
return canvas.toDataURL('image/png');
}
async function compressImage(dataUrl) {
showToast('Compressing image...', 'warning');
try {
const img = await loadImage(dataUrl);
// Ethereum storage is ~100× more expensive per byte than Polygon, so we
// have to hit much smaller targets than the original Polygon version.
// Gas budget (Sepolia 30M cap):
// URI 5 KB → 3.7M gas ✓
// URI 10 KB → 7.2M gas ✓ (pricey)
// URI 30 KB → fails
// Target the final base64-in-metadata tokenURI around 6 KB so we stay
// well under the allowance and the mint cost is reasonable.
const TARGET_KB = 6;
const HARD_LIMIT_KB = 10;
// Progressive downscale/quality sweep until we fit under TARGET_KB.
// Start at 400px longest edge and fall back toward 150px if needed.
const dimensions = [400, 340, 280, 220, 180, 150];
const qualities = [0.7, 0.55, 0.4, 0.3, 0.22];
let compressed = '';
let sizeKB = Infinity;
let usedDim = dimensions[0];
let usedQ = qualities[0];
outer:
for (const maxDim of dimensions) {
// Scale so the longer edge equals maxDim (works for portrait + landscape)
const ratio = Math.min(maxDim / img.width, maxDim / img.height, 1);
const width = Math.max(1, Math.round(img.width * ratio));
const height = Math.max(1, Math.round(img.height * ratio));
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
// White background for transparent PNGs (JPEG has no alpha)
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, width, height);
ctx.drawImage(img, 0, 0, width, height);
for (const q of qualities) {
const candidate = canvas.toDataURL('image/jpeg', q);
const candidateKB = Math.round((candidate.length - candidate.indexOf(',') - 1) * 0.75 / 1024);
if (candidateKB <= TARGET_KB) {
compressed = candidate;
sizeKB = candidateKB;
usedDim = maxDim;
usedQ = q;
break outer;
}
// keep best-so-far in case we exhaust the sweep
if (candidateKB < sizeKB) {
compressed = candidate;
sizeKB = candidateKB;
usedDim = maxDim;
usedQ = q;
}
}
}
state.compressedImage = compressed;
state.compressedSizeKB = sizeKB;
// Show preview
const previewImg = $('#upload-preview');
previewImg.src = compressed;
previewImg.classList.add('visible');
// Hide placeholder, show remove button
$('#upload-placeholder').classList.add('hidden');
$('#upload-remove-btn').classList.remove('hidden');
// Update preview card
updatePreviewCard();
if (sizeKB <= TARGET_KB) {
showToast(`Compressed to ${sizeKB}KB @ ${usedDim}px`, 'success');
$('#upload-hint').textContent = `Compressed: ${sizeKB}KB @ ${usedDim}px ✓`;
$('#upload-hint').className = 'form-hint';
} else if (sizeKB <= HARD_LIMIT_KB) {
showToast(`Image is ${sizeKB}KB — will cost more gas but should still mint.`, 'warning');
$('#upload-hint').textContent = `Compressed: ${sizeKB}KB (above target, gas will be higher)`;
$('#upload-hint').className = 'form-hint warning';
} else {
showToast(`Image is ${sizeKB}KB — too large for Sepolia. Try a simpler image.`, 'error');
$('#upload-hint').textContent = `Compressed: ${sizeKB}KB — exceeds ${HARD_LIMIT_KB}KB Sepolia limit`;
$('#upload-hint').className = 'form-hint warning';
}
} catch (err) {
showToast('Failed to process image: ' + err.message, 'error');
resetUpload();
}
}
function loadImage(dataUrl) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = dataUrl;
});
}
function resetUpload() {
state.compressedImage = null;
state.compressedSizeKB = 0;
$('#upload-input').value = '';
const preview = $('#upload-preview');
preview.src = '';
preview.classList.remove('visible');
$('#upload-placeholder').classList.remove('hidden');
$('#upload-remove-btn').classList.add('hidden');
$('#upload-hint').textContent = 'PNG, JPG or WebP — max 20MB raw';
$('#upload-hint').className = 'form-hint';
updatePreviewCard();
}
// ============================================================
// Form & Live Preview
// ============================================================
function bindFormEvents() {
const fields = ['cert-title', 'recipient-name', 'issuer-name', 'cert-description', 'issue-date'];
fields.forEach(id => {
const el = $(`#${id}`);
if (el) {
el.addEventListener('input', updatePreviewCard);
el.addEventListener('change', updatePreviewCard);
}
});
// Mint button
$('#btn-mint').addEventListener('click', handleMint);
}
function updatePreviewCard() {
const title = $('#cert-title').value || 'Certificate Title';
const recipient = $('#recipient-name').value || 'Recipient Name';
const issuer = $('#issuer-name').value || 'Issuer';
const description = $('#cert-description').value || '';
const date = $('#issue-date').value || '';
$('#preview-title').textContent = title;
$('#preview-recipient').textContent = recipient;
$('#preview-issuer').textContent = issuer;
$('#preview-date').textContent = date ? formatDate(date) : '';
const previewImg = $('#preview-image');
if (state.compressedImage) {
previewImg.src = state.compressedImage;
previewImg.classList.add('visible');
$('#preview-placeholder').classList.add('hidden');
} else {
previewImg.src = '';
previewImg.classList.remove('visible');
$('#preview-placeholder').classList.remove('hidden');
}
}
function validateForm() {
if (!state.compressedImage) {
showToast('Please upload a certificate image.', 'error');
return false;
}
if (!state.address) {
showToast('Please connect your wallet first.', 'error');
return false;
}
if (!CONFIG.CONTRACT_ADDRESS || CONFIG.CONTRACT_ADDRESS === '0x0000000000000000000000000000000000000000') {
showToast('Contract not deployed. Please update config.js with your contract address.', 'error');
return false;
}
const title = $('#cert-title').value.trim();
if (!title) {
showToast('Please enter a certificate title.', 'error');
return false;
}
const recipient = $('#recipient-name').value.trim();
if (!recipient) {
showToast('Please enter the recipient name.', 'error');
return false;
}
return true;
}
// ============================================================
// Minting
// ============================================================
async function handleMint() {
if (state.isMinting) return;
if (!validateForm()) return;
// Ensure correct network
const switched = await ensureCorrectNetwork();
if (!switched) return;
state.isMinting = true;
$('#btn-mint').disabled = true;
$('#btn-mint').textContent = 'Minting...';
showMintModal('pending');
try {
// Build metadata
const metadata = buildMetadata();
const tokenUri = 'data:application/json;base64,' + btoa(metadata);
// Call contract
const tx = await state.contract.mint(state.address, tokenUri);
showMintModal('pending', tx.hash);
// Wait for confirmation
const receipt = await tx.wait();
// Get token ID from Transfer event
const iface = new window.ethers.Interface([
'event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)'
]);
const log = receipt.logs.find(l => {
try {
const parsed = iface.parseLog(l);
return parsed?.name === 'Transfer';
} catch { return false; }
});
const tokenId = log ? iface.parseLog(log).args.tokenId : '?';
showMintModal('success', tx.hash, tokenId);
showToast('Certificate NFT minted successfully! 🎉', 'success');
// Save to Firestore for fast gallery loading
await saveCertificateToFirestore(tokenId, tx.hash);
// Reset form after success
setTimeout(() => {
closeMintModal();
resetUpload();
$('#cert-title').value = '';
$('#recipient-name').value = '';
$('#issuer-name').value = '';
$('#cert-description').value = '';
$('#issue-date').value = new Date().toISOString().split('T')[0];
updatePreviewCard();
loadGallery();
}, 3000);
} catch (err) {
console.error('Mint error:', err);
const msg = parseContractError(err);
showMintModal('error', null, null, msg);
showToast('Minting failed: ' + msg, 'error');
} finally {
state.isMinting = false;
$('#btn-mint').disabled = false;
$('#btn-mint').textContent = 'Mint NFT';
}
}
// ============================================================
// Firestore Persistence
// ============================================================
async function saveCertificateToFirestore(tokenId, txHash) {
if (!firebaseEnabled || !state.isAuthenticated || !db) return;
if (tokenId === '?') return;
const docId = `${Number(state.chainId)}_${CONFIG.CONTRACT_ADDRESS.toLowerCase()}_${tokenId.toString()}`;
try {
await db.collection('certificates').doc(docId).set({
walletAddress: state.address.toLowerCase(),
tokenId: tokenId.toString(),
contractAddress: CONFIG.CONTRACT_ADDRESS.toLowerCase(),
chainId: Number(state.chainId),
txHash: txHash,
title: $('#cert-title').value.trim(),
recipient: $('#recipient-name').value.trim(),
issuer: $('#issuer-name').value.trim(),
description: $('#cert-description').value.trim(),
issueDate: $('#issue-date').value,
image: state.compressedImage,
mintedAt: firebase.firestore.FieldValue.serverTimestamp()
});
console.info('Certificate saved to Firestore:', docId);
} catch (err) {
// Non-blocking — the NFT is already minted on-chain
console.warn('Failed to save certificate to Firestore:', err);
}
}
async function loadGalleryFromFirestore() {
if (!firebaseEnabled || !state.isAuthenticated || !db) return null;
try {
const snapshot = await db.collection('certificates')
.where('walletAddress', '==', state.address.toLowerCase())
.orderBy('mintedAt', 'desc')
.get();
if (snapshot.empty) return [];
return snapshot.docs.map(doc => {
const d = doc.data();
return {
tokenId: d.tokenId,
title: d.title,
recipient: d.recipient,
issuer: d.issuer,
issueDate: d.issueDate,
image: d.image,
txHash: d.txHash
};
});
} catch (err) {
console.warn('Firestore gallery load failed, will fall back to on-chain:', err);
return null; // null signals fallback to on-chain
}
}
function buildMetadata() {
const title = $('#cert-title').value.trim();
const recipient = $('#recipient-name').value.trim();
const issuer = $('#issuer-name').value.trim();
const description = $('#cert-description').value.trim();
const date = $('#issue-date').value || new Date().toISOString().split('T')[0];
const metadata = {
name: title,
description: description || `${recipient} completed ${issuer} on ${formatDate(date)}`,
image: state.compressedImage,
attributes: [
{ trait_type: 'Recipient', value: recipient },
{ trait_type: 'Issuer', value: issuer },
{ trait_type: 'Issue Date', value: formatDate(date) },
{ trait_type: 'Certificate Type', value: 'Completion' }
]
};
return JSON.stringify(metadata);
}
// ============================================================
// Mint Modal
// ============================================================
function showMintModal(status, txHash = null, tokenId = null, errorMsg = null) {
const overlay = $('#mint-modal');
const icon = $('#modal-icon');
const title = $('#modal-title');
const subtitle = $('#modal-subtitle');
const detail = $('#modal-detail');
const actions = $('#modal-actions');
overlay.classList.add('visible');
if (status === 'pending') {
icon.innerHTML = `<div class="spinner"></div>`;
title.textContent = 'Minting...';
subtitle.textContent = 'Please confirm the transaction in MetaMask.';
detail.textContent = txHash ? `Tx: ${shortHash(txHash)}` : '';
detail.classList.remove('hidden');
actions.innerHTML = `<button class="btn btn-secondary" onclick="closeMintModal()">Cancel</button>`;
} else if (status === 'success') {
const targetNetwork = Object.values(CONFIG.NETWORKS)[0];
const explorerUrl = `${targetNetwork.blockExplorerUrls[0]}/tx/${txHash}`;
const nftUrl = `${targetNetwork.blockExplorerUrls[0]}/nft/${CONFIG.CONTRACT_ADDRESS}/${tokenId}`;
icon.innerHTML = `<svg class="modal-icon" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="32" cy="32" r="30" stroke="#06b6d4" stroke-width="3"/>
<path d="M20 32l8 8 16-16" stroke="#06b6d4" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
</svg>`;
title.textContent = 'Minted! 🎉';
subtitle.textContent = `Your certificate NFT has been minted on ${CONFIG.NETWORK_LABEL}.`;
detail.innerHTML = `
<div>Tx: <a href="${explorerUrl}" target="_blank" rel="noopener">${shortHash(txHash)}</a></div>
<div style="margin-top:4px">Token ID: #${tokenId}</div>
`;
detail.classList.remove('hidden');
actions.innerHTML = `
<a href="${nftUrl}" target="_blank" rel="noopener" class="btn btn-secondary">View NFT</a>
<a href="${explorerUrl}" target="_blank" rel="noopener" class="btn btn-cyan">View Transaction</a>
`;
} else if (status === 'error') {
icon.innerHTML = `<svg class="modal-icon" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="32" cy="32" r="30" stroke="#ef4444" stroke-width="3"/>
<path d="M22 22l20 20M42 22L22 42" stroke="#ef4444" stroke-width="3" stroke-linecap="round"/>
</svg>`;
title.textContent = 'Minting Failed';
subtitle.textContent = errorMsg || 'An unknown error occurred.';
detail.classList.add('hidden');
actions.innerHTML = `<button class="btn btn-secondary" onclick="closeMintModal()">Close</button>`;
}
}
function closeMintModal() {
$('#mint-modal').classList.remove('visible');
}
// ============================================================
// Gallery
// ============================================================
function bindGalleryEvents() {
// Refresh button
$('#btn-refresh-gallery')?.addEventListener('click', loadGallery);
}
async function loadGallery() {
if (!state.isConnected || !state.address) return;
const grid = $('#gallery-grid');
const empty = $('#gallery-empty');
grid.innerHTML = '';
empty.classList.add('hidden');
// Try Firestore first (fast), fall back to on-chain Transfer events
const firestoreData = await loadGalleryFromFirestore();
if (firestoreData !== null) {
// ----- Firestore path -----
if (firestoreData.length === 0) {
empty.classList.remove('hidden');
empty.querySelector('p').textContent =
'No certificates minted yet. Upload one above and mint your first!';
return;
}
for (const cert of firestoreData) {
const item = createGalleryItemFromData(cert);
grid.appendChild(item);
}
return;
}
// ----- On-chain fallback -----
if (!state.contract) return;
try {
const filter = state.contract.filters.Transfer(null, state.address);
const events = await state.contract.queryFilter(filter, 0, 'latest');
const seen = new Set();
const tokenIds = [];
for (const ev of events) {
const id = ev.args?.tokenId ?? ev.args?.[2];
const key = id?.toString();
if (key && !seen.has(key)) {
seen.add(key);
tokenIds.push(id);
}
}
const owned = [];
for (const id of tokenIds) {
try {
const owner = await state.contract.ownerOf(id);
if (owner.toLowerCase() === state.address.toLowerCase()) {
owned.push(id);
}
} catch (e) { /* burned — skip */ }
}
if (owned.length === 0) {
empty.classList.remove('hidden');
empty.querySelector('p').textContent =
'No certificates minted yet. Upload one above and mint your first!';
return;
}
owned.reverse();
for (const tokenId of owned) {
const tokenUri = await state.contract.tokenURI(tokenId);
let metadata = null;
try {
if (tokenUri.startsWith('data:')) {
const b64 = tokenUri.split(',')[1];
const json = atob(b64);
metadata = JSON.parse(json);
}
} catch (e) {
console.warn('Could not parse token URI for', tokenId.toString(), e);
}
const item = createGalleryItem(tokenId, metadata, tokenUri);
grid.appendChild(item);
}
} catch (err) {
console.error('Gallery load error:', err);
empty.classList.remove('hidden');
empty.querySelector('p').textContent =
'Could not load gallery: ' + (err.shortMessage || err.message || 'unknown error');
}
}
function createGalleryItem(tokenId, metadata, tokenUri) {
const div = document.createElement('div');
div.className = 'gallery-item fade-in-up';
const imgUrl = metadata?.image || '';
const title = metadata?.name || `Certificate #${tokenId}`;
const recipient = metadata?.attributes?.find(a => a.trait_type === 'Recipient')?.value || '—';
const date = metadata?.attributes?.find(a => a.trait_type === 'Issue Date')?.value || '';
const targetNetwork = Object.values(CONFIG.NETWORKS)[0];
const nftUrl = `${targetNetwork.blockExplorerUrls[0]}/nft/${CONFIG.CONTRACT_ADDRESS}/${tokenId}`;
div.innerHTML = `
<div class="gallery-item-image-container" style="aspect-ratio:4/3;overflow:hidden;background:rgba(0,0,0,0.3);">
${imgUrl ? `<img class="gallery-item-image" src="${imgUrl}" alt="${title}" style="width:100%;height:100%;object-fit:cover;" onerror="this.style.display='none'">` : `<div style="display:flex;align-items:center;justify-content:center;height:100%;color:var(--text-muted);font-size:13px;">No image</div>`}
</div>
<div class="gallery-item-meta">
<div class="gallery-item-title">${escapeHtml(title)}</div>
<div class="gallery-item-recipient">${escapeHtml(recipient)}</div>
${date ? `<div class="gallery-item-date">${date}</div>` : ''}
<div class="gallery-item-actions">
<a href="${nftUrl}" target="_blank" rel="noopener" class="btn btn-sm btn-secondary">View on Etherscan</a>
</div>
</div>
`;
return div;
}
// Build a gallery card from Firestore document data (avoids re-fetching on-chain)
function createGalleryItemFromData(cert) {
const div = document.createElement('div');
div.className = 'gallery-item fade-in-up';
const imgUrl = cert.image || '';
const title = cert.title || `Certificate #${cert.tokenId}`;
const recipient = cert.recipient || '—';
const date = cert.issueDate || '';
const targetNetwork = Object.values(CONFIG.NETWORKS)[0];
const nftUrl = `${targetNetwork.blockExplorerUrls[0]}/nft/${CONFIG.CONTRACT_ADDRESS}/${cert.tokenId}`;
div.innerHTML = `
<div class="gallery-item-image-container" style="aspect-ratio:4/3;overflow:hidden;background:rgba(0,0,0,0.3);">
${imgUrl ? `<img class="gallery-item-image" src="${imgUrl}" alt="${escapeHtml(title)}" style="width:100%;height:100%;object-fit:cover;" onerror="this.style.display='none'">` : `<div style="display:flex;align-items:center;justify-content:center;height:100%;color:var(--text-muted);font-size:13px;">No image</div>`}
</div>
<div class="gallery-item-meta">
<div class="gallery-item-title">${escapeHtml(title)}</div>
<div class="gallery-item-recipient">${escapeHtml(recipient)}</div>
${date ? `<div class="gallery-item-date">${date}</div>` : ''}
<div class="gallery-item-actions">
<a href="${nftUrl}" target="_blank" rel="noopener" class="btn btn-sm btn-secondary">View on Etherscan</a>
</div>
</div>
`;
return div;
}
// ============================================================