@xian-tech/wallet-core 0.3.0 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,12 @@
1
- import { Ed25519Signer, XianClient } from "@xian-tech/client";
2
- import { ProviderChainMismatchError, ProviderUnauthorizedError, ProviderUnsupportedMethodError } from "@xian-tech/provider";
1
+ import { Ed25519Signer, shieldedSyncHintFromViewingPrivateKey, XianClient } from "@xian-tech/client";
2
+ import { createXianDappPolicyForRequest, findMatchingXianDappPolicy, ProviderChainMismatchError, ProviderUnauthorizedError, ProviderUnsupportedMethodError } from "@xian-tech/provider";
3
3
  import { approvalKindFromMethod, buildApprovalView } from "./approvals.js";
4
4
  import { DEFAULT_NETWORK_PRESETS, DEFAULT_DASHBOARD_URL, DEFAULT_RPC_URL, LOCAL_NETWORK_PRESET_NAME, DEFAULT_WALLET_CAPABILITIES, LOCAL_NETWORK_PRESET_ID, UNLOCKED_SESSION_TIMEOUT_MS } from "./constants.js";
5
- import { createWalletSessionKey, createWalletSecret, decryptMnemonicWithSessionKey, decryptPrivateKeyWithSessionKey, deriveWalletSessionKey, derivePrivateKeyFromMnemonic, encryptMnemonicWithSessionKey, encryptPrivateKeyWithSessionKey, isUnsafeMessageToSign } from "./crypto.js";
5
+ import { createWalletSessionKey, decryptSecretTextWithSessionKey, createWalletSecret, decryptMnemonicWithSessionKey, decryptPrivateKeyWithSessionKey, deriveWalletSessionKey, derivePrivateKeyFromMnemonic, encryptSecretTextWithSessionKey, encryptMnemonicWithSessionKey, encryptPrivateKeyWithSessionKey, isUnsafeMessageToSign } from "./crypto.js";
6
6
  const SAFE_CHAIN_ID_LOOKUP_TIMEOUT_MS = 2_000;
