-
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathregister-ui.js
More file actions
3813 lines (3567 loc) · 152 KB
/
Copy pathregister-ui.js
File metadata and controls
3813 lines (3567 loc) · 152 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
/**
* ERC-8004 registration UI.
*
* Tabbed interface for creating, listing, searching, and auditing ERC-8004
* agents. Inspired by erc8004.agency but extended with GLB uploads and 3D
* viewer links specific to 3D-Agent.
*
* Tabs:
* - Create Agent (4-step wizard: Identity → Services → Configuration → Deploy)
* - My Agents (owned-by-wallet, current chain)
* - Search (by Agent ID)
* - Templates (pre-fills Create Agent)
* - History (Registered events for the connected wallet)
*
* Uses plain DOM — consistent with the rest of the project.
*/
import {
registerAgent,
connectWallet,
eagerConnectWallet,
onWalletChange,
pinFile,
getIdentityRegistry,
buildRegistrationJSON,
} from './agent-registry.js';
import { glbFileToThumbnail } from './thumbnail.js';
import { DEFAULT_AVATARS, getDefaultAvatar } from './default-avatars.js';
import { REGISTRY_DEPLOYMENTS } from './abi.js';
import { renderBatchTab } from './batch-tab.js';
import { renderQRToCanvas } from './qr.js';
import {
CHAIN_META,
switchChain,
addressExplorerUrl,
tokenExplorerUrl,
txExplorerUrl,
supportedChainIds,
} from './chain-meta.js';
import {
getReadRegistry,
listAgentsByOwner,
listRegisteredEvents,
getAgentOnchain,
fetchAgentMetadata,
findAvatar3D,
getRegistryVersion,
getTotalSupply,
} from './queries.js';
import {
detectInputType,
resolveByAddress,
resolveByTxHash,
resolveENSAddress,
INPUT_TYPES,
} from './resolve-avatar.js';
import { runSolanaDeploy, solanaTxExplorerUrl, detectSolanaWallet } from './solana-deploy.js';
import {
getEphemeralAccount,
registerAgentGaslessAttempt,
registerAgentSelfPayRetry,
BSC_TESTNET_CHAIN_ID,
} from './gasless-register.js';
import { onchainBadgeHTML, ensureOnchainBadgeStyles } from '../shared/onchain-badge.js';
import { log } from '../shared/log.js';
ensureOnchainBadgeStyles();
// ───────────────────────────────────────────────────────────────────────────
// Solana sentinels — chain dropdown stores these strings instead of a numeric
// chainId for non-EVM targets. Most EVM-specific code paths early-return when
// _isSolana(this.selectedChainId) is true.
// ───────────────────────────────────────────────────────────────────────────
const SOLANA_MAINNET = 'solana-mainnet';
const SOLANA_DEVNET = 'solana-devnet';
const SOLANA_LABELS = {
[SOLANA_MAINNET]: 'Solana',
[SOLANA_DEVNET]: 'Solana Devnet',
};
const _isSolana = (id) => id === SOLANA_MAINNET || id === SOLANA_DEVNET;
const _solanaNetwork = (id) => (id === SOLANA_DEVNET ? 'devnet' : 'mainnet');
/**
* Map an external `?network=` argument to one of our chain IDs.
* Accepts canonical Solana strings ("mainnet-beta", "devnet"), bare chain
* names ("base", "polygon", "bsc"), or numeric EVM chainIds. Returns null
* when the value is empty or unknown so the caller can fall back.
*/
function _resolveNetworkArg(raw) {
if (!raw) return null;
const s = String(raw).trim().toLowerCase();
if (!s) return null;
if (s === 'mainnet-beta' || s === 'solana' || s === 'solana-mainnet' || s === 'mainnet')
return SOLANA_MAINNET;
if (s === 'devnet' || s === 'solana-devnet') return SOLANA_DEVNET;
if (/^\d+$/.test(s)) {
const id = Number(s);
return REGISTRY_DEPLOYMENTS[id] ? id : null;
}
const aliases = {
ethereum: 1, eth: 1, mainnet_eth: 1,
optimism: 10, op: 10,
bsc: 56, bnb: 56,
polygon: 137, matic: 137, pol: 137,
base: 8453,
arbitrum: 42161, arb: 42161,
avalanche: 43114, avax: 43114,
linea: 59144, scroll: 534352, celo: 42220,
'bsc-testnet': 97, sepolia: 11155111,
'base-sepolia': 84532, 'arbitrum-sepolia': 421614,
};
const id = aliases[s];
return id && REGISTRY_DEPLOYMENTS[id] ? id : null;
}
// ───────────────────────────────────────────────────────────────────────────
// Error classification — turns raw error messages into user-readable copy
// ───────────────────────────────────────────────────────────────────────────
function _classifyDeployError(raw, err = null) {
const m = String(raw || '').toLowerCase();
const code = err?.code;
// Wallet rejection (MetaMask 4001, ethers ACTION_REJECTED, Phantom)
if (code === 4001 || code === 'ACTION_REJECTED' ||
/user rejected|user denied|cancelled|reject/i.test(m)) {
return 'You cancelled the signature request — no transaction was sent. Click Deploy to try again.';
}
// Insufficient gas / funds
if (/insufficient funds|not enough|gas/i.test(m)) {
return 'Insufficient funds — make sure your wallet has enough ETH (or SOL) to cover gas. Top up and retry.';
}
// Wrong chain
if (/wrong chain|wrong network|mismatched chain/i.test(m)) {
return 'Wrong chain — switch your wallet to the target network and click Deploy again.';
}
// Network / RPC errors
if (/network|rpc|fetch|timeout|econnrefused|http 5/i.test(m)) {
return 'Network error — check your connection and retry. If the problem persists the RPC may be down.';
}
// Contract revert
if (/revert|execution reverted/i.test(m)) {
return `Transaction reverted by the contract — ${raw}. Check the registry address and retry.`;
}
return `Deploy failed: ${raw}`;
}
// ───────────────────────────────────────────────────────────────────────────
// SRI integrity cache
// ───────────────────────────────────────────────────────────────────────────
let _cachedIntegrity = undefined; // undefined = not yet fetched, null = fetch failed
async function fetchAgentIntegrity() {
if (_cachedIntegrity !== undefined) return _cachedIntegrity;
try {
const res = await fetch('/agent-3d/versions.json');
if (!res.ok) { _cachedIntegrity = null; return null; }
const data = await res.json();
const ver = data.latest;
_cachedIntegrity = data?.channels?.[ver]?.integrity?.['agent-3d.js'] ?? null;
} catch {
_cachedIntegrity = null;
}
return _cachedIntegrity;
}
// ───────────────────────────────────────────────────────────────────────────
// Templates (for the Templates tab → prefills Create)
// ───────────────────────────────────────────────────────────────────────────
// Service presets per template. Types match SERVICE_TYPES; endpoints are blank
// so the wizard shows empty rows the user fills in with their own URLs.
const S = {
a2a: { type: 'A2A', name: 'A2A', endpoint: '' },
mcp: { type: 'MCP', name: 'MCP', endpoint: '' },
web: { type: 'web', name: 'Website', endpoint: '' },
x402: { type: 'x402', name: 'x402', endpoint: '' },
};
const TEMPLATES = [
{
id: 'companion',
emoji: '🤝',
name: 'Virtual Companion',
description:
'Always-on digital friend with persistent memory and empathy for daily check-ins and emotional support.',
services: [S.a2a],
},
{
id: 'influencer',
emoji: '🎭',
name: 'Virtual Influencer',
description:
'On-brand 3D persona for social posts, livestreams, and AMAs with a consistent face and voice.',
services: [S.a2a, S.web],
},
{
id: 'vtuber',
emoji: '📺',
name: 'VTuber Co-Host',
description:
'Livestream co-host with reactive expressions, chat moderation, superchat shoutouts, and lore memory.',
services: [S.a2a],
},
{
id: 'tutor',
emoji: '🎓',
name: 'Language Tutor',
description:
'One-on-one conversation practice with pronunciation feedback, spaced repetition, and adaptive lessons.',
services: [S.a2a, S.mcp],
},
{
id: 'gallery',
emoji: '🖼️',
name: 'Gallery Guide',
description:
'Embodied docent for 3D galleries, NFT exhibitions, and metaverse rooms with scripted tours and Q&A.',
services: [S.a2a, S.web],
},
{
id: 'npc',
emoji: '🎮',
name: 'Game NPC',
description:
'Questgiver and dialog partner for game worlds with persistent lore, per-player memory, and branching scripts.',
services: [S.a2a],
},
{
id: 'wellness',
emoji: '🧘',
name: 'Wellness Coach',
description:
'Breathwork, meditation, and daily mood check-ins with a calm, empathetic embodied presence.',
services: [S.a2a],
},
{
id: 'concierge',
emoji: '🪪',
name: 'NFT Concierge',
description:
'Token-gated holder assistant — perks, drops, private channel access, and holder-specific analytics.',
services: [S.a2a, S.mcp],
},
{
id: 'dao',
emoji: '🏛️',
name: 'DAO Delegate',
description:
'Reads governance proposals, summarizes sentiment, and votes on behalf of delegators within a mandate.',
services: [S.a2a, S.mcp],
},
{
id: 'portfolio',
emoji: '💼',
name: 'Portfolio Manager',
description:
'Tracks wallet positions across chains, alerts on drawdown and risk, and rebalances on schedule.',
services: [S.a2a, S.mcp],
},
{
id: 'defi',
emoji: '📈',
name: 'DeFi Trading Agent',
description:
'Automated DeFi yield optimization, liquidity management, and token swaps across protocols.',
services: [S.a2a, S.mcp, S.x402],
x402Support: true,
},
{
id: 'support',
emoji: '🎧',
name: 'Avatar Support Agent',
description:
'Face-of-the-brand support — tickets, FAQ, and multi-language help with a consistent embodied persona.',
services: [S.a2a, S.web],
},
{
id: 'code',
emoji: '🔍',
name: 'Code Review Agent',
description:
'Automated code analysis, security auditing, gas optimization, and best-practice enforcement.',
services: [S.a2a, S.mcp, S.x402],
x402Support: true,
},
{
id: 'data',
emoji: '📊',
name: 'Data Analysis Agent',
description:
'On-chain and off-chain data analysis, reporting, visualization, and pattern recognition.',
services: [S.a2a, S.mcp],
},
{
id: 'content',
emoji: '✍️',
name: 'Content Creator',
description:
'AI content generation for social posts, documentation, technical writing, and marketing copy.',
services: [S.a2a, S.x402],
x402Support: true,
},
{
id: 'research',
emoji: '🔬',
name: 'Research Assistant',
description: 'Deep research on protocols, tokens, governance proposals, and market trends.',
services: [S.a2a, S.mcp],
},
];
const SERVICE_TYPES = ['A2A', 'MCP', 'OASF', 'x402', 'web', 'custom'];
// ───────────────────────────────────────────────────────────────────────────
// Helpers
// ───────────────────────────────────────────────────────────────────────────
const esc = (s) =>
String(s ?? '').replace(
/[&<>"']/g,
(c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],
);
const shortAddr = (a) => (a ? a.slice(0, 6) + '…' + a.slice(-4) : '');
/**
* True if `url` is already a content-addressed or durable public URL that
* doesn't need to be fetched and re-pinned before referencing in a
* registration JSON. Avoids wasted uploads for avatars users created
* earlier (or default avatars shipped on the same domain).
*/
const _isStableUrl = (url) => {
if (!url || typeof url !== 'string') return false;
const u = url.trim();
return (
u.startsWith('ipfs://') ||
u.startsWith('ar://') ||
u.startsWith('https://') ||
u.startsWith('http://') ||
u.startsWith('/') // same-origin public asset (e.g. /avatars/cz.glb)
);
};
// ───────────────────────────────────────────────────────────────────────────
// RegisterUI
// ───────────────────────────────────────────────────────────────────────────
export class RegisterUI {
/**
* @param {HTMLElement} containerEl
* @param {(result: { agentId: number, txHash: string, chainId: number }) => void} [onRegistered]
* @param {{ initial?: { name?: string, description?: string, imageUrl?: string, glbUrl?: string } }} [opts]
*/
constructor(containerEl, onRegistered, opts = {}) {
this.container = containerEl;
this.onRegistered = onRegistered || (() => {});
this.mode = opts.mode === 'page' ? 'page' : 'modal';
this._viewer = opts.viewer || null;
this._avatarId = opts.avatarId || null;
// Wallet state
this.wallet = null; // { address, chainId }
// Selected chain for reads + writes. Defaults to Solana mainnet, where a
// deploy mints the agent as a Metaplex Core asset. Because the Solana
// default is non-EVM, the wallet-chain adoption below leaves it intact
// unless the user explicitly picks an EVM chain.
// `initial.network` (from ?network= URL param) overrides the default
// when it maps to a known chain.
this.selectedChainId = _resolveNetworkArg(opts.initial?.network) ?? SOLANA_MAINNET;
// Tab state
this.activeTab = opts.initialTab || 'create';
const initial = opts.initial || {};
// Wizard state — pre-populate from the user's current avatar/session so
// the on-chain JSON points to the GLB they just uploaded/created.
// `avatarSource` drives Step 3 behaviour:
// 'current' → use `glbUrl` pre-filled from the live SPA viewer
// 'saved' → pick one from the signed-in user's saved avatars
// 'upload' → user drops a new .glb in the wizard
// 'url' → user pastes a hosted GLB URL directly
// 'skip' → deploy as a metadata-only agent (no 3D body)
this.wizardStep = 1;
this.form = {
name: initial.name || '',
description: initial.description || '',
imageUrl: initial.imageUrl || '',
glbUrl: initial.glbUrl || '',
glbFile: null,
pastedGlbUrl: '',
savedAvatar: null, // { id, name, modelUrl, thumbnailUrl }
defaultAvatarId: null, // id of a pre-pinned DEFAULT_AVATARS entry
avatarSource: initial.glbUrl ? 'current' : 'upload',
services: [], // [{ name, type, endpoint }]
x402Support: false,
apiToken: '', // optional Pinata JWT
};
// Cache of signed-in user's backend agent id (if any) — linked after deploy
this._backendAgentId = null;
this._signedIn = false;
this._savedAvatars = null; // loaded lazily when user switches source to 'saved'
// True when the form was pre-filled from URL params (?name=, ?avatar=,
// ?agent=). In this case the quickstart bar is hidden — the user already
// has a specific deployment context and the chips would just confuse them
// (or silently overwrite the pre-filled data).
this._urlPrefilled = !!(initial.name || initial.imageUrl || opts.avatarId);
this._build();
this._bind();
this._fetchBackendAgent(); // fire & forget
this._eagerConnectWallet(); // silent reconnect if wallet already authorized
// Keep the UI in sync when the user switches account/chain in the wallet,
// or when another tab/page on this origin connects/disconnects.
this._unsubscribeWallet = onWalletChange(({ address, chainId }) => {
if (!address) {
this.wallet = null;
} else {
this.wallet = { address, chainId: Number(chainId) };
// Don't clobber an explicit Solana selection when an EVM wallet
// reports its chain.
if (
!_isSolana(this.selectedChainId) &&
REGISTRY_DEPLOYMENTS[this.wallet.chainId]
) {
this.selectedChainId = this.wallet.chainId;
const sel = this.el.querySelector('.erc8004-chain-select');
if (sel) sel.value = String(this.selectedChainId);
}
}
this._refreshWalletButton();
this._renderActiveTab();
this._refreshMainnetBanner();
});
}
// -----------------------------------------------------------------------
// Top-level DOM
// -----------------------------------------------------------------------
_build() {
const pageMode = this.mode === 'page';
this.el = document.createElement('div');
this.el.className = 'erc8004-register' + (pageMode ? ' erc8004-register--page' : '');
if (pageMode) {
this.el.innerHTML = `
<div class="deploy-shell">
<header class="deploy-hero">
<div class="deploy-hero-text">
<div class="deploy-hero-eyebrow">
<span class="deploy-hero-dot" aria-hidden="true"></span>
<span>Deploy on-chain</span>
</div>
<h1 class="deploy-hero-title">Give your agent an on-chain identity</h1>
<p class="deploy-hero-sub">
Mint your agent as an NFT on Solana (Metaplex Core) or EVM (ERC-8004).
Your 3D body, services, and metadata live in a single discoverable record.
</p>
<div class="deploy-hero-meta">
<a class="deploy-hero-link" href="/dashboard">My agents →</a>
<a class="deploy-hero-link" href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener">ERC-8004 spec ↗</a>
<a class="deploy-hero-link" href="https://developers.metaplex.com/core" target="_blank" rel="noopener">Metaplex Core ↗</a>
</div>
</div>
<div class="deploy-hero-controls">
<label class="deploy-chain-control">
<span class="deploy-chain-label">Target network</span>
<select class="erc8004-chain-select" title="Target chain"></select>
</label>
<button class="erc8004-btn erc8004-btn--wallet deploy-wallet-btn btn btn--secondary" type="button">
Connect wallet
</button>
</div>
</header>
<div class="erc8004-mainnet-banner deploy-banner" data-role="mainnet-banner" style="display:none"></div>
<div class="deploy-grid">
<main class="deploy-main">
<div class="erc8004-tab-body" data-role="tab-body"></div>
</main>
<aside class="deploy-preview" data-role="preview" aria-label="Agent preview"></aside>
</div>
</div>
`;
} else {
this.el.innerHTML = `
<div class="erc8004-card erc8004-card--wide">
<div class="erc8004-header">
<div class="erc8004-controls">
<select class="erc8004-chain-select" title="Target chain"></select>
<button class="erc8004-btn erc8004-btn--wallet btn btn--secondary" type="button">
Connect MetaMask
</button>
<button class="erc8004-btn erc8004-btn--close btn btn--ghost btn--icon" type="button" title="Close">✕</button>
</div>
</div>
<div class="erc8004-mainnet-banner" data-role="mainnet-banner" style="display:none"></div>
<nav class="erc8004-tabs" role="tablist">
<button class="erc8004-tab erc8004-tab--active" data-tab="create">Create Agent</button>
<button class="erc8004-tab" data-tab="my">My Agents</button>
<button class="erc8004-tab" data-tab="search">Search</button>
<button class="erc8004-tab" data-tab="templates">Templates</button>
<button class="erc8004-tab" data-tab="batch">Batch</button>
<button class="erc8004-tab" data-tab="history">History</button>
</nav>
<div class="erc8004-tab-body" data-role="tab-body"></div>
</div>
`;
}
this.container.appendChild(this.el);
this._populateChainSelect();
this._renderActiveTab();
this._refreshMainnetBanner();
this._refreshWalletButton();
}
_isPageMode() {
return this.mode === 'page';
}
_refreshMainnetBanner() {
const banner = this.el.querySelector('[data-role="mainnet-banner"]');
if (!banner) return;
if (_isSolana(this.selectedChainId)) {
if (this.selectedChainId === SOLANA_MAINNET) {
banner.style.display = '';
banner.innerHTML = `⚠️ <strong>Mainnet Mode</strong> — Transactions use real SOL. Test on devnet first.`;
} else {
banner.style.display = 'none';
banner.innerHTML = '';
}
return;
}
const meta = CHAIN_META[this.selectedChainId];
if (meta && !meta.testnet) {
banner.style.display = '';
banner.innerHTML = `⚠️ <strong>Mainnet Mode</strong> — Transactions use real ${esc(
meta.currency.symbol,
)}. Test on a testnet first.`;
} else {
banner.style.display = 'none';
banner.innerHTML = '';
}
}
_bind() {
this.el
.querySelector('.erc8004-btn--wallet')
.addEventListener('click', () => this._connectWallet());
const closeBtn = this.el.querySelector('.erc8004-btn--close');
if (closeBtn) closeBtn.addEventListener('click', () => this.destroy());
this.el.querySelector('.erc8004-chain-select').addEventListener('change', async (e) => {
const raw = e.target.value;
const newChain = _isSolana(raw) ? raw : Number(raw);
this.selectedChainId = newChain;
this._refreshWalletButton();
// If we just selected an EVM chain and the user has an EVM wallet on a
// different chain, prompt to switch. Solana chains skip this entirely.
if (
!_isSolana(newChain) &&
this.wallet &&
this.wallet.chainId !== newChain &&
window.ethereum
) {
try {
await switchChain(newChain);
this.wallet.chainId = newChain;
this._refreshWalletButton();
} catch (err) {
this._toast('Chain switch rejected: ' + err.message, true);
}
}
this._renderActiveTab();
this._refreshMainnetBanner();
});
this.el.querySelectorAll('.erc8004-tab').forEach((btn) => {
btn.addEventListener('click', () => this._setTab(btn.dataset.tab));
});
}
destroy() {
if (this._unsubscribeWallet) this._unsubscribeWallet();
this.el.remove();
}
// -----------------------------------------------------------------------
// Wallet & chain
// -----------------------------------------------------------------------
async _connectWallet() {
// Connect-in-progress affordance: the button reports what's happening
// and can't be double-clicked while the wallet popup is open.
const walletBtn = this.el.querySelector('.erc8004-btn--wallet');
const setBusy = (on) => {
if (!walletBtn) return;
walletBtn.disabled = on;
if (on) walletBtn.textContent = 'Connecting…';
};
// On Solana, route to Phantom instead of MetaMask.
if (_isSolana(this.selectedChainId)) {
try {
const provider = detectSolanaWallet();
if (!provider) {
this._toast(
'No Solana wallet found. Install Phantom, then reload this page and reconnect.',
true,
);
window.open('https://phantom.app/', '_blank', 'noopener');
return;
}
setBusy(true);
const res = await provider.connect();
const pk = res?.publicKey?.toBase58?.() || provider.publicKey?.toBase58?.();
if (pk) this._toast('Connected ' + shortAddr(pk));
this._renderActiveTab();
} catch (err) {
const msg = err?.message || String(err);
this._toast(
/locked/i.test(msg)
? 'Your Solana wallet is locked. Unlock it in the extension, then reconnect.'
: 'Phantom: ' + msg,
true,
);
} finally {
setBusy(false);
this._refreshWalletButton();
}
return;
}
if (!window.ethereum) {
this._toast(
'No EVM wallet found. Install MetaMask, then reload this page and reconnect.',
true,
);
window.open('https://metamask.io/download/', '_blank', 'noopener');
return;
}
try {
setBusy(true);
const { address, chainId } = await connectWallet();
this.wallet = { address, chainId: Number(chainId) };
// Adopt wallet's chain if supported; otherwise keep selected and offer
// switch. Don't clobber an explicit Solana selection.
if (
!_isSolana(this.selectedChainId) &&
REGISTRY_DEPLOYMENTS[this.wallet.chainId]
) {
this.selectedChainId = this.wallet.chainId;
const sel = this.el.querySelector('.erc8004-chain-select');
if (sel) sel.value = String(this.selectedChainId);
}
this._renderActiveTab();
this._refreshMainnetBanner();
} catch (err) {
this._toast('Wallet: ' + err.message, true);
} finally {
setBusy(false);
this._refreshWalletButton();
}
}
// Silent reconnect on mount — uses `eth_accounts` (no popup). If the wallet
// has previously authorized this origin and is unlocked, we restore the
// connection transparently so the user doesn't see "Connect MetaMask" twice.
// Also tries a silent Phantom reconnect so users signed in with Solana
// land on the Solana chain by default instead of the EVM fallback.
async _eagerConnectWallet() {
const result = await eagerConnectWallet();
if (result) {
this.wallet = { address: result.address, chainId: Number(result.chainId) };
if (
!_isSolana(this.selectedChainId) &&
REGISTRY_DEPLOYMENTS[this.wallet.chainId]
) {
this.selectedChainId = this.wallet.chainId;
const sel = this.el.querySelector('.erc8004-chain-select');
if (sel) sel.value = String(this.selectedChainId);
}
}
// If no EVM wallet adopted the selection and a Solana wallet is
// already trusted by this origin, prefer Solana. `onlyIfTrusted` is
// silent — no popup if the user hasn't previously connected.
if (!_isSolana(this.selectedChainId) && !result) {
const solProvider = detectSolanaWallet();
if (solProvider) {
try {
if (!solProvider.publicKey && typeof solProvider.connect === 'function') {
await solProvider.connect({ onlyIfTrusted: true });
}
if (solProvider.publicKey) {
this.selectedChainId = SOLANA_MAINNET;
const sel = this.el.querySelector('.erc8004-chain-select');
if (sel) sel.value = String(this.selectedChainId);
}
} catch {
// Silent — user hasn't trusted this origin yet.
}
}
}
this._refreshWalletButton();
this._renderActiveTab();
this._refreshMainnetBanner();
}
_refreshWalletButton() {
const btn = this.el.querySelector('.erc8004-btn--wallet');
if (!btn) return;
const solana = _isSolana(this.selectedChainId);
if (solana) {
// Solana — `this.wallet` tracks EVM only; show Phantom CTA / connected state
// from window.solana when available.
const hasPhantom = !!detectSolanaWallet();
const pk = window.solana?.publicKey?.toBase58?.() || null;
if (pk) {
btn.textContent = shortAddr(pk);
btn.classList.add('erc8004-btn--connected');
} else {
btn.textContent = hasPhantom ? 'Connect Phantom' : 'Install Phantom';
btn.classList.remove('erc8004-btn--connected');
}
return;
}
if (!this.wallet) {
btn.textContent = window.ethereum ? 'Connect MetaMask' : 'Install MetaMask';
btn.classList.remove('erc8004-btn--connected');
return;
}
btn.textContent = shortAddr(this.wallet.address);
btn.classList.add('erc8004-btn--connected');
}
_populateChainSelect() {
const sel = this.el.querySelector('.erc8004-chain-select');
const ids = supportedChainIds();
// Mainnets first (production-default), then testnets
const mainnets = ids.filter((id) => !CHAIN_META[id].testnet);
const testnets = ids.filter((id) => CHAIN_META[id].testnet);
const groupS = document.createElement('optgroup');
groupS.label = 'Solana (recommended)';
for (const id of [SOLANA_MAINNET, SOLANA_DEVNET]) {
const opt = document.createElement('option');
opt.value = id;
opt.textContent = SOLANA_LABELS[id];
groupS.appendChild(opt);
}
const groupM = document.createElement('optgroup');
groupM.label = 'EVM Mainnets';
const groupT = document.createElement('optgroup');
groupT.label = 'EVM Testnets';
for (const id of mainnets) {
const opt = document.createElement('option');
opt.value = String(id);
opt.textContent = CHAIN_META[id].name;
groupM.appendChild(opt);
}
for (const id of testnets) {
const opt = document.createElement('option');
opt.value = String(id);
opt.textContent = CHAIN_META[id].name;
groupT.appendChild(opt);
}
sel.appendChild(groupS);
sel.appendChild(groupM);
sel.appendChild(groupT);
sel.value = String(this.selectedChainId);
}
async _refreshStats() {
const el = (k) => this.el.querySelector(`[data-stat="${k}"]`);
try {
const [total, version] = await Promise.all([
getTotalSupply(this.selectedChainId).catch(() => null),
getRegistryVersion(this.selectedChainId).catch(() => null),
]);
const totalEl = el('total');
const versionEl = el('version');
if (total !== null && totalEl) totalEl.textContent = String(total);
if (version && versionEl) versionEl.textContent = version;
} catch {
/* swallow; stats are cosmetic */
}
}
// -----------------------------------------------------------------------
// Backend agent link (optional)
// -----------------------------------------------------------------------
async _fetchBackendAgent() {
try {
const res = await fetch('/api/agents/me', { credentials: 'include' });
if (!res.ok) return;
this._signedIn = true;
const { agent } = await res.json();
if (agent && agent.id) this._backendAgentId = agent.id;
// If Step 3 is already rendered (signed-in detection raced with UI),
// re-render so the "Use a saved avatar" option appears.
if (this.wizardStep === 3 && this.activeTab === 'create') this._renderActiveTab();
} catch {
/* anon user or endpoint unavailable — fine */
}
}
/**
* Lazily fetch the signed-in user's saved avatars for the Step 3 picker.
* Returns [] on any failure (anonymous, endpoint down, etc) so the UI can
* silently fall back to the upload/skip options.
*/
async _loadSavedAvatars() {
if (this._savedAvatars) return this._savedAvatars;
try {
const res = await fetch('/api/avatars?limit=50', { credentials: 'include' });
if (!res.ok) {
this._savedAvatars = [];
return this._savedAvatars;
}
const payload = await res.json();
const rows = payload.avatars || payload.data || [];
this._savedAvatars = rows.map((r) => ({
id: r.id,
name: r.name || 'Untitled',
modelUrl: r.model_url || null, // null for private — resolved on select
thumbnailUrl: r.thumbnail_url || null,
visibility: r.visibility,
}));
} catch {
this._savedAvatars = [];
}
return this._savedAvatars;
}
/**
* Resolve a saved avatar's download URL. Public/unlisted expose `model_url`
* directly; private avatars require a per-object signed-URL fetch.
*/
async _resolveSavedAvatarUrl(avatar) {
if (avatar.modelUrl) return avatar.modelUrl;
const res = await fetch(`/api/avatars/${encodeURIComponent(avatar.id)}`, {
credentials: 'include',
});
if (!res.ok) throw new Error(`avatar fetch failed (${res.status})`);
const { avatar: detail } = await res.json();
return detail?.url || null;
}
async _linkAgentToAccount({ agentId, chainId, txHash, throwOnError = false }) {
if (!this._backendAgentId || !this.wallet) {
if (throwOnError) throw new Error('Sign in and connect a wallet first');
return;
}
try {
const res = await fetch(
`/api/agents/${encodeURIComponent(this._backendAgentId)}/wallet`,
{
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
wallet_address: this.wallet.address,
chain_id: chainId,
erc8004_agent_id: agentId,
tx_hash: txHash,
}),
},
);
if (!res.ok) {
const text = await res.text().catch(() => res.status);
throw new Error(`link failed (${res.status}): ${text}`);
}
} catch (err) {
log.warn('[erc8004] Failed to link on-chain agentId to account:', err.message);
if (throwOnError) throw err;
}
}
// -----------------------------------------------------------------------
// Tabs
// -----------------------------------------------------------------------
_setTab(tab) {
this.activeTab = tab;
this.el.querySelectorAll('.erc8004-tab').forEach((btn) => {
btn.classList.toggle('erc8004-tab--active', btn.dataset.tab === tab);
});
this._renderActiveTab();
}
_renderActiveTab() {
const body = this.el.querySelector('[data-role="tab-body"]');
body.innerHTML = '';
// In page mode (/deploy) we hide the tab strip and always render the
// Create wizard — this URL is single-purpose. The preview rail mirrors
// the form state on the right.
if (this._isPageMode()) {
this.activeTab = 'create';
this._renderCreate(body);
this._refreshPreview();
return;
}
switch (this.activeTab) {
case 'create':
this._renderCreate(body);
break;
case 'my':
this._renderMyAgents(body);
break;
case 'search':
this._renderSearch(body);
break;
case 'templates':
this._renderTemplates(body);
break;
case 'batch':
this._renderBatch(body);
break;
case 'history':
this._renderHistory(body);
break;
}
}
// ----- Preview rail (page mode only) -----------------------------------
_refreshPreview() {
const rail = this.el.querySelector('[data-role="preview"]');
if (!rail) return;
const f = this.form;
const solana = _isSolana(this.selectedChainId);
const chainLabel = solana
? SOLANA_LABELS[this.selectedChainId]
: (CHAIN_META[this.selectedChainId]?.name || `Chain ${this.selectedChainId}`);
const standard = solana ? 'Metaplex Core NFT' : 'ERC-8004 (ERC-721)';
const costLabel = solana ? '~0.003 SOL' : `gas on ${esc(chainLabel)}`;
const avatarLine = this._avatarSummary();
const services = (f.services || []).filter((s) => s.endpoint?.trim());
const thumb = this._previewThumbSource();
const thumbKey = `${thumb.kind}|${thumb.src || ''}`;
const needsRebuild =
this._lastPreviewThumbKey !== thumbKey || !rail.querySelector('.deploy-preview-card');
const infoHtml = `
<div class="deploy-preview-name">${esc(f.name) || '<span class="deploy-preview-dim">Untitled agent</span>'}</div>
<div class="deploy-preview-desc">${esc(f.description) || '<span class="deploy-preview-dim">Add a description in Step 1.</span>'}</div>
<dl class="deploy-preview-meta">
<dt>Chain</dt><dd>${esc(chainLabel)}</dd>
<dt>Standard</dt><dd>${standard}</dd>
<dt>Avatar</dt><dd>${avatarLine}</dd>
<dt>Services</dt><dd>${services.length ? services.map((s) => `<span class="deploy-svc-pill">${esc(s.type)}</span>`).join(' ') : '<span class="deploy-preview-dim">none</span>'}</dd>
<dt>Cost</dt><dd>${esc(costLabel)}</dd>
</dl>
<div class="deploy-preview-checklist">
<div class="deploy-check ${f.name?.trim() ? 'is-ok' : ''}">${f.name?.trim() ? '✓' : '○'} Name</div>
<div class="deploy-check ${f.description?.trim() ? 'is-ok' : ''}">${f.description?.trim() ? '✓' : '○'} Description</div>
<div class="deploy-check ${this._hasAvatar() ? 'is-ok' : ''}">${this._hasAvatar() ? '✓' : '○'} Avatar</div>
<div class="deploy-check ${this._walletReady() ? 'is-ok' : ''}">${this._walletReady() ? '✓' : '○'} Wallet</div>
</div>
`;
if (needsRebuild) {
rail.innerHTML = `
<div class="deploy-preview-card">
<div class="deploy-preview-eyebrow">Live preview</div>
<div class="deploy-preview-thumb" data-role="thumb">${this._previewThumbHtml(thumb)}</div>
<div data-role="info">${infoHtml}</div>
</div>
`;
this._lastPreviewThumbKey = thumbKey;
if (thumb.kind === 'glb') {
this._ensureModelViewer();
// Some GLBs (meshopt-compressed) exceed what the CDN model-viewer
// build can decode. Swap a failed 3D preview for a designed
// placeholder instead of leaving a silently empty viewer.
const mv = rail.querySelector('.deploy-preview-mv');
mv?.addEventListener(
'error',
() => {
const holder = rail.querySelector('[data-role="thumb"]');
if (holder) {
holder.innerHTML =
'<div class="deploy-preview-ph">3D preview unavailable for this file. Your model still deploys unchanged.</div>';
}
},
{ once: true },
);