Repository navigation
Expand file tree
/
Copy pathup-backup.html
More file actions
1224 lines (1182 loc) · 90 KB
/
Copy pathup-backup.html
File metadata and controls
1224 lines (1182 loc) · 90 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
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy" content="script-src 'self' https://cdnjs.cloudflare.com/ajax/libs/ethers/6.13.4/ 'sha256-5n8b154fSp3ibvORz3OUxvhkx8EnGwJxx0mPMMQVgLs='">
<script src="theme.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="referrer" content="no-referrer">
<title>UP backup controller — ChainIntegrate</title>
<meta name="description" content="Aggiungi un controller di backup alla tua LUKSO Universal Profile su ogni rete, o togli una chiave persa. Nessuna chiave privata richiesta: firmi sempre dal tuo wallet.">
<link rel="icon" href="favicon.ico">
<meta property="og:type" content="website">
<meta property="og:title" content="UP backup controller — ChainIntegrate">
<meta property="og:description" content="Aggiungi un controller di backup alla tua LUKSO Universal Profile su ogni rete, o togli una chiave persa. Nessuna chiave privata richiesta: firmi sempre dal tuo wallet.">
<meta property="og:image" content="https://crosschain-lukso.chainintegrate.it/og-image.png">
<meta property="og:url" content="https://crosschain-lukso.chainintegrate.it/up-backup.html">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="UP backup controller — ChainIntegrate">
<meta name="twitter:description" content="Aggiungi un controller di backup alla tua LUKSO Universal Profile su ogni rete, o togli una chiave persa. Nessuna chiave privata richiesta: firmi sempre dal tuo wallet.">
<meta name="twitter:image" content="https://crosschain-lukso.chainintegrate.it/og-image.png">
<script src="https://cdnjs.cloudflare.com/ajax/libs/ethers/6.13.4/ethers.umd.min.js" integrity="sha384-6Zl0Pc8zjSz8KvmNeXRvUQgY4ryFb+BwDvKCmLYcBME0joAaru491tQgi9B7zsMM" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="chains.js"></script>
<script src="site-ui.js"></script>
<script src="sign-check.js"></script>
<script src="backup-check.js"></script>
<style>
:root {
--bg: #0f1115; --panel: #171a21; --border: #2a2f3a; --field: #10131a; --chip: #2a2f3a; --disabled: #3a3f4b; --raised: #1d2330;
--text: #e6e8ec; --text-dim: #9aa1ad;
--accent: #5b8cff; --ok: #3fbf6f; --warn: #e0a83c; --err: #e05a5a;
}
* { box-sizing: border-box; }
body { background: var(--bg); color: var(--text); font-family: -apple-system, "Segoe UI", Roboto, sans-serif;
max-width: 820px; margin: 0 auto; padding: 32px 20px 80px; }
.header-row { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }
.brand-row { margin-bottom: 24px; }
.brand-logo { display: block; width: 100%; height: auto; border-radius: 10px; }
.site-footer { margin-top: 40px; padding: 18px 20px; background: #f5f6f8; border: 1px solid #e3e5ea; border-radius: 10px; color: #4b4f58; }
.footer-row { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; }
.footer-logo { height: 48px; width: auto; flex-shrink: 0; }
.footer-text { font-size: 13px; line-height: 1.6; }
.footer-li { display: inline-flex; vertical-align: middle; margin: 0 2px; }
.site-footer a { color: #2563eb; text-decoration: none; font-weight: 600; }
.site-footer a:hover { text-decoration: underline; }
h1 { font-size: 20px; margin-bottom: 4px; }
.subtitle { color: var(--text-dim); font-size: 13px; margin-bottom: 28px; }
#langToggle { width: auto; background: var(--chip); padding: 8px 14px; font-size: 12.5px; font-weight: 600;
border-radius: 6px; border: 1px solid var(--border); color: var(--text); cursor: pointer; margin-top: 2px; flex-shrink: 0; }
.panel { background: var(--panel); border: 1px solid var(--border); border-radius: 10px; padding: 20px; margin-bottom: 20px; }
.panel h2 { font-size: 14px; margin: 0 0 14px; color: var(--text-dim); text-transform: uppercase; letter-spacing: 0.03em; }
label { display: block; font-size: 13px; color: var(--text-dim); margin: 14px 0 6px; }
label:first-child { margin-top: 0; }
select, input, textarea { width: 100%; background: var(--field); border: 1px solid var(--border); color: var(--text);
border-radius: 6px; padding: 10px 12px; font-size: 13.5px; font-family: inherit; }
textarea { font-family: monospace; font-size: 11.5px; min-height: 90px; resize: vertical; word-break: break-all; }
button { width: 100%; background: var(--accent); color: white; border: none; border-radius: 6px;
padding: 12px; font-size: 14px; font-weight: 600; cursor: pointer; margin-top: 12px; }
button:disabled { background: var(--disabled); cursor: not-allowed; }
button.danger { background: var(--err); }
button.secondary { background: var(--chip); }
.status-box { background: var(--field); border: 1px solid var(--border); border-radius: 6px; padding: 12px;
font-family: monospace; font-size: 12.5px; margin-top: 12px; word-break: break-all; }
.status-box .empty { color: var(--text-dim); }
.line-ok { color: var(--ok); } .line-warn { color: var(--warn); } .line-err { color: var(--err); } .line-dim { color: var(--text-dim); }
.badge { display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: 11px; font-family: monospace; }
.badge.ok { background: rgba(63,191,111,0.15); color: var(--ok); }
.badge.err { background: rgba(224,90,90,0.15); color: var(--err); }
.badge.warn { background: rgba(224,168,60,0.15); color: var(--warn); }
.ctrl-card { background: var(--field); border: 1px solid var(--border); border-radius: 6px; padding: 10px 12px; margin-top: 8px; }
.ctrl-card .addr { font-family: monospace; font-size: 12.5px; }
.ctrl-card .flags { font-size: 11px; color: var(--text-dim); margin-top: 4px; }
.divider { color: var(--text-dim); font-size: 12px; text-align: center; margin: 16px 0 6px; }
.note { font-size: 12px; color: var(--text-dim); margin-bottom: 10px; line-height: 1.5; }
.note b { color: var(--text); }
.check-row { display: flex; gap: 8px; align-items: flex-start; font-size: 12.5px; color: var(--text); margin-top: 12px; }
.check-row input { width: auto; margin-top: 2px; }
.check-row[hidden] { display: none; }
#backupLog { font-family: monospace; font-size: 12.5px; white-space: pre-wrap; word-break: break-all; line-height: 1.6; margin-top: 10px; }
/* While a backup action runs: a fixed box that says what is happening, so the wait before the wallet opens is never silent. */
#busyToast { display: none; position: fixed; left: 50%; bottom: 16px; transform: translateX(-50%); z-index: 50;
width: calc(100% - 32px); max-width: 720px; background: var(--raised); border: 2px solid var(--warn); border-radius: 10px;
padding: 12px 16px; font-size: 14px; line-height: 1.5; color: var(--text); box-shadow: 0 6px 24px rgba(0,0,0,0.5); }
#busyToast.on { display: flex; gap: 12px; align-items: center; }
#busyToast .spin { width: 18px; height: 18px; flex: 0 0 18px; border: 3px solid var(--warn); border-top-color: transparent; border-radius: 50%; animation: spin 0.9s linear infinite; }
#busyToast .msg { word-break: break-word; }
@keyframes spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) { #busyToast .spin { animation: none; } }
</style>
</head>
<body>
<div class="brand-row">
<img src="banner.png" alt="ChainIntegrate" class="brand-logo">
</div>
<div class="header-row">
<div>
<h1 data-i18n="h1">UP Deploy Cross-Chain</h1>
<div class="subtitle" data-i18n="subtitle"></div>
</div>
<button id="langToggle" type="button">English</button>
</div>
<div class="panel">
<h2 data-i18n="panel0Title">0 · Perché serve</h2>
<div class="note" data-i18n-html="backupNote"></div>
</div>
<div class="panel">
<h2 data-i18n="panel1Title">1 · Rete</h2>
<input type="text" id="networkFilter" data-i18n-placeholder="networkFilterPlaceholder" placeholder="Filtra per nome...">
<select id="network" style="margin-top:8px;"></select>
<div id="customRpcWrap" style="display:none;">
<label data-i18n="customRpcLabel">RPC URL custom</label>
<input type="text" id="customRpc" data-i18n-placeholder="customRpcPlaceholder" placeholder="https://...">
<label data-i18n="customExplorerLabel">Explorer URL custom (opzionale)</label>
<input type="text" id="customExplorer" data-i18n-placeholder="customExplorerPlaceholder" placeholder="https://.../address/">
</div>
</div>
<div class="panel">
<h2 data-i18n="panel2Title">2 · La UP</h2>
<button id="connectUp" class="secondary" data-i18n="connectUpBtn">Leggi l'indirizzo dalla tua UP (estensione o app)</button>
<label for="upAddress" data-i18n="upAddressLabel">Indirizzo della UP</label>
<input type="text" id="upAddress" data-i18n-placeholder="placeholderAddr" placeholder="0x...">
</div>
<div class="panel">
<h2 data-i18n="panel3Title">3 · Il controller che firma (MetaMask)</h2>
<div class="note" data-i18n-html="signerNote"></div>
<button id="connectSigner" data-i18n="connectSigner5Btn">Connetti il controller della UP (MetaMask)</button>
<div class="note" data-i18n="signerPickHint" style="margin-top:8px;"></div>
<div class="status-box" id="signerStatus"><span class="empty" data-i18n="notConnected">Non connesso.</span></div>
</div>
<div class="panel" id="backup">
<h2 data-i18n="panel4Title">4 · Controller della UP su questa rete</h2>
<button id="readCtrlBtn" data-i18n="readCtrlBtn">Leggi i controller della UP su questa rete</button>
<div class="status-box" id="backupStatus"><span class="empty" data-i18n="backupNotRead">Controller non ancora letti.</span></div>
<div class="note" id="genesisNote" style="margin-top:8px;"></div>
<div id="backupList"></div>
<label data-i18n="backupAddrLabel">Indirizzo del controller di backup (un account MetaMask diverso, custodito a parte)</label>
<input type="text" id="backupAddress" placeholder="0x...">
<button id="addBackupBtn" disabled data-i18n="addBackupBtn">Aggiungi il controller di backup</button>
<div class="divider" data-i18n="phoneDivider">— oppure, per UP Wallet: app Android o estensione del browser —</div>
<div class="note" data-i18n-html="phoneNote"></div>
<label data-i18n="phoneAddrLabel">Indirizzo della chiave del dispositivo (lo mostra l'app, pannello "Questo telefono", o l'estensione, pannello "Questo computer")</label>
<input type="text" id="phoneAddress" placeholder="0x...">
<div id="phoneLinkRow" hidden>
<div class="note" data-i18n-html="phoneLinkTailNote"></div>
<label for="phoneLinkTail" data-i18n="phoneLinkTailLabel">Ultimi 8 caratteri</label>
<input type="text" id="phoneLinkTail" maxlength="8" autocomplete="off" spellcheck="false" placeholder="········">
<div class="note" id="phoneLinkTailState"></div>
</div>
<label for="phoneName" data-i18n="phoneNameLabel">Nome del dispositivo (facoltativo)</label>
<input type="text" id="phoneName" maxlength="64" autocomplete="off" data-i18n-placeholder="phoneNamePh">
<button id="addPhoneBtn" disabled data-i18n="addPhoneBtn">Autorizza il dispositivo su questa rete</button>
<div class="divider" data-i18n="nameDivider">— oppure, il nome di un controller —</div>
<div class="note" data-i18n-html="nameNote"></div>
<label for="nameSelect" data-i18n="nameSelectLabel">Controller</label>
<select id="nameSelect"></select>
<label for="nameInput" data-i18n="nameInputLabel">Nome</label>
<input type="text" id="nameInput" maxlength="64" autocomplete="off">
<button id="nameBtn" disabled data-i18n="nameBtn">Salva il nome su questa rete</button>
<div class="divider" data-i18n="removeDivider">— oppure, dopo aver perso una chiave —</div>
<label data-i18n="removeLabel">Controller da rimuovere</label>
<select id="removeSelect"></select>
<div class="note" data-i18n="removeHint"></div>
<label class="check-row"><input type="checkbox" id="removeAck"> <span data-i18n="removeAck">Confermo: questa chiave è persa o non mi serve più. Il controller connesso nel wallet resta e continua a gestire la UP.</span></label>
<button id="removeBtn" class="danger" disabled data-i18n="removeBtn">Rimuovi il controller selezionato</button>
<div id="backupLog"></div>
<button id="copyBackupLog" class="secondary" data-i18n="copyLogBtn">Copia il log</button>
</div>
<div id="busyToast" role="status" aria-live="polite"><div class="spin"></div><div class="msg" id="busyMsg"></div></div>
<div class="site-footer">
<div class="footer-row">
<img src="logo.png" alt="ChainIntegrate" class="footer-logo">
<div class="footer-text" data-i18n-html="footerHtml"></div>
</div>
</div>
<script>
const $ = (id) => document.getElementById(id);
// Every value that did not originate in this file (user input, wallet responses, RPC or
// library error messages) must be escaped before being interpolated into innerHTML.
const escapeHtml = (v) => String(v).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
// ==================== I18N ====================
let LANG = SiteUI.initialLang();
const I18N = {
it: {
pageTitle: "Controller di backup della UP",
h1: "Controller di backup della UP",
subtitle: "Aggiunge un secondo controller alla tua Universal Profile su una rete, con gli stessi permessi del controller che firma, oppure toglie una chiave persa. Una sola transazione del Key Manager, simulata prima e riletta dopo. La pagina non chiede mai chiavi private: firmi tu, dal tuo wallet.",
langToggleBtn: "English",
panel0Title: "0 · Perché serve",
panel1Title: "1 · Rete",
panel2Title: "2 · La UP",
connectUpBtn: "Leggi l'indirizzo dalla tua UP (estensione o app)",
upAddressLabel: "Indirizzo della UP",
panel3Title: "3 · Il controller che firma (MetaMask)",
signerNote: "Il wallet connesso qui <b>deve essere un controller amministratore della UP</b> su questa rete (con ADDCONTROLLER ed EDITPERMISSIONS), e paga il gas. Su una UP appena deployata è la <b>chiave di genesi</b> importata in MetaMask: se hai fatto il deploy con quell'account, è già quello giusto. Va fatto <b>su ogni rete</b>, perché ogni rete ha la sua lista di controller, <b>LUKSO compresa</b>: lì il controller che firma è quello che la UP ha oggi su LUKSO, per esempio la chiave dell'estensione Universal Profile importata in MetaMask, che può essere diversa dalla chiave di genesi. Dal telefono, dove il browser non ha MetaMask, il pulsante collega l'app MetaMask con WalletConnect: la transazione arriva nell'app da approvare. <b>Non accettare mai su questo account un \"upgrade a smart account\" (EIP-7702) che non hai chiesto</b>: delegato a un contratto malevolo, gli darebbe il pieno controllo della UP.",
panel4Title: "4 · Controller della UP su questa rete",
genesisUnknown: "Chiave di genesi non riconosciuta: la transazione di creazione della UP non è stata trovata sull'explorer di LUKSO. Il resto funziona lo stesso.",
backupNote: "<b>Il problema non è il furto, è la perdita.</b> Su ogni rete dove rifai il deploy, la UP nasce controllata solo dalla <b>chiave di genesi</b>: la stringa che hai estratto dall'estensione Universal Profile. Se la perdi (computer rotto, stringa mai salvata, password dimenticata) e non c'è un altro controller con gli stessi permessi, resti fuori da questa UP su questa rete per sempre, con tutto quello che contiene. Nessuno può rimediare. Un <b>controller di backup</b> è un secondo account (per esempio un altro account MetaMask, con la sua seed custodita a parte) con <b>esattamente gli stessi permessi</b> del controller che firma qui. Se perdi una delle due chiavi, con l'altra continui a firmare, aggiungi un nuovo backup e rimuovi quella persa. Se perdi proprio la chiave di genesi, l'unica cosa che non potrai più fare è il deploy su reti nuove, perché lì la UP nasce solo con lei.",
backupNotRead: "Controller non ancora letti.",
addBackupBtn: "Aggiungi il controller di backup",
phoneDivider: "— oppure, per UP Wallet: app Android o estensione del browser —",
phoneNote: "<b>Autorizza un dispositivo.</b> Solo su LUKSO? Lo puoi fare anche con l'estensione o l'app Universal Profiles, senza MetaMask: <a href=\"up-authorize-lukso.html\" style=\"color:var(--accent);\">Autorizza un dispositivo su LUKSO</a>. L'app UP Wallet per Android (da 0.9.0) firma con una chiave creata e tenuta sul telefono; l'estensione UP Wallet per il browser con una chiave tenuta sul computer. Qui la aggiungi alla UP come controller <b>senza permessi di amministrazione</b>: <b>non</b> può aggiungere controller, cambiare permessi o estensioni. Può però <b>usare tutti i fondi della UP</b>: chiamate e invii verso qualsiasi indirizzo (SUPER_CALL, SUPER_TRANSFERVALUE), firme (SIGN), gas pagato dal sito (4337) e scrittura del solo profilo (SETDATA, limitato alla chiave <code>LSP3Profile</code>). Chi sblocca il dispositivo e passa impronta, PIN, passkey o password può muovere i fondi: autorizza solo un dispositivo tuo. Firma il controller amministratore connesso qui, una volta per rete. Se perdi il dispositivo o togli l'app o l'estensione, rimuovi la sua chiave qui sotto, rete per rete.",
phoneAddrLabel: "Indirizzo della chiave del dispositivo (lo mostra l'app, pannello \"Questo telefono\", o l'estensione, pannello \"Questo computer\")",
phoneLinkTailNote: () => `Il link porta l'indirizzo <code>${phoneLinkAddr ? phoneLinkAddr.slice(0, 10) : ""}…</code>. Chiunque può fare un link così: apri la tua app UP Wallet ("Questo telefono") o la tua estensione ("Questo computer") e <b>scrivi qui gli ultimi 8 caratteri</b> dell'indirizzo che ti mostra.`,
phoneLinkTailLabel: "Ultimi 8 caratteri dell'indirizzo, dall'app o dall'estensione",
phoneLinkTailOk: "✅ Corrisponde: l'indirizzo del link è quello del tuo dispositivo.",
phoneLinkTailBad: "❌ Non corrisponde. Ricontrolla l'app o l'estensione: se è giusto, il link non è tuo e non va usato.",
bkPhoneLinkAck: "L'indirizzo del dispositivo viene dal link: prima scrivi gli ultimi 8 caratteri che mostra la tua app o la tua estensione. Un link di qualcun altro potrebbe darti il suo indirizzo, e con questa autorizzazione potrebbe muovere i fondi della UP.",
addPhoneBtn: "Autorizza il dispositivo su questa rete",
phoneNameLabel: "Nome del dispositivo (facoltativo): salvato sulla UP con l'autorizzazione, per riconoscerlo nella lista. Pubblico, come gli indirizzi dei controller: niente dati personali",
phoneNamePh: "es. PC ufficio · estensione",
deviceComputer: "Computer · estensione UP Wallet",
devicePhone: "Telefono · app UP Wallet",
nameDivider: "— oppure, il nome di un controller —",
nameNote: "<b>Un nome per ogni controller</b> (\"PC ufficio · estensione\", \"MetaMask backup\"), salvato sulla UP: lo vedono questa pagina e UP Wallet da ogni dispositivo. Come i controller, vale <b>per questa rete</b>: ripetilo su ogni rete. È pubblico come gli indirizzi dei controller: niente dati personali. Al massimo 64 caratteri; lascia vuoto per toglierlo. Lo firma il controller amministratore connesso qui, con una transazione su questa rete. È solo un'etichetta: non cambia nessun permesso.",
nameSelectLabel: "Controller",
nameInputLabel: "Nome (vuoto per toglierlo)",
nameBtn: "Salva il nome su questa rete",
nameNone: "Nessun controller letto.",
bkName: (v) => `Nome: ${v.name}`,
bkPlanName: (v) => `Piano (una transazione, firmata da ${v.signer} tramite il Key Manager ${v.km}):\n- nome di ${v.addr} → ${v.name}`,
bkPlanNameLine: (v) => `- nome → ${v.name}`,
bkPlanNameClear: "\n- nome → cancellato",
bkNameCleared: "nessuno (tolto)",
bkNameSame: "Il controller ha già questo nome su questa rete.",
bkNameOk: (v) => `✅ Nome di ${v.addr} su questa rete: ${v.name}.`,
bkPlanPhone: (v) => `Piano (una transazione, firmata da ${v.signer} tramite il Key Manager ${v.km}):\n- AddressPermissions[] da ${v.len} a ${v.len1} voci, posizione ${v.len} → ${v.phone}\n- permessi del dispositivo → ${v.perms} (${v.names})\n- chiavi di dati ammesse → solo LSP3Profile (il profilo)`,
bkPhoneOk: (v) => `✅ Dispositivo autorizzato su questa rete: ${v.addr}, senza permessi di amministrazione. Ripeti su ogni rete dove usi la UP. Per revocarlo: "Rimuovi il controller selezionato".`,
bkPhoneAdmin: "Questo indirizzo è già un controller amministratore della UP: non serve autorizzarlo come dispositivo.",
backupAddrLabel: "Indirizzo del controller di backup (un account MetaMask diverso, custodito a parte)",
connectSigner5Btn: "Connetti il controller della UP (MetaMask)",
signerPickHint: "Il wallet ti fa scegliere l'account a ogni connessione: puoi firmare con la chiave di genesi o con un backup. Per cambiare account ripremi il pulsante e scegline un altro.",
readCtrlBtn: "Leggi i controller della UP su questa rete",
removeDivider: "— oppure, dopo aver perso una chiave —",
removeLabel: "Controller da rimuovere",
removeHint: "L'elenco mostra tutti i controller tranne quello connesso nel wallet: chi firma non può rimuovere se stesso. Per rimuovere la chiave connessa, connetti un altro amministratore (per esempio il backup). Per la chiave di un dispositivo (app o estensione), se ce l'hai ancora, prima manda alla UP il suo saldo (pannello \"Questo telefono\" o \"Questo computer\", \"Manda il saldo della chiave alla UP\"): dopo la revoca la chiave può ancora spostarlo, ma una chiave persa non ha copie.",
removeAck: "Confermo: questa chiave è persa o non mi serve più. Il controller connesso nel wallet resta e continua a gestire la UP.",
removeBtn: "Rimuovi il controller selezionato",
removeNone: "(nessun controller rimovibile)",
copyLogBtn: "Copia il log",
copiedLog: "Log copiato.",
busyStart: "In corso: lettura dei dati e simulazione. Se serve una firma, MetaMask si apre tra qualche secondo.",
connectedBadge: "Connesso",
connectionRejected: "Connessione rifiutata o fallita",
notConnected: "Non connesso.",
wcDisconnectBtn: "Scollega",
unknownNetworkLabel: (v) => `rete sconosciuta (chainId ${v.chainId})`,
customNetName: "Rete custom",
rpcChainMismatchErr: (v) => `❌ BLOCCANTE — l'RPC risponde con chainId ${v.rpcChainId}, ma la rete selezionata è ${v.netName} (chainId ${v.chainId}). Non procedere.`,
signerChangedErr: (v) => `❌ BLOCCANTE — l'account attivo nel wallet (${v.now}) non è quello verificato (${v.checked}). Rifai la verifica.`,
walletNetworkCheckFailed: (v) => `⚠️ Non è stato possibile verificare la rete del wallet firmatario — controlla tu stesso che MetaMask sia su ${v.netName} prima di procedere.`,
walletWrongNetwork: (v) => `❌ BLOCCANTE — il wallet firmatario è connesso alla rete con chainId ${v.walletChainId}, ma qui hai selezionato ${v.netName} (chainId ${v.chainId}). Cambia rete in MetaMask prima di continuare.`,
customRpcLabel: "RPC URL custom",
customRpcPlaceholder: "https://...",
customExplorerLabel: "Explorer URL custom (opzionale)",
customExplorerPlaceholder: "https://.../address/",
networkFilterPlaceholder: "Filtra per nome... (es. base, polygon, arbitrum)",
footerHtml: `Servizi di consulenza in integrazione dati & blockchain a cura di ChainIntegrate <a href="https://www.linkedin.com/company/chainintegrate" target="_blank" rel="noopener" aria-label="LinkedIn" class="footer-li"><svg width="20" height="20" viewBox="0 0 20 20"><rect width="20" height="20" rx="4" fill="#0A66C2"/><text x="10" y="15" text-anchor="middle" font-family="Arial, sans-serif" font-size="12" font-weight="700" fill="#fff">in</text></svg></a> · <a href="https://t.me/Simone_1977_2" target="_blank" rel="noopener">Assistenza via Telegram</a> · <a href="https://github.com/ChainIntegrate/Cross_Chain" target="_blank" rel="noopener">Codice sorgente su GitHub</a> · <a href="privacy.html">Privacy</a>`,
placeholderAddr: "0x...",
bkAckRequired: "Spunta la conferma prima di rimuovere.",
bkAddOk: (v) => `✅ Backup registrato: ${v.addr} ha gli stessi permessi del controller che ha firmato. Custodisci la sua seed a parte, mai insieme alla chiave di genesi.`,
bkAdmin: "amministratore",
bkAlready: "Questo indirizzo è già un controller della UP su questa rete.",
bkBadAddr: "Indirizzo del backup non valido.",
bkCancelled: "Annullato in MetaMask: nessuna transazione inviata.",
bkChangedRead: "La UP, la rete o il wallet sono cambiati: premi di nuovo «Leggi i controller».",
bkContract: "A questo indirizzo c'è un contratto: come backup serve un account normale (per esempio un account MetaMask).",
bkError: (v) => `Errore: ${v.err}`,
bkGasOk: (v) => `Gas stimato: circa ${v.cost} ${v.cur}, pagato da ${v.addr} (saldo ${v.bal} ${v.cur}).`,
bkGenesis: "chiave di genesi (dalla calldata originale)",
bkGenesisWarn: "Stai rimuovendo la chiave di genesi da questa rete. Qui la UP resta gestita dal wallet connesso; sulle reti nuove però la UP nascerà comunque controllata solo dalla chiave di genesi: senza di lei non potrai più fare deploy su reti nuove.",
bkNeedNet: "Scegli prima la rete (sezione 1).",
bkNeedUp: "Inserisci prima l'indirizzo della UP (sezione 2).",
bkNoBackupAfter: "Dopo la rimozione su questa rete resterà un solo controller amministratore: aggiungi subito un nuovo backup.",
bkNoGas: (v) => `❌ ${v.addr} ha ${v.bal} ${v.cur} su questa rete, ne servono circa ${v.cost} per il gas. Niente inviato: aggiungi un po' di ${v.cur || "valuta della rete"} a questo account, oppure connetti un altro controller amministratore che ne abbia.`,
bkNotDeployed: (v) => `La UP ${v.up} non è deployata su questa rete.`,
bkPickRemove: "Scegli il controller da rimuovere.",
bkPlanAdd: (v) => `Piano (una transazione, firmata da ${v.signer} tramite il Key Manager ${v.km}):\n- AddressPermissions[] da ${v.len} a ${v.len1} voci, posizione ${v.len} → ${v.backup}\n- permessi del backup → ${v.perms} (identici a quelli di chi firma: ${v.names})${v.extra}`,
bkPlanClear: "\n- cancellate anche le sue restrizioni AllowedCalls / AllowedERC725YDataKeys",
bkPlanExtra: "\n- copiate anche le restrizioni AllowedCalls / AllowedERC725YDataKeys di chi firma",
bkPlanMoved: (v) => ` (l'ultima voce, ${v.addr}, prende il suo posto)`,
bkPlanRemove: (v) => `Piano (una transazione, firmata da ${v.signer} tramite il Key Manager ${v.km}):\n- permessi di ${v.target} → cancellati\n- AddressPermissions[]: tolta la posizione ${v.index}${v.moved}, da ${v.len} a ${v.len1} voci${v.extra}`,
bkReadFail: (v) => `Lettura non riuscita: ${v.err}`,
bkReading: "Lettura dei controller...",
bkRemoveOk: (v) => `✅ Controller ${v.addr} rimosso da questa rete.`,
bkRoleBad: "voce non valida nella lista",
bkRoleCtrl: "controller",
bkRoleEp: "EntryPoint 4337 (gas relay): non è un controller per firmare",
bkRoleUrd: "Universal Receiver Delegate: infrastruttura, non è un controller per firmare",
bkRoleYou: "il wallet connesso (sezione 3)",
bkRpcBehind: (v) => `L'RPC è ancora al blocco ${v.head}, prima della tua ultima modifica (blocco ${v.block}): mostrerebbe la lista com'era prima. Riprova tra qualche secondo.`,
bkSameAsSigner: "Il backup deve essere un account diverso da quello che firma.",
bkSignerNone: "Collega il wallet della sezione 3: deve essere un controller amministratore di questa UP.",
bkSignerNotAdmin: (v) => `Il wallet connesso (${v.addr}) è un controller, ma non ha ADDCONTROLLER ed EDITPERMISSIONS: non può aggiungere né rimuovere controller.`,
bkSignerNotCtrl: (v) => `Il wallet connesso (${v.addr}) non è un controller di questa UP su questa rete: collega in MetaMask un controller amministratore (per una UP appena deployata, la chiave di genesi importata).`,
bkSignerOk: (v) => `Firmerà il wallet connesso: ${v.addr} (amministratore).`,
bkSimFail: (v) => `❌ La simulazione fallisce: ${v.err}. Niente è stato inviato.`,
bkSimOk: "✅ Simulazione riuscita. Conferma la transazione in MetaMask.",
bkSimulating: "Simulazione...",
bkSummaryMissing: (v) => `⚠️ Nessun backup su ${v.net}: c'è un solo controller amministratore. Se perdi la sua chiave resti fuori da questa UP su questa rete.`,
bkSummaryNoAdmin: (v) => `❌ Su ${v.net} nessun controller ha ADDCONTROLLER ed EDITPERMISSIONS: da qui non si può aggiungere un backup.`,
bkSummaryOk: (v) => `✅ Backup presente su ${v.net}: ${v.n} controller con gli stessi permessi di amministrazione.`,
bkSystem: "Questo indirizzo è la UP, il suo Key Manager, l'EntryPoint o il Universal Receiver Delegate: non può fare da backup.",
bkTx: (v) => `Tx: ${v.hash}`,
bkTxFailed: "❌ La transazione è stata inclusa ma è fallita: niente è cambiato.",
bkVerifyBad: (v) => `⚠️ Transazione confermata, ma la rilettura non torna (${v.what}): ricontrolla con «Leggi i controller».`,
bkWaiting: "In attesa di conferma...",
bkWhyAdmin: "Controller amministratore: può firmare qualsiasi operazione della UP e aggiungere o togliere altri controller.",
bkWhyBad: "Questa voce della lista non contiene un indirizzo valido: non è un controller funzionante.",
bkWhyEp: "Serve al gas relay: esegue le operazioni che il tuo controller ha firmato, così il controller non deve avere gas. Può solo chiamare contratti e inviare fondi per conto di una firma valida di un tuo controller; non può cambiare i dati, i permessi o i controller della UP.",
bkWhyGenesis: "È la chiave di genesi: su ogni nuova rete la UP nasce controllata solo da lei.",
bkWhyLimited: "Controller con permessi limitati: può fare solo quello che dicono i permessi qui sotto; non può gestire gli altri controller, quindi non fa da backup.",
bkWhyPair: "Ha gli stessi permessi di un altro amministratore: se perdi una delle due chiavi, l'altra fa da backup.",
bkWhyUrd: "Serve a tenere aggiornata, nei dati della UP, la lista dei token e degli NFT LUKSO (LSP7/LSP8) che la UP riceve. Non firma operazioni e non può spostare fondi né cambiare i controller.",
bkWhyYou: "È il wallet connesso adesso: firmerà le operazioni di questa sezione.",
},
en: {
pageTitle: "UP backup controller",
h1: "UP backup controller",
subtitle: "Adds a second controller to your Universal Profile on a network, with the same permissions as the signing controller, or removes a lost key. A single Key Manager transaction, simulated first and re-read after. The page never asks for private keys: you sign, from your own wallet.",
langToggleBtn: "Italiano",
panel0Title: "0 · Why it matters",
panel1Title: "1 · Network",
panel2Title: "2 · The UP",
connectUpBtn: "Read the address from your UP (extension or app)",
upAddressLabel: "UP address",
panel3Title: "3 · The signing controller (MetaMask)",
signerNote: "The wallet connected here <b>must be an admin controller of the UP</b> on this network (with ADDCONTROLLER and EDITPERMISSIONS), and it pays the gas. On a UP you just deployed, that is the <b>genesis key</b> imported into MetaMask: if you made the deploy with that account, it is already the right one. Do it <b>on every network</b>: each network has its own list of controllers, <b>LUKSO included</b>. There the signer is the controller the UP has today on LUKSO, for example the Universal Profile extension's key imported into MetaMask, which may differ from the genesis key. On a phone, where the browser has no MetaMask, the button connects the MetaMask app with WalletConnect: the transaction reaches the app to approve. <b>Never accept on this account an \"upgrade to a smart account\" (EIP-7702) you did not ask for</b>: delegated to a malicious contract, it would give that contract full control of the UP.",
panel4Title: "4 · The UP's controllers on this network",
genesisUnknown: "Genesis key not recognized: the UP's creation transaction was not found on the LUKSO explorer. Everything else works the same.",
backupNote: "<b>The risk here is loss, not theft.</b> On every network where you redeploy, the UP is born controlled only by the <b>genesis key</b>: the key string you extracted from the Universal Profile extension. If you lose it (a broken computer, a key never saved, a forgotten password) and no other controller has the same permissions, you are locked out of this UP on this network for good, with everything it holds. No one can fix it. A <b>backup controller</b> is a second account (for example another MetaMask account, with its own seed phrase kept separately) with <b>exactly the same permissions</b> as the controller signing here. If you lose one of the two keys, the other one still signs: it adds a new backup and removes the lost key. If the one you lose is the genesis key, the only thing you can no longer do is deploy on new networks, because there the UP is born with that key only.",
backupNotRead: "Controllers not read yet.",
addBackupBtn: "Add the backup controller",
phoneDivider: "— or, for UP Wallet: Android app or browser extension —",
phoneNote: "<b>Authorize a device.</b> Only on LUKSO? You can also do it with the Universal Profile extension or app, without MetaMask: <a href=\"up-authorize-lukso.html\" style=\"color:var(--accent);\">Authorize a device on LUKSO</a>. The UP Wallet app for Android (from 0.9.0) signs with a key created and kept on the phone; the UP Wallet browser extension with a key kept on the computer. Here you add it to the UP as a controller <b>with no admin permissions</b>: it <b>cannot</b> add controllers, change permissions or extensions. It <b>can use all the UP's funds</b>, though: calls and sends to any address (SUPER_CALL, SUPER_TRANSFERVALUE), signatures (SIGN), gas paid by the site (4337) and writing the profile only (SETDATA, limited to the <code>LSP3Profile</code> key). Whoever unlocks the device and passes the fingerprint, PIN, passkey or password can move the funds: authorize only a device of yours. The admin controller connected here signs, once per network. If you lose the device or remove the app or the extension, remove its key below, network by network.",
phoneAddrLabel: "The device key's address (the app shows it, \"This phone\" panel, or the extension, \"This computer\" panel)",
phoneLinkTailNote: () => `The link carries the address <code>${phoneLinkAddr ? phoneLinkAddr.slice(0, 10) : ""}…</code>. Anyone can make such a link: open your UP Wallet app ("This phone") or your extension ("This computer") and <b>type here the last 8 characters</b> of the address it shows.`,
phoneLinkTailLabel: "Last 8 characters of the address, from the app or the extension",
phoneLinkTailOk: "✅ It matches: the link's address is your device's.",
phoneLinkTailBad: "❌ It does not match. Check the app or the extension again: if this is right, the link is not yours and must not be used.",
bkPhoneLinkAck: "The device's address comes from the link: first type the last 8 characters your app or your extension shows. Someone else's link could give you their address, and with this authorization they could move the UP's funds.",
addPhoneBtn: "Authorize the device on this network",
phoneNameLabel: "The device's name (optional): saved on the UP with the authorization, to recognize it in the list. Public, as the controllers' addresses are: no personal data",
phoneNamePh: "e.g. Office PC · extension",
deviceComputer: "Computer · UP Wallet extension",
devicePhone: "Phone · UP Wallet app",
nameDivider: "— or, a controller's name —",
nameNote: "<b>A name for each controller</b> (\"Office PC · extension\", \"MetaMask backup\"), saved on the UP: this page and UP Wallet show it on every device. Like the controllers, it is <b>per network</b>: repeat it on every network. It is public, as the controllers' addresses are: no personal data. At most 64 characters; leave it empty to remove it. The admin controller connected here signs it, with one transaction on this network. A label only: no permission changes.",
nameSelectLabel: "Controller",
nameInputLabel: "Name (empty to remove it)",
nameBtn: "Save the name on this network",
nameNone: "No controllers read.",
bkName: (v) => `Name: ${v.name}`,
bkPlanName: (v) => `Plan (one transaction, signed by ${v.signer} through the Key Manager ${v.km}):\n- name of ${v.addr} → ${v.name}`,
bkPlanNameLine: (v) => `- name → ${v.name}`,
bkPlanNameClear: "\n- name → cleared",
bkNameCleared: "none (removed)",
bkNameSame: "The controller already has this name on this network.",
bkNameOk: (v) => `✅ Name of ${v.addr} on this network: ${v.name}.`,
bkPlanPhone: (v) => `Plan (one transaction, signed by ${v.signer} through the Key Manager ${v.km}):\n- AddressPermissions[] from ${v.len} to ${v.len1} entries, position ${v.len} → ${v.phone}\n- the device's permissions → ${v.perms} (${v.names})\n- allowed data keys → LSP3Profile only (the profile)`,
bkPhoneOk: (v) => `✅ Device authorized on this network: ${v.addr}, with no admin permissions. Repeat on every network where you use the UP. To revoke it: "Remove the selected controller".`,
bkPhoneAdmin: "This address is already an admin controller of the UP: it does not need to be authorized as a device.",
backupAddrLabel: "Backup controller address (a different MetaMask account, kept separately)",
connectSigner5Btn: "Connect the UP's controller (MetaMask)",
signerPickHint: "The wallet lets you choose the account on every connection: you can sign with the genesis key or with a backup. To switch account, press the button again and pick another one.",
readCtrlBtn: "Read the UP's controllers on this network",
removeDivider: "— or, after losing a key —",
removeLabel: "Controller to remove",
removeHint: "The list shows every controller except the one connected in the wallet: the signer cannot remove itself. To remove the connected key, connect another admin (for example the backup). For a device key (app or extension) you still have, first send its balance to the UP (panel \"This phone\" or \"This computer\", \"Send the key's balance to the UP\"): after the revoke the key can still move it, but a lost key has no copy.",
removeAck: "I confirm: this key is lost or no longer needed. The controller connected in the wallet stays and keeps managing the UP.",
removeBtn: "Remove the selected controller",
removeNone: "(no removable controller)",
copyLogBtn: "Copy the log",
copiedLog: "Log copied.",
busyStart: "Working: reading the data and simulating. If a signature is needed, MetaMask opens in a few seconds.",
connectedBadge: "Connected",
connectionRejected: "Connection rejected or failed",
notConnected: "Not connected.",
wcDisconnectBtn: "Disconnect",
unknownNetworkLabel: (v) => `unknown network (chainId ${v.chainId})`,
customNetName: "Custom network",
rpcChainMismatchErr: (v) => `❌ BLOCKING — the RPC answers with chainId ${v.rpcChainId}, but the selected network is ${v.netName} (chainId ${v.chainId}). Do not proceed.`,
signerChangedErr: (v) => `❌ BLOCKING — the active wallet account (${v.now}) is not the one that was verified (${v.checked}). Verify again.`,
walletNetworkCheckFailed: (v) => `⚠️ Could not verify the signing wallet's network — check yourself that MetaMask is on ${v.netName} before proceeding.`,
walletWrongNetwork: (v) => `❌ BLOCKING — the signing wallet is connected to chainId ${v.walletChainId}, but you selected ${v.netName} (chainId ${v.chainId}) here. Switch network in MetaMask before continuing.`,
customRpcLabel: "Custom RPC URL",
customRpcPlaceholder: "https://...",
customExplorerLabel: "Custom explorer URL (optional)",
customExplorerPlaceholder: "https://.../address/",
networkFilterPlaceholder: "Filter by name... (e.g. base, polygon, arbitrum)",
footerHtml: `Data & blockchain integration consulting by ChainIntegrate <a href="https://www.linkedin.com/company/chainintegrate" target="_blank" rel="noopener" aria-label="LinkedIn" class="footer-li"><svg width="20" height="20" viewBox="0 0 20 20"><rect width="20" height="20" rx="4" fill="#0A66C2"/><text x="10" y="15" text-anchor="middle" font-family="Arial, sans-serif" font-size="12" font-weight="700" fill="#fff">in</text></svg></a> · <a href="https://t.me/Simone_1977_2" target="_blank" rel="noopener">Support via Telegram</a> · <a href="https://github.com/ChainIntegrate/Cross_Chain" target="_blank" rel="noopener">Source code on GitHub</a> · <a href="privacy.html">Privacy</a>`,
placeholderAddr: "0x...",
bkAckRequired: "Tick the confirmation before removing.",
bkAddOk: (v) => `✅ Backup registered: ${v.addr} has the same permissions as the controller that signed. Keep its seed phrase separately, never together with the genesis key.`,
bkAdmin: "admin",
bkAlready: "This address is already a controller of the UP on this network.",
bkBadAddr: "Invalid backup address.",
bkCancelled: "Cancelled in MetaMask: no transaction sent.",
bkChangedRead: "The UP, the network or the wallet changed: press \"Read the controllers\" again.",
bkContract: "There is a contract at this address: a backup must be a plain account (for example a MetaMask account).",
bkError: (v) => `Error: ${v.err}`,
bkGasOk: (v) => `Estimated gas: about ${v.cost} ${v.cur}, paid by ${v.addr} (balance ${v.bal} ${v.cur}).`,
bkGenesis: "genesis key (from the original calldata)",
bkGenesisWarn: "You are removing the genesis key from this network. Here the UP stays managed by the connected wallet; on new networks, though, the UP will still be born controlled only by the genesis key: without it you can no longer deploy on new networks.",
bkNeedNet: "Choose the network first (section 1).",
bkNeedUp: "Enter the UP address first (section 2).",
bkNoBackupAfter: "After the removal only one admin controller will remain on this network: add a new backup right away.",
bkNoGas: (v) => `❌ ${v.addr} holds ${v.bal} ${v.cur} on this network; about ${v.cost} is needed for gas. Nothing sent: add a little ${v.cur || "of the network's currency"} to this account, or connect another admin controller that has some.`,
bkNotDeployed: (v) => `The UP ${v.up} is not deployed on this network.`,
bkPickRemove: "Choose the controller to remove.",
bkPlanAdd: (v) => `Plan (one transaction, signed by ${v.signer} through the Key Manager ${v.km}):\n- AddressPermissions[] from ${v.len} to ${v.len1} entries, position ${v.len} → ${v.backup}\n- backup permissions → ${v.perms} (identical to the signer's: ${v.names})${v.extra}`,
bkPlanClear: "\n- its AllowedCalls / AllowedERC725YDataKeys restrictions are cleared too",
bkPlanExtra: "\n- the signer's AllowedCalls / AllowedERC725YDataKeys restrictions are copied too",
bkPlanMoved: (v) => ` (the last entry, ${v.addr}, takes its place)`,
bkPlanRemove: (v) => `Plan (one transaction, signed by ${v.signer} through the Key Manager ${v.km}):\n- permissions of ${v.target} → cleared\n- AddressPermissions[]: position ${v.index} removed${v.moved}, from ${v.len} to ${v.len1} entries${v.extra}`,
bkReadFail: (v) => `Reading failed: ${v.err}`,
bkReading: "Reading the controllers...",
bkRemoveOk: (v) => `✅ Controller ${v.addr} removed from this network.`,
bkRoleBad: "invalid entry in the list",
bkRoleCtrl: "controller",
bkRoleEp: "4337 EntryPoint (gas relay): not a controller that signs",
bkRoleUrd: "Universal Receiver Delegate: infrastructure, not a controller that signs",
bkRoleYou: "the connected wallet (section 3)",
bkRpcBehind: (v) => `The RPC is still at block ${v.head}, before your last change (block ${v.block}): it would show the list as it was before. Try again in a few seconds.`,
bkSameAsSigner: "The backup must be a different account from the one signing.",
bkSignerNone: "Connect the wallet of section 3: it must be an admin controller of this UP.",
bkSignerNotAdmin: (v) => `The connected wallet (${v.addr}) is a controller, but it lacks ADDCONTROLLER and EDITPERMISSIONS: it cannot add or remove controllers.`,
bkSignerNotCtrl: (v) => `The connected wallet (${v.addr}) is not a controller of this UP on this network: connect an admin controller in MetaMask (for a UP you just deployed, the imported genesis key).`,
bkSignerOk: (v) => `The connected wallet will sign: ${v.addr} (admin).`,
bkSimFail: (v) => `❌ The simulation fails: ${v.err}. Nothing was sent.`,
bkSimOk: "✅ Simulation passed. Confirm the transaction in MetaMask.",
bkSimulating: "Simulating...",
bkSummaryMissing: (v) => `⚠️ No backup on ${v.net}: there is only one admin controller. If you lose its key you are locked out of this UP on this network.`,
bkSummaryNoAdmin: (v) => `❌ On ${v.net} no controller has ADDCONTROLLER and EDITPERMISSIONS: a backup cannot be added from here.`,
bkSummaryOk: (v) => `✅ Backup in place on ${v.net}: ${v.n} controllers with the same admin permissions.`,
bkSystem: "This address is the UP, its Key Manager, the EntryPoint or the Universal Receiver Delegate: it cannot be a backup.",
bkTx: (v) => `Tx: ${v.hash}`,
bkTxFailed: "❌ The transaction was included but failed: nothing changed.",
bkVerifyBad: (v) => `⚠️ Transaction confirmed, but the re-read does not match (${v.what}): check again with "Read the controllers".`,
bkWaiting: "Waiting for confirmation...",
bkWhyAdmin: "Admin controller: it can sign any operation of the UP and add or remove other controllers.",
bkWhyBad: "This entry of the list holds no valid address: it is not a working controller.",
bkWhyEp: "It is used by the gas relay: it runs the operations your controller signed, so the controller needs no gas. It can only call contracts and send funds on behalf of a valid signature by one of your controllers; it cannot change the UP's data, permissions or controllers.",
bkWhyGenesis: "It is the genesis key: on every new network the UP is born controlled by this key only.",
bkWhyLimited: "Controller with limited permissions: it can only do what the permissions below say; it cannot manage the other controllers, so it is not a backup.",
bkWhyPair: "It has the same permissions as another admin: if you lose one of the two keys, the other one is the backup.",
bkWhyUrd: "It keeps the list of LUKSO tokens and NFTs (LSP7/LSP8) the UP receives up to date, in the UP's data. It does not sign operations and cannot move funds or change the controllers.",
bkWhyYou: "It is the wallet connected now: it will sign the operations of this section.",
},
};
function t(key, vars) {
const v = I18N[LANG][key];
return typeof v === "function" ? v(vars || {}) : v;
}
function applyI18n() {
document.documentElement.lang = LANG;
document.title = t("pageTitle");
document.querySelectorAll("[data-i18n]").forEach(el => { el.textContent = t(el.getAttribute("data-i18n")); });
document.querySelectorAll("[data-i18n-html]").forEach(el => { el.innerHTML = t(el.getAttribute("data-i18n-html")); });
document.querySelectorAll("[data-i18n-placeholder]").forEach(el => { el.placeholder = t(el.getAttribute("data-i18n-placeholder")); });
$("langToggle").textContent = t("langToggleBtn");
if (!signerAddress) setSignerStatus(`<span class="empty">${t("notConnected")}</span>`);
if (bk) renderBackup(); else if (!$("backupStatus").textContent.trim() || $("backupStatus").querySelector("[data-i18n]")) $("backupStatus").innerHTML = `<span class="empty">${t("backupNotRead")}</span>`;
$("genesisNote").textContent = genesisMissing ? t("genesisUnknown") : "";
}
$("langToggle").addEventListener("click", () => {
LANG = LANG === "it" ? "en" : "it"; SiteUI.saveLang(LANG);
applyI18n();
});
// ==================== APP ====================
const FACTORY_ADDRESS = "0x2300000A84D25dF63081feAa37ba6b62C4c89a30"; // LSP23 factory, same address on every EVM network
const DEPLOY_SELECTOR = "0x6a66a753"; // deployERC1167Proxies(...) on LSP23LinkedContractsFactory
// Data key prefix of LSP6 "AddressPermissions:Permissions:<address>" (bytes10 + bytes2 padding).
const PERM_PREFIX = "4b80742de2bf82acb3630000";
// Bit order as defined in @lukso/lsp6-contracts LSP6Constants.sol (bits 0..22).
const PERMISSION_BITS = [
"CHANGEOWNER","ADDCONTROLLER","EDITPERMISSIONS","ADDEXTENSIONS","CHANGEEXTENSIONS",
"ADDUNIVERSALRECEIVERDELEGATE","CHANGEUNIVERSALRECEIVERDELEGATE","REENTRANCY",
"SUPER_TRANSFERVALUE","TRANSFERVALUE","SUPER_CALL","CALL","SUPER_STATICCALL","STATICCALL",
"SUPER_DELEGATECALL","DELEGATECALL","DEPLOY","SUPER_SETDATA","SETDATA","ENCRYPT","DECRYPT",
"SIGN","EXECUTE_RELAY_CALL"
];
// Indirizzi di infrastruttura LUKSO ufficiale, riconoscibili e non legati a un singolo profilo.
// Stesso indirizzo su ogni rete dove LUKSO ha deployato gli stessi contratti (deploy deterministico).
// Verificato su explorer.execution.mainnet.lukso.network (contratto verificato, nome confermato).
const KNOWN_ADDRESSES = {
"0x7870c5b8bc9572a8001c3f96f7ff59961b23500d": {
labelKey: "knownLsp1Label",
noteKey: "knownLsp1Note"
}
};
// Nome rete leggibile a partire dal chainId, usato per mostrare all'utente a quale rete
// è connesso il wallet firmatario (LUKSO stessa non è nell'elenco CHAINS sopra perché
// quell'elenco è quello delle reti di destinazione del deploy, non della UP originale).
function chainDisplayName(chainId) {
if (chainId === 42) return "LUKSO Mainnet";
if (chainId === 4201) return "LUKSO Testnet";
const found = CHAINS.find(c => c.chainId === chainId);
return found ? found.name : t("unknownNetworkLabel", { chainId });
}
// --- Network: every redeploy network and LUKSO, where the UP was born (it has its own controller list) ---
const networkSelectEl = $("network");
const NETWORKS = [LUKSO_CHAIN, LUKSO_TESTNET_CHAIN, ...CHAINS];
function renderNetworkOptions(filter) {
const f = (filter || "").toLowerCase();
networkSelectEl.innerHTML = "";
NETWORKS.filter(c => c.name.toLowerCase().includes(f)).forEach(c => {
const opt = document.createElement("option");
opt.value = c.key;
opt.textContent = c.chainId ? `${c.name} (chainId ${c.chainId})` : c.name;
networkSelectEl.appendChild(opt);
});
}
renderNetworkOptions("");
$("networkFilter").addEventListener("input", (e) => {
renderNetworkOptions(e.target.value);
// Filtering can silently change the selected option: propagate it like a user selection.
networkSelectEl.dispatchEvent(new Event("change"));
});
networkSelectEl.addEventListener("change", () => {
$("customRpcWrap").style.display = networkSelectEl.value === "custom" ? "block" : "none";
});
function getNetwork() {
const key = networkSelectEl.value;
if (key === "custom") {
return { name: t("customNetName"), rpc: $("customRpc").value.trim(), explorer: $("customExplorer").value.trim() || null };
}
return NETWORKS.find(c => c.key === key);
}
// --- The UP: from the extension, or the Universal Profiles app (site-ui.js), or typed ---
$("connectUp").addEventListener("click", async () => {
try {
const a = await SiteUI.upAddress();
if (!a) return;
$("upAddress").value = ethers.getAddress(a);
$("upAddress").dispatchEvent(new Event("change"));
resetBackupView();
} catch (e) { /* rejected */ }
});
// --- The signing controller, via EIP-6963 (never the Universal Profile extension) ---
let signerProvider = null, signerAddress = null;
const discoveredProviders = [];
window.addEventListener("eip6963:announceProvider", (e) => discoveredProviders.push(e.detail));
window.dispatchEvent(new Event("eip6963:requestProvider"));
function setSignerStatus(html) { $("signerStatus").innerHTML = html; }
// The connected signer; through WalletConnect also the wallet's name and a button to disconnect (the way to
// pick another account there).
function showSigner(netLabel = "") {
const wc = signerProvider && signerProvider.isWalletConnect;
setSignerStatus(`<span class="badge ok">${t("connectedBadge")}</span> ${escapeHtml(signerAddress + netLabel)}` +
(wc ? `<div class="line-dim" style="margin-top:6px;">WalletConnect · ${escapeHtml(signerProvider.walletName)} <button type="button" id="signerDisconnect" class="secondary" style="width:auto; margin:0 0 0 8px; padding:4px 10px; font-size:12px;">${t("wcDisconnectBtn")}</button></div>` : ""));
if (wc) $("signerDisconnect").addEventListener("click", async () => {
await signerProvider.disconnect();
signerProvider = null; signerAddress = null; watchedSigner = null;
setSignerStatus(`<span class="empty">${t("notConnected")}</span>`);
resetBackupView();
});
}
async function connectSignerWallet() {
let candidate = discoveredProviders.find(p => !/lukso|universal profile/i.test(p.info.name))?.provider;
if (!candidate && window.ethereum && window.ethereum !== window.lukso) candidate = window.ethereum;
// No wallet in this browser (a phone): MetaMask on the phone through WalletConnect (site-ui.js).
if (!candidate) {
try { candidate = await SiteUI.walletConnectSigner({ chain: getNetwork }); } catch (e) { candidate = null; }
if (!candidate) {
if (!signerAddress) setSignerStatus(`<span class="empty">${t("notConnected")}</span>`);
return false;
}
}
try {
// Ask the wallet to show its account picker every time, so the signer can be chosen (genesis
// key, backup, ...). eth_requestAccounts alone silently returns the account already connected.
// Wallets without wallet_requestPermissions fall back to it; a refusal in the picker stops here.
try { await candidate.request({ method: "wallet_requestPermissions", params: [{ eth_accounts: {} }] }); }
catch (e) { if (e && e.code === 4001) throw e; }
const accounts = await candidate.request({ method: "eth_requestAccounts" });
signerAddress = accounts[0];
signerProvider = candidate;
watchSigner(candidate);
let netLabel = "";
try {
const chainIdHex = await candidate.request({ method: "eth_chainId" });
netLabel = ` · ${chainDisplayName(parseInt(chainIdHex, 16))}`;
} catch (e) { /* the address is shown even when the network cannot be read */ }
showSigner(netLabel);
return true;
} catch (e) {
setSignerStatus(`<span class="badge err">${t("connectionRejected")}</span>`);
return false;
}
}
let watchedSigner = null;
function watchSigner(p) {
if (watchedSigner === p || typeof p.on !== "function") return;
watchedSigner = p;
p.on("chainChanged", () => resetBackupView());
p.on("accountsChanged", (accs) => {
signerAddress = accs && accs[0] ? accs[0] : null;
if (signerAddress) showSigner(); else setSignerStatus(`<span class="empty">${t("notConnected")}</span>`);
resetBackupView();
});
}
// --- The genesis key(s): the controllers set by the UP's creation on LUKSO ---
// Read from the LUKSO explorer: the creation transaction's LSP23 calldata, straight or from its trace.
// The explorer is not trusted: a calldata counts only if it predicts exactly this UP's address.
// Used for the "genesis key" badge and the warning before removing it; nothing else depends on it.
const LUKSO_EXPLORER_API = "https://explorer.execution.mainnet.lukso.network/api/v2/";
let genesisCache = { up: "", list: [] }, genesisMissing = false;
async function explorerGet(path) {
const res = await fetch(LUKSO_EXPLORER_API + path, { referrerPolicy: "no-referrer", signal: AbortSignal.timeout(8000) });
if (!res.ok) throw new Error(`explorer HTTP ${res.status}`);
return res.json();
}
const isDeployCall = (to, input) =>
typeof input === "string" && input.toLowerCase().startsWith(DEPLOY_SELECTOR) && String(to || "").toLowerCase() === FACTORY_ADDRESS.toLowerCase();
const minimalProxyInitcode = (impl) => "0x3d602d80600a3d3981f3363d3d373d3d3d363d73" + impl.slice(2).toLowerCase() + "5af43d82803e903d91602b57fd5bf3";
// The controllers in an LSP23 calldata, or null when it does not create `up`.
function genesisFromCalldata(data, up) {
const coder = ethers.AbiCoder.defaultAbiCoder();
const [p, s, module, moduleCalldata] = coder.decode(["tuple(bytes32,uint256,address,bytes)", "tuple(uint256,address,bytes,bool,bytes)", "address", "bytes"], "0x" + data.slice(10));
const salt = ethers.keccak256(coder.encode(["bytes32", "address", "bytes", "bool", "bytes", "address", "bytes"], [p[0], s[1], s[2], s[3], s[4], module, moduleCalldata]));
if (ethers.getCreate2Address(FACTORY_ADDRESS, salt, ethers.keccak256(minimalProxyInitcode(p[2]))).toLowerCase() !== up.toLowerCase()) return null;
const [keys] = coder.decode(["bytes32[]", "bytes[]"], moduleCalldata);
return keys.map(k => k.toLowerCase().slice(2)).filter(k => k.startsWith(PERM_PREFIX)).map(k => "0x" + k.slice(24))
.filter(a => !KNOWN_ADDRESSES[a]).map(a => ethers.getAddress(a).toLowerCase());
}
async function genesisOf(up) {
if (genesisCache.up === up) return genesisCache.list;
let list = [];
try {
const addr = await explorerGet("addresses/" + up);
const txHash = addr.creation_transaction_hash || addr.creation_tx_hash;
if (txHash) {
const tx = await explorerGet("transactions/" + txHash);
let inputs = isDeployCall(tx.to && tx.to.hash, tx.raw_input || tx.input) ? [tx.raw_input || tx.input] : [];
if (!inputs.length) {
const trace = await explorerGet("transactions/" + txHash + "/raw-trace");
inputs = (Array.isArray(trace) ? trace : []).map(c => c.action || c).filter(a => isDeployCall(a.to, a.input)).map(a => a.input);
}
for (const data of inputs) { try { const g = genesisFromCalldata(data, up); if (g) { list = g; break; } } catch (e) { /* not this one */ } }
}
} catch (e) { /* explorer unreachable: no genesis badge */ }
genesisCache = { up, list };
genesisMissing = !list.length;
$("genesisNote").textContent = genesisMissing ? t("genesisUnknown") : "";
return list;
}
// ==================== 5. Backup controller ====================
// Adds a second controller with exactly the signer's permissions (and its AllowedCalls /
// AllowedERC725YDataKeys, if any), or removes a lost controller. One Key Manager transaction,
// simulated before MetaMask opens and re-read after confirmation. Detection and the list are
// read by backup-check.js, the same code that drives the alert on the other pages.
const BK = window.BackupCheck;
const KM_EXEC_IFACE = new ethers.Interface(["function execute(bytes) payable returns (bytes)"]);
const UP_DATA_IFACE = new ethers.Interface(["function setDataBatch(bytes32[] dataKeys, bytes[] dataValues)", "function getDataBatch(bytes32[]) view returns (bytes[])"]);
const LUKSO_CHAIN_IDS = [42, 4201];
let bk = null; // last read: { up, rpc, chainId, netName, provider, r, signer, signerCtrl, genesis, names }
let bkBusy = false;
const permNames = (p) => { const f = []; for (let i = 0; i < 24; i++) if ((p >> BigInt(i)) & 1n) f.push(i === 23 ? "ERC4337" : PERMISSION_BITS[i]); return f.join(", ") || "—"; };
const permHex = (p) => "0x" + p.toString(16);
function bkLog(msg, cls) {
const l = document.createElement("div");
if (cls) l.className = cls;
l.textContent = msg;
$("backupLog").appendChild(l);
// While an action runs, the fixed box shows its latest step (first line only).
if (bkBusy && !/^—— /.test(msg)) { const first = String(msg).split("\n")[0]; $("busyMsg").textContent = first.length > 200 ? first.slice(0, 200) + "…" : first; }
}
// The log keeps every action of the session: each one starts with time, UP and network.
function bkSeparator() {
const net = getNetwork();
const up = $("upAddress").value.trim();
bkLog(`—— ${new Date().toLocaleTimeString()} · UP ${up || "?"} · ${net ? net.name : "?"} ——`, "line-dim");
}
function setBusy(on) {
bkBusy = on;
if (on) $("busyMsg").textContent = t("busyStart");
$("busyToast").classList.toggle("on", on);
updateBackupButtons();
}
function setBackupStatus(text, cls) {
const el = $("backupStatus");
el.innerHTML = "";
const sp = document.createElement("div");
sp.className = cls || "";
sp.style.whiteSpace = "pre-wrap";
sp.textContent = text;
el.appendChild(sp);
}
// Same rule as backup-check.js: two admin controllers with the same permissions, ERC4337 ignored.
function backupAmong(list) {
const groups = {}, seen = new Set();
list.filter(c => c.role === "controller" && (c.perms & BK.ADMIN) === BK.ADMIN && !seen.has(c.address) && seen.add(c.address))
.forEach(c => { const g = (c.perms & ~BK.ERC4337).toString(16); groups[g] = (groups[g] || 0) + 1; });
return Object.values(groups).some(n => n >= 2);
}
function resetBackupView() {
if (!bk) return;
bk = null;
setBackupStatus(t("bkChangedRead"), "line-warn");
$("backupList").innerHTML = "";
updateBackupButtons();
}
function signerState(b) {
if (!b || !b.signer) return "none";
if (!b.signerCtrl) return "notCtrl";
return (b.signerCtrl.perms & BK.ADMIN) === BK.ADMIN ? "ok" : "notAdmin";
}
function updateBackupButtons() {
const ok = !bkBusy && bk && signerState(bk) === "ok";
$("addBackupBtn").disabled = !ok;
$("addPhoneBtn").disabled = !ok;
$("nameBtn").disabled = !ok || !$("nameSelect").value;
$("removeBtn").disabled = !ok || !$("removeSelect").value;
$("readCtrlBtn").disabled = bkBusy;
$("connectSigner").disabled = bkBusy;
}
function renderBackup() {
if (!bk) return;
const { r, netName } = bk;
const summary = r.hasBackup ? t("bkSummaryOk", { net: netName, n: Math.max(2, r.admins.length) })
: r.admins.length ? t("bkSummaryMissing", { net: netName }) : t("bkSummaryNoAdmin", { net: netName });
const st = signerState(bk);
const signerLine = st === "none" ? t("bkSignerNone") : st === "notCtrl" ? t("bkSignerNotCtrl", { addr: bk.signer })
: st === "notAdmin" ? t("bkSignerNotAdmin", { addr: bk.signer }) : t("bkSignerOk", { addr: bk.signer });
setBackupStatus(summary + "\n" + signerLine, r.hasBackup ? (st === "ok" ? "line-ok" : "line-warn") : r.admins.length ? "line-warn" : "line-err");
const box = $("backupList");
box.innerHTML = "";
r.controllers.forEach(c => {
const card = document.createElement("div");
card.className = "ctrl-card";
const a = document.createElement("div");
a.className = "addr";
a.textContent = `[${c.index}] ${c.address || "?"}`;
const name = c.address && bk.names[c.address.toLowerCase()];
let nameEl = null;
if (name) { nameEl = document.createElement("div"); nameEl.style.cssText = "font-weight:600; margin-top:2px; overflow-wrap:anywhere;"; nameEl.textContent = t("bkName", { name }); }
const role = document.createElement("div");
role.style.marginTop = "4px";
const badges = [];
if (c.role === "entrypoint") badges.push(["ok", t("bkRoleEp")]);
else if (c.role === "urd") badges.push(["ok", t("bkRoleUrd")]);
else if (c.role === "malformed") badges.push(["err", t("bkRoleBad")]);
else {
if (bk.signer && c.address.toLowerCase() === bk.signer.toLowerCase()) badges.push(["ok", t("bkRoleYou")]);
else badges.push(["warn", t("bkRoleCtrl")]);
if ((c.perms & BK.ADMIN) === BK.ADMIN) badges.push(["err", t("bkAdmin")]);
if (bk.genesis.includes(c.address.toLowerCase())) badges.push(["warn", t("bkGenesis")]);
}
// A space between badges too, so a copied list stays readable.
badges.forEach(([cls, text], i) => { const s = document.createElement("span"); s.className = "badge " + cls; s.style.marginRight = "6px"; s.textContent = text; if (i) role.append(" "); role.appendChild(s); });
// What it is for, in plain words.
const why = [];
if (c.role === "entrypoint") why.push(t("bkWhyEp"));
else if (c.role === "urd") why.push(t("bkWhyUrd"));
else if (c.role === "malformed") why.push(t("bkWhyBad"));
else {
const admin = (c.perms & BK.ADMIN) === BK.ADMIN;
why.push(t(admin ? "bkWhyAdmin" : "bkWhyLimited"));
if (admin && r.admins.some(o => o !== c && (o.perms & ~BK.ERC4337) === (c.perms & ~BK.ERC4337))) why.push(t("bkWhyPair"));
if (bk.genesis.includes(c.address.toLowerCase())) why.push(t("bkWhyGenesis"));
if (bk.signer && c.address.toLowerCase() === bk.signer.toLowerCase()) why.push(t("bkWhyYou"));
}
const whyEl = document.createElement("div");
whyEl.style.cssText = "font-size:12.5px; color:var(--text); margin-top:6px; line-height:1.5;";
whyEl.textContent = why.join(" ");
const flags = document.createElement("div");
flags.className = "flags";
flags.textContent = `${permHex(c.perms)} — ${permNames(c.perms)}`;
card.append(a, ...(nameEl ? [nameEl] : []), role, whyEl, flags);
box.appendChild(card);
});
const sel = $("removeSelect");
const prev = sel.value;
sel.innerHTML = "";
const removable = r.controllers.filter(c => c.role === "controller" && !(bk.signer && c.address.toLowerCase() === bk.signer.toLowerCase()));
if (!removable.length) {
const o = document.createElement("option"); o.value = ""; o.textContent = t("removeNone"); sel.appendChild(o);
} else {
removable.forEach(c => {
const o = document.createElement("option");
o.value = c.address;
const tags = [(c.perms & BK.ADMIN) === BK.ADMIN ? t("bkAdmin") : t("bkRoleCtrl")];
if (bk.genesis.includes(c.address.toLowerCase())) tags.push(t("bkGenesis"));
const nm = bk.names[c.address.toLowerCase()];
o.textContent = `${nm ? nm + " · " : ""}${c.address} — ${permHex(c.perms)} · ${tags.join(", ")}`;
sel.appendChild(o);
});
if (removable.some(c => c.address === prev)) sel.value = prev;
}
// Any controller can get a name, the connected one included.
const nsel = $("nameSelect");
const nprev = nsel.value;
nsel.innerHTML = "";
const nameable = r.controllers.filter(c => c.role === "controller");
if (!nameable.length) { const o = document.createElement("option"); o.value = ""; o.textContent = t("nameNone"); nsel.appendChild(o); }
nameable.forEach(c => {
const o = document.createElement("option");
o.value = c.address;
const nm = bk.names[c.address.toLowerCase()];
o.textContent = `${nm ? nm + " · " : ""}${c.address}${bk.signer && c.address.toLowerCase() === bk.signer.toLowerCase() ? " · " + t("bkRoleYou") : ""}`;
nsel.appendChild(o);
});
if (nameable.some(c => c.address === nprev)) nsel.value = nprev;
else $("nameInput").value = (nsel.value && bk.names[nsel.value.toLowerCase()]) || "";
updateBackupButtons();
}
// Reads the UP's controllers on the selected network. Returns the state or null (and says why).
// The block of this page's last backup write, per UP and chain. Later reads are pinned at or after it:
// a load-balanced RPC answering from an older node would otherwise show the list as it was before the
// write, and the next write would overwrite an entry (AUDIT 2026-10-02 L-4).
let bkSeen = { key: "", block: 0 };
async function readBackup() {
bk = null;
$("backupList").innerHTML = "";
updateBackupButtons();
const raw = $("upAddress").value.trim();
if (!ethers.isAddress(raw)) { setBackupStatus(t("bkNeedUp"), "line-err"); return null; }
const net = getNetwork();
if (!net || !net.rpc) { setBackupStatus(t("bkNeedNet"), "line-err"); return null; }
setBackupStatus(t("bkReading"), "line-dim");
try {
const up = ethers.getAddress(raw);
const probe = new ethers.JsonRpcProvider(net.rpc, undefined, { batchMaxCount: 1 });
const chainId = Number(await probe.send("eth_chainId", []));
if (net.chainId && chainId !== net.chainId) { setBackupStatus(t("rpcChainMismatchErr", { rpcChainId: chainId, netName: net.name, chainId: net.chainId }), "line-err"); return null; }
const provider = new ethers.JsonRpcProvider(net.rpc, chainId, { staticNetwork: true, batchMaxCount: 1 });
if ((await provider.getCode(up)) === "0x") { setBackupStatus(t("bkNotDeployed", { up }), "line-err"); return null; }
let at;
if (bkSeen.key === `${chainId}:${up}`) {
let head = 0;
for (let i = 0; i < 6; i++) { if (i) await new Promise(res => setTimeout(res, 1500)); head = await provider.getBlockNumber(); if (head >= bkSeen.block) break; }
if (head < bkSeen.block) { setBackupStatus(t("bkRpcBehind", { block: bkSeen.block, head }), "line-err"); return null; }
at = { blockTag: head };
}
const r = await BK.read(provider, up, at);
const signer = signerAddress ? ethers.getAddress(signerAddress) : null;
const signerCtrl = signer ? r.controllers.find(c => c.role === "controller" && c.address === signer) || null : null;
// The genesis controllers, from the UP's creation transaction on LUKSO (empty when not found).
const genesis = await genesisOf(up);
// The controllers' names kept on the UP (labels only).
const names = await BK.readNames(provider, up, r.controllers.map(c => c.address), at).catch(() => ({}));
const netName = net.chainId ? net.name : `${t("customNetName")} (chainId ${chainId})`;
bk = { up, rpc: net.rpc, chainId, netName, provider, r, signer, signerCtrl, genesis, names };
renderBackup();
return bk;
} catch (e) {
setBackupStatus(t("bkReadFail", { err: e.shortMessage || e.message }), "line-err");
return null;
}
}
$("readCtrlBtn").addEventListener("click", async () => {
if (bkBusy) return;
bkSeparator();
setBusy(true); $("busyMsg").textContent = t("bkReading");
try { await readBackup(); } finally { setBusy(false); }
});
// Connecting reads the controllers right away when UP and network are set.
$("connectSigner").addEventListener("click", async () => {
if (bkBusy) return;
if (!(await connectSignerWallet())) return;
if (!ethers.isAddress($("upAddress").value.trim())) return;
setBusy(true); $("busyMsg").textContent = t("bkReading");
try { await readBackup(); } finally { setBusy(false); }
});
$("removeSelect").addEventListener("change", updateBackupButtons);
$("nameSelect").addEventListener("change", () => { $("nameInput").value = (bk && $("nameSelect").value && bk.names[$("nameSelect").value.toLowerCase()]) || ""; updateBackupButtons(); });
$("copyBackupLog").addEventListener("click", async () => {
try { await navigator.clipboard.writeText($("backupLog").innerText); $("copyBackupLog").textContent = t("copiedLog"); }
catch (e) { /* clipboard not allowed: the log can still be selected by hand */ }
setTimeout(() => { $("copyBackupLog").textContent = t("copyLogBtn"); }, 1500);
});
// A fresh read, then the checks every write needs: admin signer, wallet on the same chain.
async function freshAdminState() {
const b = await readBackup();
if (!b) return null;
const st = signerState(b);
if (st !== "ok") { bkLog(st === "none" ? t("bkSignerNone") : t(st === "notCtrl" ? "bkSignerNotCtrl" : "bkSignerNotAdmin", { addr: b.signer }), "line-err"); return null; }
let walletChainId;
try { walletChainId = parseInt(await signerProvider.request({ method: "eth_chainId" }), 16); }
catch (e) { bkLog(t("walletNetworkCheckFailed", { netName: b.netName }), "line-err"); return null; }
if (walletChainId !== b.chainId) { bkLog(t("walletWrongNetwork", { walletChainId, netName: b.netName, chainId: b.chainId }) + (signerProvider.isWalletConnect ? " " + signerProvider.wrongChainText() : ""), "line-err"); return null; }
b.km = b.r.km ? ethers.getAddress(b.r.km) : null;
if (!b.km || (await b.provider.getCode(b.km)) === "0x") { bkLog(t("bkReadFail", { err: "Key Manager" }), "line-err"); return null; }
return b;
}
// After a write: every controller listed just before its block (except the one removed) must still be
// listed. The "before" list is read at the previous block, not taken from the page's own read: a stale
// read is exactly what could have made the write overwrite an entry (AUDIT 2026-10-02 L-4).
async function stillListed(b, at, removed) {
const [before, after] = await Promise.all([BK.read(b.provider, b.up, { blockTag: at.blockTag - 1 }), BK.read(b.provider, b.up, at)]);
const now = new Set(after.controllers.map(c => (c.address || "").toLowerCase()));
return before.controllers.filter(c => c.address && c.address.toLowerCase() !== String(removed || "").toLowerCase() && !now.has(c.address.toLowerCase()))
.map(c => `${c.address} no longer listed`);
}
// Simulates, sends through MetaMask, waits, then re-reads with `verify(at)` (a list of problems).
async function sendBackupTx(b, data, verify, what) {
bkLog(t("bkSimulating"), "line-dim");
try { await b.provider.call({ from: b.signer, to: b.km, data }); }
catch (e) { bkLog(t("bkSimFail", { err: e.shortMessage || e.reason || e.message }), "line-err"); return false; }
// The signer pays the gas: check its balance before MetaMask opens (a fresh backup key often holds
// nothing on this network, and the wallet then shows only a generic fee alert).
try {
const [gas, fee, bal] = await Promise.all([b.provider.estimateGas({ from: b.signer, to: b.km, data }), b.provider.getFeeData(), b.provider.getBalance(b.signer)]);
const price = fee.maxFeePerGas || fee.gasPrice;
if (price) {
const net = getNetwork();
const cur = net && net.currency && net.currency !== "?" ? net.currency : "";
const v = { addr: b.signer, bal: ethers.formatEther(bal), cost: ethers.formatEther(gas * price), cur };
if (bal < gas * price) { bkLog(t("bkNoGas", v), "line-err"); return false; }
bkLog(t("bkGasOk", v), "line-dim");
}
} catch (e) { /* no estimate: MetaMask still shows its own fee */ }
bkLog(t("bkSimOk"), "line-ok");
const browserProvider = new ethers.BrowserProvider(signerProvider);
browserProvider.pollingInterval = 1000; // confirm as soon as the block is there (default 4 s)
const signerObj = await browserProvider.getSigner();
if (signerObj.address.toLowerCase() !== b.signer.toLowerCase()) { bkLog(t("signerChangedErr", { now: signerObj.address, checked: b.signer }), "line-err"); return false; }
const tx = await SignCheck.sendTransaction(signerObj, { to: b.km, data, chainId: b.chainId }, { what, toLabel: { it: "Key Manager della UP", en: "the UP's Key Manager" } });
bkLog(t("bkTx", { hash: tx.hash }), "line-dim");
bkLog(t("bkWaiting"), "line-dim");
const receipt = await tx.wait();
if (!receipt || receipt.status !== 1) { bkLog(t("bkTxFailed"), "line-err"); return false; }
bkSeen = { key: `${b.chainId}:${b.up}`, block: receipt.blockNumber };
const net = getNetwork();
const url = net && getExplorerUrl(net, "/tx/", tx.hash);
if (url) bkLog(url, "line-dim");
// Public RPCs are load-balanced: read at the receipt's block, retrying while a node lags behind.
let problems = ["not read"];
for (let i = 0; i < 6 && problems.length; i++) {
if (i) await new Promise(res => setTimeout(res, 1500));
try { problems = await verify({ blockTag: receipt.blockNumber }); } catch (e) { problems = [e.shortMessage || e.message]; }
}
return problems;
}
$("addBackupBtn").addEventListener("click", async () => {
if (bkBusy) return;
bkSeparator();
setBusy(true);
try {
const b = await freshAdminState();
if (!b) return;
const rawAddr = $("backupAddress").value.trim();
if (!ethers.isAddress(rawAddr) || BigInt(rawAddr) === 0n) { bkLog(t("bkBadAddr"), "line-err"); return; }
const backup = ethers.getAddress(rawAddr);
if (backup === b.signer) { bkLog(t("bkSameAsSigner"), "line-err"); return; }
if ([b.up, b.km, BK.ENTRY_POINT].map(x => x.toLowerCase()).includes(backup.toLowerCase()) || backup.toLowerCase() === b.r.urd || KNOWN_ADDRESSES[backup.toLowerCase()]) { bkLog(t("bkSystem"), "line-err"); return; }
const upData = new ethers.Contract(b.up, UP_DATA_IFACE, b.provider);
const [existing, calls, dataKeys] = await upData.getDataBatch([BK.permKey(backup), BK.callsKey(b.signer), BK.dataKeysKey(b.signer)]);
if ((existing && existing !== "0x" && BigInt(existing) !== 0n) || b.r.controllers.some(c => c.address === backup)) { bkLog(t("bkAlready"), "line-err"); return; }
// A plain account, or one delegated through EIP-7702 (code 0xef0100 + address): never a contract.
const code = (await b.provider.getCode(backup)).toLowerCase();
if (code !== "0x" && !code.startsWith("0xef0100")) { bkLog(t("bkContract"), "line-err"); return; }
const raw = b.signerCtrl.raw;
const keys = [BK.ARRAY_KEY, BK.indexKey(b.r.len), BK.permKey(backup)];
const vals = [ethers.toBeHex(b.r.len + 1, 16), backup, raw];
const copy = [];
if (calls && calls !== "0x") { keys.push(BK.callsKey(backup)); vals.push(calls); copy.push("calls"); }
if (dataKeys && dataKeys !== "0x") { keys.push(BK.dataKeysKey(backup)); vals.push(dataKeys); copy.push("keys"); }
bkLog(t("bkPlanAdd", { signer: b.signer, km: b.km, len: b.r.len, len1: b.r.len + 1, backup, perms: permHex(b.signerCtrl.perms), names: permNames(b.signerCtrl.perms), extra: copy.length ? t("bkPlanExtra") : "" }), "line-dim");
const data = KM_EXEC_IFACE.encodeFunctionData("execute", [UP_DATA_IFACE.encodeFunctionData("setDataBatch", [keys, vals])]);
const what = { it: `Aggiunge il backup ${backup} alla UP ${b.up}, con gli stessi permessi di ${b.signer}`, en: `Adds the backup ${backup} to the UP ${b.up}, with the same permissions as ${b.signer}` };
const problems = await sendBackupTx(b, data, async (at) => {
const [p, lenRaw, item] = await upData.getDataBatch([BK.permKey(backup), BK.ARRAY_KEY, BK.indexKey(b.r.len)], at);
const out = [];
if (String(p).toLowerCase() !== String(raw).toLowerCase()) out.push(`permissions ${p}`);
if (BigInt(lenRaw || "0x0") !== BigInt(b.r.len + 1)) out.push(`list length ${lenRaw}`);
if (String(item).toLowerCase() !== backup.toLowerCase()) out.push(`list entry ${item}`);