7
+ const TRUSTED_DAPP_POLICY_TTL_MS = 30 * 24 * 60 * 60 * 1000;
8
+ const MAX_DAPP_METADATA_TEXT_LENGTH = 120;
9
+ const MAX_DAPP_ICON_URL_LENGTH = 2048;
7
10
  function firstParamObject(params) {
8
11
  if (Array.isArray(params)) {
9
12
  return (params[0] ?? {});
@@ -36,6 +39,210 @@ function trimOptionalString(value) {
36
39
  const trimmed = value?.trim();
37
40
  return trimmed ? trimmed : undefined;
38
41
  }
42
+ function trimOptionalIndexedString(value) {
43
+ const trimmed = value?.trim();
44
+ if (!trimmed) {
45
+ return undefined;
46
+ }
47
+ try {
48
+ const parsed = JSON.parse(trimmed);
49
+ if (typeof parsed === "string") {
50
+ return trimOptionalString(parsed);
51
+ }
52
+ if (parsed == null) {
53
+ return undefined;
54
+ }
55
+ if (typeof parsed === "number" || typeof parsed === "boolean") {
56
+ return String(parsed);
57
+ }
58
+ }
59
+ catch {
60
+ // BDS versions that already return plain text should pass through unchanged.
61
+ }
62
+ return trimmed;
63
+ }
64
+ function trimNullableString(value) {
65
+ if (typeof value !== "string") {
66
+ return null;
67
+ }
68
+ const trimmed = value.trim();
69
+ return trimmed.length > 0 ? trimmed : null;
70
+ }
71
+ function messageFromUnknown(value) {
72
+ if (value instanceof Error) {
73
+ return value.message;
74
+ }
75
+ if (typeof value === "string") {
76
+ return value;
77
+ }
78
+ try {
79
+ return JSON.stringify(value);
80
+ }
81
+ catch {
82
+ return String(value);
83
+ }
84
+ }
85
+ function isMissingContractResult(value) {
86
+ const message = messageFromUnknown(value);
87
+ return /ImportError\(['"]Module\s+[^'"]+\s+not found['"]\)/i.test(message) ||
88
+ /Module\s+\S+\s+not found/i.test(message);
89
+ }
90
+ function isRecord(value) {
91
+ return typeof value === "object" && value != null;
92
+ }
93
+ function normalizeAssetNetworkStates(value) {
94
+ if (!isRecord(value)) {
95
+ return {};
96
+ }
97
+ const states = {};
98
+ for (const [networkId, rawNetworkState] of Object.entries(value)) {
99
+ if (!networkId || !isRecord(rawNetworkState)) {
100
+ continue;
101
+ }
102
+ const networkState = {};
103
+ for (const [contract, rawAssetState] of Object.entries(rawNetworkState)) {
104
+ if (!contract || !isRecord(rawAssetState)) {
105
+ continue;
106
+ }
107
+ const status = rawAssetState.status;
108
+ const normalized = {};
109
+ if (status === "available" ||
110
+ status === "not_found" ||
111
+ status === "unknown") {
112
+ normalized.status = status;
113
+ }
114
+ if (typeof rawAssetState.hidden === "boolean") {
115
+ normalized.hidden = rawAssetState.hidden;
116
+ }
117
+ if (typeof rawAssetState.lastCheckedAt === "string") {
118
+ normalized.lastCheckedAt = rawAssetState.lastCheckedAt;
119
+ }
120
+ if (typeof rawAssetState.error === "string") {
121
+ normalized.error = rawAssetState.error;
122
+ }
123
+ if (Object.keys(normalized).length > 0) {
124
+ networkState[contract] = normalized;
125
+ }
126
+ }
127
+ if (Object.keys(networkState).length > 0) {
128
+ states[networkId] = networkState;
129
+ }
130
+ }
131
+ return states;
132
+ }
133
+ function normalizeTrustedDappPolicies(value) {
134
+ if (!Array.isArray(value)) {
135
+ return [];
136
+ }
137
+ return value.flatMap((entry) => {
138
+ if (!isRecord(entry) ||
139
+ typeof entry.id !== "string" ||
140
+ typeof entry.origin !== "string" ||
141
+ typeof entry.account !== "string" ||
142
+ typeof entry.chainId !== "string" ||
143
+ !Array.isArray(entry.methods) ||
144
+ typeof entry.createdAt !== "number") {
145
+ return [];
146
+ }
147
+ const methods = entry.methods.filter((method) => method === "xian_signTransaction" ||
148
+ method === "xian_sendTransaction" ||
149
+ method === "xian_sendCall");
150
+ if (methods.length === 0) {
151
+ return [];
152
+ }
153
+ return [
154
+ {
155
+ id: entry.id,
156
+ origin: entry.origin,
157
+ account: entry.account,
158
+ chainId: entry.chainId,
159
+ methods,
160
+ contract: trimNullableString(entry.contract) ?? undefined,
161
+ function: trimNullableString(entry.function) ?? undefined,
162
+ maxChi: typeof entry.maxChi === "number" ||
163
+ typeof entry.maxChi === "bigint" ||
164
+ typeof entry.maxChi === "string"
165
+ ? entry.maxChi
166
+ : undefined,
167
+ kwargs: isRecord(entry.kwargs) ? entry.kwargs : undefined,
168
+ label: trimNullableString(entry.label) ?? undefined,
169
+ createdAt: entry.createdAt,
170
+ updatedAt: typeof entry.updatedAt === "number" ? entry.updatedAt : undefined,
171
+ expiresAt: typeof entry.expiresAt === "number" ? entry.expiresAt : undefined,
172
+ lastUsedAt: typeof entry.lastUsedAt === "number" ? entry.lastUsedAt : undefined,
173
+ useCount: typeof entry.useCount === "number" ? entry.useCount : undefined
174
+ }
175
+ ];
176
+ });
177
+ }
178
+ function trimMetadataText(value) {
179
+ if (typeof value !== "string") {
180
+ return undefined;
181
+ }
182
+ const trimmed = value.trim();
183
+ return trimmed.length > 0
184
+ ? trimmed.slice(0, MAX_DAPP_METADATA_TEXT_LENGTH)
185
+ : undefined;
186
+ }
187
+ function normalizeDappIconUrl(value) {
188
+ if (typeof value !== "string") {
189
+ return undefined;
190
+ }
191
+ const trimmed = value.trim();
192
+ if (trimmed.length === 0 ||
193
+ trimmed.length > MAX_DAPP_ICON_URL_LENGTH) {
194
+ return undefined;
195
+ }
196
+ try {
197
+ const url = new URL(trimmed);
198
+ return url.protocol === "https:" || url.protocol === "http:"
199
+ ? url.href
200
+ : undefined;
201
+ }
202
+ catch {
203
+ return undefined;
204
+ }
205
+ }
206
+ function normalizeConnectedDappMetadataEntry(value, options) {
207
+ if (!isRecord(value)) {
208
+ return null;
209
+ }
210
+ const metadata = {};
211
+ const name = trimMetadataText(value.name);
212
+ const iconUrl = normalizeDappIconUrl(value.iconUrl);
213
+ if (name) {
214
+ metadata.name = name;
215
+ }
216
+ if (iconUrl) {
217
+ metadata.iconUrl = iconUrl;
218
+ }
219
+ if (typeof value.lastSeenAt === "number" && Number.isFinite(value.lastSeenAt)) {
220
+ metadata.lastSeenAt = value.lastSeenAt;
221
+ }
222
+ else if (typeof options?.now === "number") {
223
+ metadata.lastSeenAt = options.now;
224
+ }
225
+ return Object.keys(metadata).length > 0 ? metadata : null;
226
+ }
227
+ function normalizeConnectedDappMetadata(value, connectedOrigins) {
228
+ if (!isRecord(value)) {
229
+ return {};
230
+ }
231
+ const allowedOrigins = connectedOrigins
232
+ ? new Set(connectedOrigins)
233
+ : undefined;
234
+ const metadata = {};
235
+ for (const [origin, entry] of Object.entries(value)) {
236
+ if (allowedOrigins && !allowedOrigins.has(origin)) {
237
+ continue;
238
+ }
239
+ const normalized = normalizeConnectedDappMetadataEntry(entry);
240
+ if (normalized) {
241
+ metadata[origin] = normalized;
242
+ }
243
+ }
244
+ return metadata;
245
+ }
39
246
  function normalizeTrackedAsset(asset) {
40
247
  return {
41
248
  contract: asset.contract.trim(),
@@ -74,6 +281,9 @@ function normalizePresetInputValue(preset, fallback) {
74
281
  function normalizeStoredWalletNetworks(state) {
75
282
  const localPreset = createLocalNetworkPreset();
76
283
  const rawPresets = Array.isArray(state.networkPresets) ? state.networkPresets : [];
284
+ const assetNetworkStates = normalizeAssetNetworkStates(state.assetNetworkStates);
285
+ const trustedDappPolicies = normalizeTrustedDappPolicies(state.trustedDappPolicies);
286
+ const connectedDappMetadata = normalizeConnectedDappMetadata(state.connectedDappMetadata, state.connectedOrigins);
77
287
  if (rawPresets.length === 0) {
78
288
  const rpcUrl = trimOptionalString(state.rpcUrl) ?? DEFAULT_RPC_URL;
79
289
  const dashboardUrl = trimOptionalString(state.dashboardUrl) ?? DEFAULT_DASHBOARD_URL;
@@ -85,7 +295,10 @@ function normalizeStoredWalletNetworks(state) {
85
295
  rpcUrl: localPreset.rpcUrl,
86
296
  dashboardUrl: localPreset.dashboardUrl,
87
297
  activeNetworkId: localPreset.id,
88
- networkPresets: [localPreset]
298
+ networkPresets: [localPreset],
299
+ assetNetworkStates,
300
+ trustedDappPolicies,
301
+ connectedDappMetadata
89
302
  };
90
303
  }
91
304
  const customPreset = normalizePresetInputValue({
@@ -104,7 +317,10 @@ function normalizeStoredWalletNetworks(state) {
104
317
  rpcUrl: customPreset.rpcUrl,
105
318
  dashboardUrl: customPreset.dashboardUrl,
106
319
  activeNetworkId: customPreset.id,
107
- networkPresets: [localPreset, customPreset]
320
+ networkPresets: [localPreset, customPreset],
321
+ assetNetworkStates,
322
+ trustedDappPolicies,
323
+ connectedDappMetadata
108
324
  };
109
325
  }
110
326
  const presets = new Map();
@@ -131,7 +347,118 @@ function normalizeStoredWalletNetworks(state) {
131
347
  rpcUrl: activePreset.rpcUrl,
132
348
  dashboardUrl: activePreset.dashboardUrl,
133
349
  activeNetworkId,
134
- networkPresets: [...presets.values()]
350
+ networkPresets: [...presets.values()],
351
+ assetNetworkStates,
352
+ trustedDappPolicies,
353
+ connectedDappMetadata
354
+ };
355
+ }
356
+ function updateAssetNetworkStateInWallet(state, networkId, contract, update) {
357
+ const currentStates = normalizeAssetNetworkStates(state.assetNetworkStates);
358
+ const currentNetwork = currentStates[networkId] ?? {};
359
+ const currentAsset = currentNetwork[contract] ?? {};
360
+ const nextAsset = { ...currentAsset, ...update };
361
+ if (nextAsset.status === "available" || nextAsset.status === "unknown") {
362
+ delete nextAsset.error;
363
+ }
364
+ if (JSON.stringify(currentAsset) === JSON.stringify(nextAsset)) {
365
+ return { state, changed: false };
366
+ }
367
+ return {
368
+ state: {
369
+ ...state,
370
+ assetNetworkStates: {
371
+ ...currentStates,
372
+ [networkId]: {
373
+ ...currentNetwork,
374
+ [contract]: nextAsset
375
+ }
376
+ }
377
+ },
378
+ changed: true
379
+ };
380
+ }
381
+ function removeAssetNetworkStateFromWallet(state, contract) {
382
+ const currentStates = normalizeAssetNetworkStates(state.assetNetworkStates);
383
+ let changed = false;
384
+ const assetNetworkStates = Object.fromEntries(Object.entries(currentStates).flatMap(([networkId, networkState]) => {
385
+ if (!(contract in networkState)) {
386
+ return [[networkId, networkState]];
387
+ }
388
+ changed = true;
389
+ const nextNetworkState = { ...networkState };
390
+ delete nextNetworkState[contract];
391
+ return Object.keys(nextNetworkState).length > 0
392
+ ? [[networkId, nextNetworkState]]
393
+ : [];
394
+ }));
395
+ return changed ? { ...state, assetNetworkStates } : state;
396
+ }
397
+ function sameTrustedDappPolicyScope(left, right) {
398
+ return (left.origin === right.origin &&
399
+ left.account === right.account &&
400
+ left.chainId === right.chainId &&
401
+ left.contract === right.contract &&
402
+ left.function === right.function &&
403
+ left.methods.length === right.methods.length &&
404
+ left.methods.every((method) => right.methods.includes(method)));
405
+ }
406
+ function parseShieldedWalletSnapshot(stateSnapshot) {
407
+ let decoded;
408
+ try {
409
+ decoded = JSON.parse(stateSnapshot);
410
+ }
411
+ catch {
412
+ throw new Error("shielded wallet snapshot must be valid JSON");
413
+ }
414
+ if (typeof decoded !== "object" || decoded == null || Array.isArray(decoded)) {
415
+ throw new Error("shielded wallet snapshot must be a JSON object");
416
+ }
417
+ const record = decoded;
418
+ const assetId = typeof record.asset_id === "string" ? trimOptionalString(record.asset_id) : undefined;
419
+ if (!assetId) {
420
+ throw new Error("shielded wallet snapshot must contain asset_id");
421
+ }
422
+ if (typeof record.owner_secret !== "string" || record.owner_secret.length === 0) {
423
+ throw new Error("shielded wallet snapshot must contain owner_secret");
424
+ }
425
+ if (typeof record.viewing_private_key !== "string" ||
426
+ record.viewing_private_key.length === 0) {
427
+ throw new Error("shielded wallet snapshot must contain viewing_private_key");
428
+ }
429
+ const notes = record.notes ?? [];
430
+ if (!Array.isArray(notes)) {
431
+ throw new Error("shielded wallet snapshot notes must be an array");
432
+ }
433
+ const commitments = record.commitments ?? [];
434
+ if (!Array.isArray(commitments) || commitments.some((value) => typeof value !== "string")) {
435
+ throw new Error("shielded wallet snapshot commitments must be an array of strings");
436
+ }
437
+ const lastScannedValue = record.last_scanned_index;
438
+ const lastScannedIndex = typeof lastScannedValue === "number" &&
439
+ Number.isInteger(lastScannedValue) &&
440
+ lastScannedValue >= 0
441
+ ? lastScannedValue
442
+ : commitments.length;
443
+ return {
444
+ normalizedSnapshot: JSON.stringify(record),
445
+ assetId,
446
+ syncHint: shieldedSyncHintFromViewingPrivateKey(record.viewing_private_key),
447
+ noteCount: notes.length,
448
+ commitmentCount: commitments.length,
449
+ lastScannedIndex,
450
+ };
451
+ }
452
+ function shieldedWalletSnapshotSummary(record) {
453
+ return {
454
+ id: record.id,
455
+ label: record.label,
456
+ assetId: record.assetId,
457
+ syncHint: record.syncHint,
458
+ noteCount: record.noteCount,
459
+ commitmentCount: record.commitmentCount,
460
+ lastScannedIndex: record.lastScannedIndex,
461
+ updatedAt: record.updatedAt,
135
462
  };
136
463
  }
137
464
  function hydrateError(error) {
@@ -148,6 +475,7 @@ export class WalletController {
148
475
  unlockedSigner = null;
149
476
  unlockedSessionKey = null;
150
477
  unlockedMnemonic = null;
478
+ unlockedSessionExpiresAt = null;
151
479
  constructor(options) {
152
480
  this.options = options;
153
481
  }
@@ -181,23 +509,24 @@ export class WalletController {
181
509
  };
182
510
  }
183
511
  async restoreUnlockedSession() {
184
- if (this.unlockedPrivateKey) {
185
- return true;
186
- }
187
512
  const session = await this.store.loadUnlockedSession();
188
513
  if (!session) {
514
+ this.unlockedPrivateKey = null;
515
+ this.unlockedSigner = null;
516
+ this.unlockedMnemonic = null;
517
+ this.unlockedSessionKey = null;
518
+ this.unlockedSessionExpiresAt = null;
189
519
  return false;
190
520
  }
191
521
  if (session.expiresAt <= this.now()) {
192
- await this.store.clearUnlockedSession();
522
+ await this.expireUnlockedSession();
193
523
  return false;
194
524
  }
195
525
  this.unlockedPrivateKey = session.privateKey;
196
526
  this.unlockedSigner = new Ed25519Signer(session.privateKey);
197
- if (session.mnemonic) {
198
- this.unlockedMnemonic = session.mnemonic;
199
- }
527
+ this.unlockedMnemonic = session.mnemonic ?? null;
200
528
  this.unlockedSessionKey = session.sessionKey;
529
+ this.unlockedSessionExpiresAt = session.expiresAt;
201
530
  return true;
202
531
  }
203
532
  async resolveUnlockedSessionExpiry() {
@@ -222,14 +551,24 @@ export class WalletController {
222
551
  expiresAt: nextExpiresAt
223
552
  };
224
553
  await this.store.saveUnlockedSession(session);
554
+ this.unlockedSessionExpiresAt = nextExpiresAt;
225
555
  }
226
556
  async clearUnlockedSession() {
227
557
  this.unlockedPrivateKey = null;
228
558
  this.unlockedSigner = null;
229
559
  this.unlockedMnemonic = null;
230
560
  this.unlockedSessionKey = null;
561
+ this.unlockedSessionExpiresAt = null;
231
562
  await this.store.clearUnlockedSession();
232
563
  }
564
+ async expireUnlockedSession() {
565
+ await this.clearUnlockedSession();
566
+ const state = await this.loadWalletState();
567
+ if (!state) {
568
+ return;
569
+ }
570
+ await Promise.allSettled(state.connectedOrigins.map((origin) => this.emitDisconnectLifecycle(origin)));
571
+ }
233
572
  async getUnlockedSigner() {
234
573
  await this.restoreUnlockedSession();
235
574
  if (!this.unlockedPrivateKey) {
@@ -256,6 +595,54 @@ export class WalletController {
256
595
  }
257
596
  return normalizeStoredWalletNetworks(state);
258
597
  }
598
+ async resolveTokenMetadataForState(state, contract) {
599
+ const normalizedContract = contract.trim();
600
+ const client = this.currentClient(state);
601
+ const metadata = await client.getTokenMetadata(normalizedContract);
602
+ return {
603
+ contract: normalizedContract,
604
+ name: trimNullableString(metadata.name),
605
+ symbol: trimNullableString(metadata.symbol),
606
+ logoUrl: trimNullableString(metadata.logoUrl),
607
+ logoSvg: trimNullableString(metadata.logoSvg)
608
+ };
609
+ }
610
+ async hydrateWatchedAssetIcons(state) {
611
+ const assetsMissingIcons = state.watchedAssets.some((asset) => !trimOptionalString(asset.icon));
612
+ if (!assetsMissingIcons) {
613
+ return state;
614
+ }
615
+ let changed = false;
616
+ const watchedAssets = await Promise.all(state.watchedAssets.map(async (asset) => {
617
+ if (trimOptionalString(asset.icon)) {
618
+ return asset;
619
+ }
620
+ try {
621
+ const metadata = await this.resolveTokenMetadataForState(state, asset.contract);
622
+ const icon = metadata.logoUrl ?? metadata.logoSvg ?? undefined;
623
+ if (!icon) {
624
+ return asset;
625
+ }
626
+ changed = true;
627
+ return {
628
+ ...asset,
629
+ icon
630
+ };
631
+ }
632
+ catch {
633
+ return asset;
634
+ }
635
+ }));
636
+ if (!changed) {
637
+ return state;
638
+ }
639
+ const nextState = {
640
+ ...state,
641
+ watchedAssets
642
+ };
643
+ await this.store.saveState(nextState);
644
+ return nextState;
645
+ }
259
646
  requireAccounts(state) {
260
647
  if (!state.accounts || state.accounts.length === 0) {
261
648
  throw new Error("wallet state has no accounts");
@@ -274,6 +661,52 @@ export class WalletController {
274
661
  }
275
662
  return decryptMnemonicWithSessionKey(state.encryptedMnemonic, await this.sessionKeyForState(state, password));
276
663
  }
664
+ async requireUnlockedSessionKey() {
665
+ if (!(await this.restoreUnlockedSession()) || !this.unlockedSessionKey) {
666
+ throw new ProviderUnauthorizedError("wallet is locked");
667
+ }
668
+ return this.unlockedSessionKey;
669
+ }
670
+ storedShieldedWalletSnapshots(state) {
671
+ return [...(state.shieldedWalletSnapshots ?? [])].sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
672
+ }
673
+ shieldedWalletSnapshotSummaries(state) {
674
+ return this.storedShieldedWalletSnapshots(state).map(shieldedWalletSnapshotSummary);
675
+ }
676
+ async exportShieldedWalletSnapshots(state, sessionKey) {
677
+ const exported = [];
678
+ for (const record of this.storedShieldedWalletSnapshots(state)) {
679
+ exported.push({
680
+ label: record.label,
681
+ stateSnapshot: await decryptSecretTextWithSessionKey(record.encryptedStateSnapshot, sessionKey),
682
+ });
683
+ }
684
+ return exported;
685
+ }
686
+ async importShieldedWalletSnapshots(snapshots, sessionKey, nowIso) {
687
+ const imported = [];
688
+ for (const item of snapshots ?? []) {
689
+ if (typeof item !== "object" ||
690
+ item == null ||
691
+ typeof item.label !== "string" ||
692
+ typeof item.stateSnapshot !== "string") {
693
+ throw new Error("backup shieldedStateSnapshots must contain label and stateSnapshot");
694
+ }
695
+ const parsed = parseShieldedWalletSnapshot(item.stateSnapshot);
696
+ imported.push({
697
+ id: this.createId(),
698
+ label: trimOptionalString(item.label) ?? parsed.assetId,
699
+ assetId: parsed.assetId,
700
+ syncHint: parsed.syncHint,
701
+ encryptedStateSnapshot: await encryptSecretTextWithSessionKey(parsed.normalizedSnapshot, sessionKey),
702
+ noteCount: parsed.noteCount,
703
+ commitmentCount: parsed.commitmentCount,
704
+ lastScannedIndex: parsed.lastScannedIndex,
705
+ updatedAt: nowIso,
706
+ });
707
+ }
708
+ return imported;
709
+ }
277
710
  activeNetworkPreset(state) {
278
711
  const normalized = normalizeStoredWalletNetworks(state);
279
712
  return (normalized.networkPresets.find((preset) => preset.id === normalized.activeNetworkId) ??
@@ -389,22 +822,102 @@ export class WalletController {
389
822
  await this.store.saveState(normalizeStoredWalletNetworks(state));
390
823
  return this.getPopupState();
391
824
  }
392
- async updateConnectedOrigin(origin, connected) {
825
+ async updateConnectedOrigin(origin, connected, dappMetadata) {
393
826
  const state = this.requireStoredWallet(await this.loadWalletState());
394
827
  const nextOrigins = new Set(state.connectedOrigins);
828
+ const nextDappMetadata = {
829
+ ...(state.connectedDappMetadata ?? {})
830
+ };
395
831
  if (connected) {
396
832
  nextOrigins.add(origin);
833
+ const normalizedMetadata = normalizeConnectedDappMetadataEntry(dappMetadata, { now: this.now() });
834
+ if (normalizedMetadata) {
835
+ nextDappMetadata[origin] = {
836
+ ...(nextDappMetadata[origin] ?? {}),
837
+ ...normalizedMetadata
838
+ };
839
+ }
397
840
  }
398
841
  else {
399
842
  nextOrigins.delete(origin);
843
+ delete nextDappMetadata[origin];
400
844
  }
401
845
  const nextState = {
402
846
  ...state,
403
- connectedOrigins: [...nextOrigins]
847
+ connectedOrigins: [...nextOrigins],
848
+ connectedDappMetadata: nextDappMetadata,
849
+ trustedDappPolicies: connected
850
+ ? state.trustedDappPolicies ?? []
851
+ : (state.trustedDappPolicies ?? []).filter((policy) => policy.origin !== origin)
404
852
  };
405
853
  await this.store.saveState(nextState);
406
854
  return nextState;
407
855
  }
856
+ async upsertTrustedDappPolicy(policy) {
857
+ const state = this.requireStoredWallet(await this.loadWalletState());
858
+ const currentPolicies = state.trustedDappPolicies ?? [];
859
+ await this.store.saveState({
860
+ ...state,
861
+ trustedDappPolicies: [
862
+ ...currentPolicies.filter((existing) => !sameTrustedDappPolicyScope(existing, policy)),
863
+ policy
864
+ ]
865
+ });
866
+ }
867
+ async touchTrustedDappPolicy(policyId) {
868
+ const state = this.requireStoredWallet(await this.loadWalletState());
869
+ const policies = state.trustedDappPolicies ?? [];
870
+ if (!policies.some((policy) => policy.id === policyId)) {
871
+ return;
872
+ }
873
+ await this.store.saveState({
874
+ ...state,
875
+ trustedDappPolicies: policies.map((policy) => policy.id === policyId
876
+ ? {
877
+ ...policy,
878
+ lastUsedAt: this.now(),
879
+ useCount: (policy.useCount ?? 0) + 1
880
+ }
881
+ : policy)
882
+ });
883
+ }
884
+ async maybeExecuteTrustedDappRequest(state, origin, request, account, chainId) {
885
+ if (!chainId) {
886
+ return null;
887
+ }
888
+ const match = findMatchingXianDappPolicy(state.trustedDappPolicies ?? [], {
889
+ origin,
890
+ account,
891
+ chainId,
892
+ now: this.now()
893
+ }, request);
894
+ if (!match.matched || !match.policy) {
895
+ return null;
896
+ }
897
+ const value = await this.executeApprovedRequest(origin, request);
898
+ await this.touchTrustedDappPolicy(match.policy.id);
899
+ return {
900
+ kind: "result",
901
+ value
902
+ };
903
+ }
904
+ async createTrustedDappPolicyForApproval(approval) {
905
+ const state = this.requireStoredWallet(await this.loadWalletState());
906
+ const activeChainId = approval.view.chainId ??
907
+ this.displayChainId(this.activeNetworkPreset(state), await this.safeGetChainId(state));
908
+ if (!activeChainId) {
909
+ return null;
910
+ }
911
+ return createXianDappPolicyForRequest({
912
+ id: this.createId(),
913
+ origin: approval.record.origin,
914
+ account: state.publicKey,
915
+ chainId: activeChainId,
916
+ request: approval.record.request,
917
+ now: this.now(),
918
+ expiresAt: this.now() + TRUSTED_DAPP_POLICY_TTL_MS
919
+ });
920
+ }
408
921
  async updateWatchedAssets(updater) {
409
922
  const state = this.requireStoredWallet(await this.loadWalletState());
410
923
  await this.store.saveState({
@@ -435,9 +948,9 @@ export class WalletController {
435
948
  seenContracts.add(contract);
436
949
  detectedAssets.push({
437
950
  contract,
438
- name: trimOptionalString(item.name ?? undefined),
439
- symbol: trimOptionalString(item.symbol ?? undefined),
440
- icon: trimOptionalString(item.logoUrl ?? undefined),
951
+ name: trimOptionalIndexedString(item.name),
952
+ symbol: trimOptionalIndexedString(item.symbol),
953
+ icon: trimOptionalIndexedString(item.logoUrl),
441
954
  balance: item.balance,
442
955
  tracked: trackedContracts.has(contract)
443
956
  });
@@ -569,8 +1082,8 @@ export class WalletController {
569
1082
  function: intent.function,
570
1083
  kwargs: intent.kwargs,
571
1084
  chainId: activeChainId,
572
- stamps: parseIntentNumber(intent.stamps, "stamps"),
573
- stampsSupplied: parseIntentNumber(intent.stampsSupplied, "stampsSupplied")
1085
+ chi: parseIntentNumber(intent.chi, "chi"),
1086
+ chiSupplied: parseIntentNumber(intent.chiSupplied, "chiSupplied")
574
1087
  });
575
1088
  }
576
1089
  async signPreparedTransaction(state, tx) {
@@ -588,13 +1101,13 @@ export class WalletController {
588
1101
  const signedTx = await this.signPreparedTransaction(state, tx);
589
1102
  return this.currentClient(state).broadcastTx(signedTx, options);
590
1103
  }
591
- async executeApprovedRequest(origin, request) {
1104
+ async executeApprovedRequest(origin, request, dappMetadata) {
592
1105
  const state = this.requireStoredWallet(await this.loadWalletState());
593
1106
  switch (request.method) {
594
1107
  case "xian_requestAccounts": {
595
1108
  await this.getUnlockedSigner();
596
1109
  const chainId = this.displayChainId(this.activeNetworkPreset(state), await this.safeGetChainId(state));
597
- const nextState = await this.updateConnectedOrigin(origin, true);
1110
+ const nextState = await this.updateConnectedOrigin(origin, true, dappMetadata);
598
1111
  await this.emitConnectionLifecycle(origin, chainId ?? "unknown", nextState.publicKey);
599
1112
  return [nextState.publicKey];
600
1113
  }
@@ -735,7 +1248,7 @@ export class WalletController {
735
1248
  return rejected;
736
1249
  }
737
1250
  }
738
- async executeImmediateRequest(state, origin, request) {
1251
+ async executeImmediateRequest(state, origin, request, dappMetadata) {
739
1252
  switch (request.method) {
740
1253
  case "xian_getWalletInfo":
741
1254
  return {
@@ -747,9 +1260,10 @@ export class WalletController {
747
1260
  await this.getUnlockedSigner();
748
1261
  const approvalChainId = this.displayChainId(this.activeNetworkPreset(walletState), await this.safeGetChainId(walletState));
749
1262
  if (walletState.connectedOrigins.includes(origin)) {
1263
+ const nextState = await this.updateConnectedOrigin(origin, true, dappMetadata);
750
1264
  return {
751
1265
  kind: "result",
752
- value: [walletState.publicKey]
1266
+ value: [nextState.publicKey]
753
1267
  };
754
1268
  }
755
1269
  return {
@@ -852,10 +1366,15 @@ export class WalletController {
852
1366
  const walletState = this.requireStoredWallet(state);
853
1367
  this.requireConnectedOrigin(walletState, origin);
854
1368
  await this.getUnlockedSigner();
1369
+ const activeChainId = this.displayChainId(this.activeNetworkPreset(walletState), await this.safeGetChainId(walletState));
1370
+ const trustedResult = await this.maybeExecuteTrustedDappRequest(walletState, origin, request, walletState.publicKey, activeChainId);
1371
+ if (trustedResult) {
1372
+ return trustedResult;
1373
+ }
855
1374
  return {
856
1375
  kind: "approval",
857
1376
  account: walletState.publicKey,
858
- chainId: this.displayChainId(this.activeNetworkPreset(walletState), await this.safeGetChainId(walletState))
1377
+ chainId: activeChainId
859
1378
  };
860
1379
  }
861
1380
  default:
@@ -870,7 +1389,10 @@ export class WalletController {
870
1389
  }));
871
1390
  }
872
1391
  async getPopupState() {
873
- const state = await this.loadWalletState();
1392
+ const loadedState = await this.loadWalletState();
1393
+ const state = loadedState
1394
+ ? await this.hydrateWatchedAssetIcons(loadedState)
1395
+ : null;
874
1396
  const approvals = await this.store.listApprovalStates();
875
1397
  const pendingApprovals = approvals
876
1398
  .map((approval) => approval.view)
@@ -882,6 +1404,9 @@ export class WalletController {
882
1404
  return {
883
1405
  hasWallet: state != null,
884
1406
  unlocked,
1407
+ sessionExpiresAt: unlocked
1408
+ ? this.unlockedSessionExpiresAt ?? undefined
1409
+ : undefined,
885
1410
  publicKey: state?.publicKey,
886
1411
  rpcUrl: state?.rpcUrl ?? DEFAULT_RPC_URL,
887
1412
  dashboardUrl: state?.dashboardUrl ?? DEFAULT_DASHBOARD_URL,
@@ -897,10 +1422,13 @@ export class WalletController {
897
1422
  activeNetworkName: activePreset?.name,
898
1423
  networkPresets: state?.networkPresets ?? DEFAULT_NETWORK_PRESETS,
899
1424
  watchedAssets,
1425
+ assetNetworkStates: state?.assetNetworkStates ?? {},
900
1426
  detectedAssets: [],
901
1427
  assetBalances: {},
902
1428
  assetFiatValues: {},
903
1429
  connectedOrigins: state?.connectedOrigins ?? [],
1430
+ trustedDappPolicies: state?.trustedDappPolicies ?? [],
1431
+ connectedDappMetadata: state?.connectedDappMetadata ?? {},
904
1432
  pendingApprovalCount: pendingApprovals.length,
905
1433
  pendingApprovals,
906
1434
  hasRecoveryPhrase: Boolean(state?.encryptedMnemonic),
@@ -908,19 +1436,28 @@ export class WalletController {
908
1436
  mnemonicWordCount: state?.mnemonicWordCount,
909
1437
  accounts: state ? this.getAccountsList(state) : [],
910
1438
  activeAccountIndex: state?.activeAccountIndex ?? 0,
1439
+ shieldedWalletSnapshots: state
1440
+ ? this.shieldedWalletSnapshotSummaries(state)
1441
+ : [],
911
1442
  version: this.options.version
912
1443
  };
913
1444
  }
914
1445
  async getAssetBalances() {
1446
+ return (await this.getAssetBalanceSnapshot()).balances;
1447
+ }
1448
+ async getAssetBalanceSnapshot() {
915
1449
  const state = await this.loadWalletState();
916
1450
  if (!state) {
917
- return {};
1451
+ return {
1452
+ balances: {},
1453
+ assetNetworkStates: {}
1454
+ };
918
1455
  }
919
- return this.fetchAssetBalances(state, state.watchedAssets);
1456
+ return this.fetchAssetBalanceSnapshot(state, state.watchedAssets);
920
1457
  }
921
1458
  async getTokenMetadata(contract) {
922
1459
  const state = this.requireStoredWallet(await this.loadWalletState());
923
- return this.currentClient(state).getTokenMetadata(contract);
1460
+ return this.resolveTokenMetadataForState(state, contract);
924
1461
  }
925
1462
  async getDetectedAssets() {
926
1463
  const state = await this.loadWalletState();
@@ -939,36 +1476,48 @@ export class WalletController {
939
1476
  if (!normalized.contract) {
940
1477
  throw new TypeError("asset contract is required");
941
1478
  }
942
- // Auto-fetch metadata if name/symbol not provided
943
- if (!normalized.name || !normalized.symbol) {
1479
+ const state = this.requireStoredWallet(await this.loadWalletState());
1480
+ let networkState = {
1481
+ status: "available",
1482
+ lastCheckedAt: new Date().toISOString()
1483
+ };
1484
+ // Auto-fetch metadata if any display metadata is missing.
1485
+ if (!normalized.name || !normalized.symbol || !normalized.icon) {
944
1486
  try {
945
- const state = this.requireStoredWallet(await this.loadWalletState());
946
- const meta = await this.currentClient(state).getTokenMetadata(normalized.contract);
1487
+ const meta = await this.resolveTokenMetadataForState(state, normalized.contract);
947
1488
  if (meta.name && !normalized.name)
948
1489
  normalized.name = meta.name;
949
1490
  if (meta.symbol && !normalized.symbol)
950
1491
  normalized.symbol = meta.symbol;
951
1492
  if (meta.logoUrl && !normalized.icon)
952
1493
  normalized.icon = meta.logoUrl;
1494
+ if (meta.logoSvg && !normalized.icon)
1495
+ normalized.icon = meta.logoSvg;
953
1496
  }
954
- catch {
955
- // Metadata fetch failed — use contract name as fallback
1497
+ catch (error) {
1498
+ networkState = {
1499
+ status: isMissingContractResult(error) ? "not_found" : "unknown",
1500
+ lastCheckedAt: new Date().toISOString(),
1501
+ error: messageFromUnknown(error)
1502
+ };
956
1503
  }
957
1504
  }
958
- await this.updateWatchedAssets((assets) => {
959
- const next = assets.filter((entry) => entry.contract !== normalized.contract);
960
- next.push(normalized);
961
- return next;
962
- });
1505
+ const watchedAssets = state.watchedAssets.filter((entry) => entry.contract !== normalized.contract);
1506
+ watchedAssets.push(normalized);
1507
+ const updated = updateAssetNetworkStateInWallet({
1508
+ ...state,
1509
+ watchedAssets
1510
+ }, state.activeNetworkId, normalized.contract, networkState).state;
1511
+ await this.store.saveState(updated);
963
1512
  return this.getPopupState();
964
1513
  }
965
1514
  async updateAssetSettings(assets) {
966
- const state = this.requireStoredWallet(await this.loadWalletState());
1515
+ let state = this.requireStoredWallet(await this.loadWalletState());
967
1516
  for (const update of assets) {
968
1517
  const asset = state.watchedAssets.find((a) => a.contract === update.contract);
969
1518
  if (asset) {
970
1519
  if (update.hidden !== undefined) {
971
- asset.hidden = update.hidden;
1520
+ state = updateAssetNetworkStateInWallet(state, state.activeNetworkId, update.contract, { hidden: update.hidden }).state;
972
1521
  }
973
1522
  if (update.order !== undefined) {
974
1523
  asset.order = update.order;
@@ -989,16 +1538,32 @@ export class WalletController {
989
1538
  await this.store.saveState(state);
990
1539
  return this.getPopupState();
991
1540
  }
992
- async estimateTransactionStamps(request) {
1541
+ async estimateTransactionChi(request) {
993
1542
  const state = this.requireStoredWallet(await this.loadWalletState());
994
1543
  const client = this.currentClient(state);
995
- return client.estimateStamps({
1544
+ return client.estimateChi({
996
1545
  sender: state.publicKey,
997
1546
  contract: request.contract,
998
1547
  function: request.function,
999
1548
  kwargs: request.kwargs
1000
1549
  });
1001
1550
  }
1551
+ async getChiRate() {
1552
+ const state = await this.loadWalletState();
1553
+ if (!state)
1554
+ return null;
1555
+ try {
1556
+ const client = this.currentClient(state);
1557
+ if (typeof client.getChiRate !== "function") {
1558
+ return null;
1559
+ }
1560
+ const rate = await client.getChiRate();
1561
+ return rate != null ? Number(rate) : null;
1562
+ }
1563
+ catch {
1564
+ return null;
1565
+ }
1566
+ }
1002
1567
  async sendDirectTransaction(intent) {
1003
1568
  const state = this.requireStoredWallet(await this.loadWalletState());
1004
1569
  await this.getUnlockedSigner();
@@ -1006,7 +1571,7 @@ export class WalletController {
1006
1571
  contract: intent.contract,
1007
1572
  function: intent.function,
1008
1573
  kwargs: intent.kwargs,
1009
- stamps: intent.stamps
1574
+ chi: intent.chi
1010
1575
  });
1011
1576
  return this.sendPreparedTransaction(state, tx, { mode: "commit" });
1012
1577
  }
@@ -1014,30 +1579,85 @@ export class WalletController {
1014
1579
  const state = this.requireStoredWallet(await this.loadWalletState());
1015
1580
  return this.currentClient(state).getContractMethods(contract);
1016
1581
  }
1017
- async fetchAssetBalances(state, assets) {
1582
+ async fetchAssetBalanceSnapshot(state, assets) {
1018
1583
  const balances = {};
1019
1584
  if (!state || assets.length === 0) {
1020
- return balances;
1585
+ return {
1586
+ balances,
1587
+ assetNetworkStates: state?.assetNetworkStates ?? {}
1588
+ };
1021
1589
  }
1022
1590
  const client = this.currentClient(state);
1591
+ let nextState = state;
1592
+ let changed = false;
1593
+ const checkedAt = new Date().toISOString();
1023
1594
  const results = await Promise.allSettled(assets.map(async (asset) => {
1024
1595
  const raw = await client.getBalance(state.publicKey, {
1025
1596
  contract: asset.contract
1026
1597
  });
1027
1598
  return { contract: asset.contract, raw };
1028
1599
  }));
1029
- for (const result of results) {
1600
+ for (const [index, result] of results.entries()) {
1030
1601
  if (result.status === "fulfilled") {
1031
1602
  const { contract, raw } = result.value;
1032
- balances[contract] =
1033
- raw != null ? String(raw) : null;
1603
+ if (isMissingContractResult(raw)) {
1604
+ balances[contract] = null;
1605
+ const updated = updateAssetNetworkStateInWallet(nextState, state.activeNetworkId, contract, {
1606
+ status: "not_found",
1607
+ lastCheckedAt: checkedAt,
1608
+ error: messageFromUnknown(raw)
1609
+ });
1610
+ nextState = updated.state;
1611
+ changed = changed || updated.changed;
1612
+ continue;
1613
+ }
1614
+ balances[contract] = raw != null ? String(raw) : null;
1615
+ const updated = updateAssetNetworkStateInWallet(nextState, state.activeNetworkId, contract, { status: "available", lastCheckedAt: checkedAt });
1616
+ nextState = updated.state;
1617
+ changed = changed || updated.changed;
1034
1618
  }
1035
1619
  else {
1036
- // If a single balance fetch fails, mark it null rather than
1037
- // failing the entire popup state.
1620
+ const reason = result.reason;
1621
+ const contract = assets[index]?.contract;
1622
+ if (!contract) {
1623
+ continue;
1624
+ }
1625
+ balances[contract] = null;
1626
+ const updated = updateAssetNetworkStateInWallet(nextState, state.activeNetworkId, contract, {
1627
+ status: isMissingContractResult(reason) ? "not_found" : "unknown",
1628
+ lastCheckedAt: checkedAt,
1629
+ error: messageFromUnknown(reason)
1630
+ });
1631
+ nextState = updated.state;
1632
+ changed = changed || updated.changed;
1633
+ }
1634
+ }
1635
+ let assetNetworkStates = nextState.assetNetworkStates ?? {};
1636
+ if (changed) {
1637
+ const latestState = await this.loadWalletState();
1638
+ if (latestState?.publicKey === state.publicKey) {
1639
+ const networkId = state.activeNetworkId;
1640
+ const latestStates = latestState.assetNetworkStates ?? {};
1641
+ const latestNetworkState = latestStates[networkId] ?? {};
1642
+ const fetchedNetworkState = nextState.assetNetworkStates?.[networkId] ?? {};
1643
+ const mergedState = {
1644
+ ...latestState,
1645
+ assetNetworkStates: {
1646
+ ...latestStates,
1647
+ [networkId]: {
1648
+ ...latestNetworkState,
1649
+ ...fetchedNetworkState
1650
+ }
1651
+ }
1652
+ };
1653
+ await this.store.saveState(mergedState);
1654
+ assetNetworkStates = mergedState.assetNetworkStates ?? {};
1038
1655
  }
1039
1656
  }
1040
- return balances;
1657
+ return {
1658
+ balances,
1659
+ assetNetworkStates
1660
+ };
1041
1661
  }
1042
1662
  async createOrImportWallet(input) {
1043
1663
  const secret = await createWalletSecret({
@@ -1108,6 +1728,15 @@ export class WalletController {
1108
1728
  symbol: "XIAN"
1109
1729
  }
1110
1730
  ],
1731
+ assetNetworkStates: {
1732
+ [activePreset.id]: {
1733
+ currency: {
1734
+ status: "available"
1735
+ }
1736
+ }
1737
+ },
1738
+ trustedDappPolicies: [],
1739
+ connectedDappMetadata: {},
1111
1740
  connectedOrigins: [],
1112
1741
  createdAt: new Date().toISOString()
1113
1742
  });
@@ -1152,6 +1781,7 @@ export class WalletController {
1152
1781
  async exportWallet(password) {
1153
1782
  const state = this.requireStoredWallet(await this.loadWalletState());
1154
1783
  const accounts = this.requireAccounts(state);
1784
+ const sessionKey = await this.sessionKeyForState(state, password);
1155
1785
  const backup = {
1156
1786
  version: 1,
1157
1787
  type: state.seedSource,
@@ -1159,13 +1789,18 @@ export class WalletController {
1159
1789
  activeAccountIndex: state.activeAccountIndex ?? accounts[0]?.index ?? 0,
1160
1790
  activeNetworkId: state.activeNetworkId,
1161
1791
  networkPresets: state.networkPresets.filter((p) => !p.builtin),
1162
- watchedAssets: state.watchedAssets
1792
+ watchedAssets: state.watchedAssets,
1793
+ assetNetworkStates: state.assetNetworkStates
1163
1794
  };
1164
1795
  if (state.encryptedMnemonic) {
1165
- backup.mnemonic = await this.decryptMnemonicForState(state, password);
1796
+ backup.mnemonic = await decryptMnemonicWithSessionKey(state.encryptedMnemonic, sessionKey);
1166
1797
  }
1167
1798
  else {
1168
- backup.privateKey = await this.decryptPrivateKeyForState(state, password);
1799
+ backup.privateKey = await decryptPrivateKeyWithSessionKey(state.encryptedPrivateKey, sessionKey);
1800
+ }
1801
+ const shieldedStateSnapshots = await this.exportShieldedWalletSnapshots(state, sessionKey);
1802
+ if (shieldedStateSnapshots.length > 0) {
1803
+ backup.shieldedStateSnapshots = shieldedStateSnapshots;
1169
1804
  }
1170
1805
  return backup;
1171
1806
  }
@@ -1184,6 +1819,7 @@ export class WalletController {
1184
1819
  throw new Error("backup must contain a mnemonic or private key");
1185
1820
  }
1186
1821
  const { walletEncryptionSalt, sessionKey } = await createWalletSessionKey(password);
1822
+ const nowIso = new Date().toISOString();
1187
1823
  const encryptedMnemonic = mnemonic
1188
1824
  ? await encryptMnemonicWithSessionKey(mnemonic, sessionKey)
1189
1825
  : undefined;
@@ -1235,6 +1871,7 @@ export class WalletController {
1235
1871
  const watchedAssets = backup.watchedAssets?.length
1236
1872
  ? backup.watchedAssets
1237
1873
  : [{ contract: "currency", name: "Xian", symbol: "XIAN" }];
1874
+ const shieldedWalletSnapshots = await this.importShieldedWalletSnapshots(backup.shieldedStateSnapshots, sessionKey, nowIso);
1238
1875
  await this.persistWalletState({
1239
1876
  publicKey: activeAccount.publicKey,
1240
1877
  encryptedPrivateKey: activeAccount.encryptedPrivateKey,
@@ -1249,11 +1886,102 @@ export class WalletController {
1249
1886
  activeNetworkId: activePreset.id,
1250
1887
  networkPresets: presets,
1251
1888
  watchedAssets,
1889
+ assetNetworkStates: backup.assetNetworkStates,
1890
+ shieldedWalletSnapshots,
1891
+ trustedDappPolicies: [],
1892
+ connectedDappMetadata: {},
1252
1893
  connectedOrigins: [],
1253
- createdAt: new Date().toISOString()
1894
+ createdAt: nowIso
1254
1895
  });
1255
1896
  return this.getPopupState();
1256
1897
  }
1898
+ async saveShieldedWalletSnapshot(stateSnapshot, label) {
1899
+ const state = this.requireStoredWallet(await this.loadWalletState());
1900
+ const sessionKey = await this.requireUnlockedSessionKey();
1901
+ const parsed = parseShieldedWalletSnapshot(stateSnapshot);
1902
+ const resolvedLabel = trimOptionalString(label) ?? parsed.assetId;
1903
+ const existing = this.storedShieldedWalletSnapshots(state).find((record) => record.assetId === parsed.assetId && record.label === resolvedLabel);
1904
+ const updatedAt = new Date().toISOString();
1905
+ const nextRecord = {
1906
+ id: existing?.id ?? this.createId(),
1907
+ label: resolvedLabel,
1908
+ assetId: parsed.assetId,
1909
+ syncHint: parsed.syncHint,
1910
+ encryptedStateSnapshot: await encryptSecretTextWithSessionKey(parsed.normalizedSnapshot, sessionKey),
1911
+ noteCount: parsed.noteCount,
1912
+ commitmentCount: parsed.commitmentCount,
1913
+ lastScannedIndex: parsed.lastScannedIndex,
1914
+ updatedAt,
1915
+ };
1916
+ state.shieldedWalletSnapshots = [
1917
+ nextRecord,
1918
+ ...this.storedShieldedWalletSnapshots(state).filter((record) => record.id !== nextRecord.id),
1919
+ ];
1920
+ await this.persistWalletState(state);
1921
+ return this.getPopupState();
1922
+ }
1923
+ async exportShieldedWalletSnapshot(snapshotId, password) {
1924
+ const state = this.requireStoredWallet(await this.loadWalletState());
1925
+ const record = this.storedShieldedWalletSnapshots(state).find((item) => item.id === snapshotId);
1926
+ if (!record) {
1927
+ throw new Error("shielded wallet snapshot not found");
1928
+ }
1929
+ const sessionKey = await this.sessionKeyForState(state, password);
1930
+ return {
1931
+ label: record.label,
1932
+ stateSnapshot: await decryptSecretTextWithSessionKey(record.encryptedStateSnapshot, sessionKey),
1933
+ };
1934
+ }
1935
+ async removeShieldedWalletSnapshot(snapshotId) {
1936
+ const state = this.requireStoredWallet(await this.loadWalletState());
1937
+ const nextSnapshots = this.storedShieldedWalletSnapshots(state).filter((record) => record.id !== snapshotId);
1938
+ if (nextSnapshots.length === this.storedShieldedWalletSnapshots(state).length) {
1939
+ throw new Error("shielded wallet snapshot not found");
1940
+ }
1941
+ state.shieldedWalletSnapshots = nextSnapshots;
1942
+ await this.persistWalletState(state);
1943
+ return this.getPopupState();
1944
+ }
1945
+ async getShieldedWalletSnapshotHistory(snapshotId, limit = 5) {
1946
+ const state = this.requireStoredWallet(await this.loadWalletState());
1947
+ const record = this.storedShieldedWalletSnapshots(state).find((item) => item.id === snapshotId);
1948
+ if (!record) {
1949
+ throw new Error("shielded wallet snapshot not found");
1950
+ }
1951
+ const client = this.currentClient(state);
1952
+ if (typeof client.getShieldedWalletHistory !== "function") {
1953
+ return {
1954
+ snapshotId: record.id,
1955
+ label: record.label,
1956
+ available: false,
1957
+ hasNewerIndexedHistory: false,
1958
+ checkedAfterNoteIndex: record.lastScannedIndex,
1959
+ newItems: [],
1960
+ };
1961
+ }
1962
+ const history = await client.getShieldedWalletHistory(record.syncHint, {
1963
+ kind: "sync_hint",
1964
+ limit: Math.max(1, Math.min(Math.trunc(limit), 10)),
1965
+ afterNoteIndex: record.lastScannedIndex,
1966
+ });
1967
+ return {
1968
+ snapshotId: record.id,
1969
+ label: record.label,
1970
+ available: history.available,
1971
+ hasNewerIndexedHistory: history.items.length > 0,
1972
+ checkedAfterNoteIndex: record.lastScannedIndex,
1973
+ newItems: history.items.map((item) => ({
1974
+ txHash: item.txHash,
1975
+ blockHeight: item.blockHeight,
1976
+ function: item.function,
1977
+ action: item.action,
1978
+ noteIndex: item.noteIndex,
1979
+ commitment: item.commitment,
1980
+ hasPayload: item.outputPayload != null && item.outputPayload !== "",
1981
+ createdAt: item.createdAt,
1982
+ })),
1983
+ };
1984
+ }
1257
1985
  async addAccount() {
1258
1986
  await this.restoreUnlockedSession();
1259
1987
  if (!this.unlockedMnemonic || !this.unlockedSessionKey) {
@@ -1408,12 +2136,29 @@ export class WalletController {
1408
2136
  }
1409
2137
  const nextState = {
1410
2138
  ...state,
1411
- connectedOrigins: []
2139
+ connectedOrigins: [],
2140
+ trustedDappPolicies: [],
2141
+ connectedDappMetadata: {}
1412
2142
  };
1413
2143
  await this.store.saveState(nextState);
1414
2144
  await Promise.all(state.connectedOrigins.map((origin) => this.emitDisconnectLifecycle(origin)));
1415
2145
  return this.getPopupState();
1416
2146
  }
2147
+ async removeTrustedDappPolicy(policyId) {
2148
+ const state = await this.loadWalletState();
2149
+ if (!state) {
2150
+ return this.getPopupState();
2151
+ }
2152
+ const nextPolicies = (state.trustedDappPolicies ?? []).filter((policy) => policy.id !== policyId);
2153
+ if (nextPolicies.length === (state.trustedDappPolicies ?? []).length) {
2154
+ return this.getPopupState();
2155
+ }
2156
+ await this.store.saveState({
2157
+ ...state,
2158
+ trustedDappPolicies: nextPolicies
2159
+ });
2160
+ return this.getPopupState();
2161
+ }
1417
2162
  async removeWatchedAsset(contract) {
1418
2163
  const trimmed = contract.trim();
1419
2164
  if (trimmed.length === 0) {
@@ -1426,10 +2171,10 @@ export class WalletController {
1426
2171
  if (trimmed === "currency") {
1427
2172
  throw new Error("the native XIAN asset is pinned in the wallet");
1428
2173
  }
1429
- return this.persistWalletState({
2174
+ return this.persistWalletState(removeAssetNetworkStateFromWallet({
1430
2175
  ...state,
1431
2176
  watchedAssets: state.watchedAssets.filter((asset) => asset.contract !== trimmed)
1432
- });
2177
+ }, trimmed));
1433
2178
  }
1434
2179
  async saveNetworkPreset(input) {
1435
2180
  const state = this.requireStoredWallet(await this.loadWalletState());
@@ -1477,7 +2222,7 @@ export class WalletController {
1477
2222
  await this.emitChainChangedForConnectedOrigins(nextState, previousChainId);
1478
2223
  return this.getPopupState();
1479
2224
  }
1480
- async startProviderRequest(requestId, origin, request) {
2225
+ async startProviderRequest(requestId, origin, request, options) {
1481
2226
  const existing = await this.store.loadRequestState(requestId);
1482
2227
  if (existing) {
1483
2228
  if (existing.status === "pending") {
@@ -1504,13 +2249,14 @@ export class WalletController {
1504
2249
  requestId,
1505
2250
  origin,
1506
2251
  request,
2252
+ dappMetadata: normalizeConnectedDappMetadataEntry(options?.dappMetadata) ?? undefined,
1507
2253
  createdAt: this.now(),
1508
2254
  updatedAt: this.now(),
1509
2255
  status: "pending"
1510
2256
  };
1511
2257
  await this.store.saveRequestState(requestState);
1512
2258
  try {
1513
- const immediate = await this.executeImmediateRequest(await this.loadWalletState(), origin, request);
2259
+ const immediate = await this.executeImmediateRequest(await this.loadWalletState(), origin, request, requestState.dappMetadata);
1514
2260
  if (immediate.kind === "result") {
1515
2261
  const fulfilled = await this.fulfillRequest(requestState, immediate.value);
1516
2262
  if (fulfilled.status !== "fulfilled") {
@@ -1578,7 +2324,7 @@ export class WalletController {
1578
2324
  windowId
1579
2325
  });
1580
2326
  }
1581
- async resolveApproval(approvalId, approved) {
2327
+ async resolveApproval(approvalId, approved, options) {
1582
2328
  const approval = await this.store.loadApprovalState(approvalId);
1583
2329
  if (!approval) {
1584
2330
  throw new Error("approval request not found");
@@ -1594,8 +2340,14 @@ export class WalletController {
1594
2340
  return null;
1595
2341
  }
1596
2342
  try {
1597
- const result = await this.executeApprovedRequest(approval.record.origin, approval.record.request);
2343
+ const result = await this.executeApprovedRequest(approval.record.origin, approval.record.request, requestState.dappMetadata);
1598
2344
  await this.fulfillRequest(requestState, result);
2345
+ if (options?.trust) {
2346
+ const policy = await this.createTrustedDappPolicyForApproval(approval);
2347
+ if (policy) {
2348
+ await this.upsertTrustedDappPolicy(policy);
2349
+ }
2350
+ }
1599
2351
  return null;
1600
2352
  }
1601
2353
  catch (error) {