@xian-tech/wallet-core 0.3.2 → 0.3.5

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
1
  import { Ed25519Signer, shieldedSyncHintFromViewingPrivateKey, XianClient } from "@xian-tech/client";
2
- import { ProviderChainMismatchError, ProviderUnauthorizedError, ProviderUnsupportedMethodError } from "@xian-tech/provider";
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
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,28 @@ 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
+ }
39
64
  function trimNullableString(value) {
40
65
  if (typeof value !== "string") {
41
66
  return null;
@@ -43,6 +68,181 @@ function trimNullableString(value) {
43
68
  const trimmed = value.trim();
44
69
  return trimmed.length > 0 ? trimmed : null;
45
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
+ }
46
246
  function normalizeTrackedAsset(asset) {
47
247
  return {
48
248
  contract: asset.contract.trim(),
@@ -81,6 +281,9 @@ function normalizePresetInputValue(preset, fallback) {
81
281
  function normalizeStoredWalletNetworks(state) {
82
282
  const localPreset = createLocalNetworkPreset();
83
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);
84
287
  if (rawPresets.length === 0) {
85
288
  const rpcUrl = trimOptionalString(state.rpcUrl) ?? DEFAULT_RPC_URL;
86
289
  const dashboardUrl = trimOptionalString(state.dashboardUrl) ?? DEFAULT_DASHBOARD_URL;
@@ -92,7 +295,10 @@ function normalizeStoredWalletNetworks(state) {
92
295
  rpcUrl: localPreset.rpcUrl,
93
296
  dashboardUrl: localPreset.dashboardUrl,
94
297
  activeNetworkId: localPreset.id,
95
- networkPresets: [localPreset]
298
+ networkPresets: [localPreset],
299
+ assetNetworkStates,
300
+ trustedDappPolicies,
301
+ connectedDappMetadata
96
302
  };
97
303
  }
98
304
  const customPreset = normalizePresetInputValue({
@@ -111,7 +317,10 @@ function normalizeStoredWalletNetworks(state) {
111
317
  rpcUrl: customPreset.rpcUrl,
112
318
  dashboardUrl: customPreset.dashboardUrl,
113
319
  activeNetworkId: customPreset.id,
114
- networkPresets: [localPreset, customPreset]
320
+ networkPresets: [localPreset, customPreset],
321
+ assetNetworkStates,
322
+ trustedDappPolicies,
323
+ connectedDappMetadata
115
324
  };
116
325
  }
117
326
  const presets = new Map();
@@ -138,9 +347,62 @@ function normalizeStoredWalletNetworks(state) {
138
347
  rpcUrl: activePreset.rpcUrl,
139
348
  dashboardUrl: activePreset.dashboardUrl,
140
349
  activeNetworkId,
141
- 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
142
379
  };
143
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
+ }
144
406
  function parseShieldedWalletSnapshot(stateSnapshot) {
145
407
  let decoded;
146
408
  try {
@@ -213,6 +475,7 @@ export class WalletController {
213
475
  unlockedSigner = null;
214
476
  unlockedSessionKey = null;
215
477
  unlockedMnemonic = null;
478
+ unlockedSessionExpiresAt = null;
216
479
  constructor(options) {
217
480
  this.options = options;
218
481
  }
@@ -246,23 +509,24 @@ export class WalletController {
246
509
  };
247
510
  }
248
511
  async restoreUnlockedSession() {
249
- if (this.unlockedPrivateKey) {
250
- return true;
251
- }
252
512
  const session = await this.store.loadUnlockedSession();
253
513
  if (!session) {
514
+ this.unlockedPrivateKey = null;
515
+ this.unlockedSigner = null;
516
+ this.unlockedMnemonic = null;
517
+ this.unlockedSessionKey = null;
518
+ this.unlockedSessionExpiresAt = null;
254
519
  return false;
255
520
  }
256
521
  if (session.expiresAt <= this.now()) {
257
- await this.store.clearUnlockedSession();
522
+ await this.expireUnlockedSession();
258
523
  return false;
259
524
  }
260
525
  this.unlockedPrivateKey = session.privateKey;
261
526
  this.unlockedSigner = new Ed25519Signer(session.privateKey);
262
- if (session.mnemonic) {
263
- this.unlockedMnemonic = session.mnemonic;
264
- }
527
+ this.unlockedMnemonic = session.mnemonic ?? null;
265
528
  this.unlockedSessionKey = session.sessionKey;
529
+ this.unlockedSessionExpiresAt = session.expiresAt;
266
530
  return true;
267
531
  }
268
532
  async resolveUnlockedSessionExpiry() {
@@ -287,14 +551,24 @@ export class WalletController {
287
551
  expiresAt: nextExpiresAt
288
552
  };
289
553
  await this.store.saveUnlockedSession(session);
554
+ this.unlockedSessionExpiresAt = nextExpiresAt;
290
555
  }
291
556
  async clearUnlockedSession() {
292
557
  this.unlockedPrivateKey = null;
293
558
  this.unlockedSigner = null;
294
559
  this.unlockedMnemonic = null;
295
560
  this.unlockedSessionKey = null;
561
+ this.unlockedSessionExpiresAt = null;
296
562
  await this.store.clearUnlockedSession();
297
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
+ }
298
572
  async getUnlockedSigner() {
299
573
  await this.restoreUnlockedSession();
300
574
  if (!this.unlockedPrivateKey) {
@@ -548,22 +822,102 @@ export class WalletController {
548
822
  await this.store.saveState(normalizeStoredWalletNetworks(state));
549
823
  return this.getPopupState();
550
824
  }
551
- async updateConnectedOrigin(origin, connected) {
825
+ async updateConnectedOrigin(origin, connected, dappMetadata) {
552
826
  const state = this.requireStoredWallet(await this.loadWalletState());
553
827
  const nextOrigins = new Set(state.connectedOrigins);
828
+ const nextDappMetadata = {
829
+ ...(state.connectedDappMetadata ?? {})
830
+ };
554
831
  if (connected) {
555
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
+ }
556
840
  }
557
841
  else {
558
842
  nextOrigins.delete(origin);
843
+ delete nextDappMetadata[origin];
559
844
  }
560
845
  const nextState = {
561
846
  ...state,
562
- connectedOrigins: [...nextOrigins]
847
+ connectedOrigins: [...nextOrigins],
848
+ connectedDappMetadata: nextDappMetadata,
849
+ trustedDappPolicies: connected
850
+ ? state.trustedDappPolicies ?? []
851
+ : (state.trustedDappPolicies ?? []).filter((policy) => policy.origin !== origin)
563
852
  };
564
853
  await this.store.saveState(nextState);
565
854
  return nextState;
566
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
+ }
567
921
  async updateWatchedAssets(updater) {
568
922
  const state = this.requireStoredWallet(await this.loadWalletState());
569
923
  await this.store.saveState({
@@ -594,9 +948,9 @@ export class WalletController {
594
948
  seenContracts.add(contract);
595
949
  detectedAssets.push({
596
950
  contract,
597
- name: trimOptionalString(item.name ?? undefined),
598
- symbol: trimOptionalString(item.symbol ?? undefined),
599
- icon: trimOptionalString(item.logoUrl ?? undefined),
951
+ name: trimOptionalIndexedString(item.name),
952
+ symbol: trimOptionalIndexedString(item.symbol),
953
+ icon: trimOptionalIndexedString(item.logoUrl),
600
954
  balance: item.balance,
601
955
  tracked: trackedContracts.has(contract)
602
956
  });
@@ -747,13 +1101,13 @@ export class WalletController {
747
1101
  const signedTx = await this.signPreparedTransaction(state, tx);
748
1102
  return this.currentClient(state).broadcastTx(signedTx, options);
749
1103
  }
750
- async executeApprovedRequest(origin, request) {
1104
+ async executeApprovedRequest(origin, request, dappMetadata) {
751
1105
  const state = this.requireStoredWallet(await this.loadWalletState());
752
1106
  switch (request.method) {
753
1107
  case "xian_requestAccounts": {
754
1108
  await this.getUnlockedSigner();
755
1109
  const chainId = this.displayChainId(this.activeNetworkPreset(state), await this.safeGetChainId(state));
756
- const nextState = await this.updateConnectedOrigin(origin, true);
1110
+ const nextState = await this.updateConnectedOrigin(origin, true, dappMetadata);
757
1111
  await this.emitConnectionLifecycle(origin, chainId ?? "unknown", nextState.publicKey);
758
1112
  return [nextState.publicKey];
759
1113
  }
@@ -894,7 +1248,7 @@ export class WalletController {
894
1248
  return rejected;
895
1249
  }
896
1250
  }
897
- async executeImmediateRequest(state, origin, request) {
1251
+ async executeImmediateRequest(state, origin, request, dappMetadata) {
898
1252
  switch (request.method) {
899
1253
  case "xian_getWalletInfo":
900
1254
  return {
@@ -906,9 +1260,10 @@ export class WalletController {
906
1260
  await this.getUnlockedSigner();
907
1261
  const approvalChainId = this.displayChainId(this.activeNetworkPreset(walletState), await this.safeGetChainId(walletState));
908
1262
  if (walletState.connectedOrigins.includes(origin)) {
1263
+ const nextState = await this.updateConnectedOrigin(origin, true, dappMetadata);
909
1264
  return {
910
1265
  kind: "result",
911
- value: [walletState.publicKey]
1266
+ value: [nextState.publicKey]
912
1267
  };
913
1268
  }
914
1269
  return {
@@ -1011,10 +1366,15 @@ export class WalletController {
1011
1366
  const walletState = this.requireStoredWallet(state);
1012
1367
  this.requireConnectedOrigin(walletState, origin);
1013
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
+ }
1014
1374
  return {
1015
1375
  kind: "approval",
1016
1376
  account: walletState.publicKey,
1017
- chainId: this.displayChainId(this.activeNetworkPreset(walletState), await this.safeGetChainId(walletState))
1377
+ chainId: activeChainId
1018
1378
  };
1019
1379
  }
1020
1380
  default:
@@ -1044,6 +1404,9 @@ export class WalletController {
1044
1404
  return {
1045
1405
  hasWallet: state != null,
1046
1406
  unlocked,
1407
+ sessionExpiresAt: unlocked
1408
+ ? this.unlockedSessionExpiresAt ?? undefined
1409
+ : undefined,
1047
1410
  publicKey: state?.publicKey,
1048
1411
  rpcUrl: state?.rpcUrl ?? DEFAULT_RPC_URL,
1049
1412
  dashboardUrl: state?.dashboardUrl ?? DEFAULT_DASHBOARD_URL,
@@ -1059,10 +1422,13 @@ export class WalletController {
1059
1422
  activeNetworkName: activePreset?.name,
1060
1423
  networkPresets: state?.networkPresets ?? DEFAULT_NETWORK_PRESETS,
1061
1424
  watchedAssets,
1425
+ assetNetworkStates: state?.assetNetworkStates ?? {},
1062
1426
  detectedAssets: [],
1063
1427
  assetBalances: {},
1064
1428
  assetFiatValues: {},
1065
1429
  connectedOrigins: state?.connectedOrigins ?? [],
1430
+ trustedDappPolicies: state?.trustedDappPolicies ?? [],
1431
+ connectedDappMetadata: state?.connectedDappMetadata ?? {},
1066
1432
  pendingApprovalCount: pendingApprovals.length,
1067
1433
  pendingApprovals,
1068
1434
  hasRecoveryPhrase: Boolean(state?.encryptedMnemonic),
@@ -1077,11 +1443,17 @@ export class WalletController {
1077
1443
  };
1078
1444
  }
1079
1445
  async getAssetBalances() {
1446
+ return (await this.getAssetBalanceSnapshot()).balances;
1447
+ }
1448
+ async getAssetBalanceSnapshot() {
1080
1449
  const state = await this.loadWalletState();
1081
1450
  if (!state) {
1082
- return {};
1451
+ return {
1452
+ balances: {},
1453
+ assetNetworkStates: {}
1454
+ };
1083
1455
  }
1084
- return this.fetchAssetBalances(state, state.watchedAssets);
1456
+ return this.fetchAssetBalanceSnapshot(state, state.watchedAssets);
1085
1457
  }
1086
1458
  async getTokenMetadata(contract) {
1087
1459
  const state = this.requireStoredWallet(await this.loadWalletState());
@@ -1104,10 +1476,14 @@ export class WalletController {
1104
1476
  if (!normalized.contract) {
1105
1477
  throw new TypeError("asset contract is required");
1106
1478
  }
1479
+ const state = this.requireStoredWallet(await this.loadWalletState());
1480
+ let networkState = {
1481
+ status: "available",
1482
+ lastCheckedAt: new Date().toISOString()
1483
+ };
1107
1484
  // Auto-fetch metadata if any display metadata is missing.
1108
1485
  if (!normalized.name || !normalized.symbol || !normalized.icon) {
1109
1486
  try {
1110
- const state = this.requireStoredWallet(await this.loadWalletState());
1111
1487
  const meta = await this.resolveTokenMetadataForState(state, normalized.contract);
1112
1488
  if (meta.name && !normalized.name)
1113
1489
  normalized.name = meta.name;
@@ -1118,24 +1494,30 @@ export class WalletController {
1118
1494
  if (meta.logoSvg && !normalized.icon)
1119
1495
  normalized.icon = meta.logoSvg;
1120
1496
  }
1121
- catch {
1122
- // 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
+ };
1123
1503
  }
1124
1504
  }
1125
- await this.updateWatchedAssets((assets) => {
1126
- const next = assets.filter((entry) => entry.contract !== normalized.contract);
1127
- next.push(normalized);
1128
- return next;
1129
- });
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);
1130
1512
  return this.getPopupState();
1131
1513
  }
1132
1514
  async updateAssetSettings(assets) {
1133
- const state = this.requireStoredWallet(await this.loadWalletState());
1515
+ let state = this.requireStoredWallet(await this.loadWalletState());
1134
1516
  for (const update of assets) {
1135
1517
  const asset = state.watchedAssets.find((a) => a.contract === update.contract);
1136
1518
  if (asset) {
1137
1519
  if (update.hidden !== undefined) {
1138
- asset.hidden = update.hidden;
1520
+ state = updateAssetNetworkStateInWallet(state, state.activeNetworkId, update.contract, { hidden: update.hidden }).state;
1139
1521
  }
1140
1522
  if (update.order !== undefined) {
1141
1523
  asset.order = update.order;
@@ -1197,30 +1579,85 @@ export class WalletController {
1197
1579
  const state = this.requireStoredWallet(await this.loadWalletState());
1198
1580
  return this.currentClient(state).getContractMethods(contract);
1199
1581
  }
1200
- async fetchAssetBalances(state, assets) {
1582
+ async fetchAssetBalanceSnapshot(state, assets) {
1201
1583
  const balances = {};
1202
1584
  if (!state || assets.length === 0) {
1203
- return balances;
1585
+ return {
1586
+ balances,
1587
+ assetNetworkStates: state?.assetNetworkStates ?? {}
1588
+ };
1204
1589
  }
1205
1590
  const client = this.currentClient(state);
1591
+ let nextState = state;
1592
+ let changed = false;
1593
+ const checkedAt = new Date().toISOString();
1206
1594
  const results = await Promise.allSettled(assets.map(async (asset) => {
1207
1595
  const raw = await client.getBalance(state.publicKey, {
1208
1596
  contract: asset.contract
1209
1597
  });
1210
1598
  return { contract: asset.contract, raw };
1211
1599
  }));
1212
- for (const result of results) {
1600
+ for (const [index, result] of results.entries()) {
1213
1601
  if (result.status === "fulfilled") {
1214
1602
  const { contract, raw } = result.value;
1215
- balances[contract] =
1216
- 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;
1217
1618
  }
1218
1619
  else {
1219
- // If a single balance fetch fails, mark it null rather than
1220
- // 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 ?? {};
1221
1655
  }
1222
1656
  }
1223
- return balances;
1657
+ return {
1658
+ balances,
1659
+ assetNetworkStates
1660
+ };
1224
1661
  }
1225
1662
  async createOrImportWallet(input) {
1226
1663
  const secret = await createWalletSecret({
@@ -1291,6 +1728,15 @@ export class WalletController {
1291
1728
  symbol: "XIAN"
1292
1729
  }
1293
1730
  ],
1731
+ assetNetworkStates: {
1732
+ [activePreset.id]: {
1733
+ currency: {
1734
+ status: "available"
1735
+ }
1736
+ }
1737
+ },
1738
+ trustedDappPolicies: [],
1739
+ connectedDappMetadata: {},
1294
1740
  connectedOrigins: [],
1295
1741
  createdAt: new Date().toISOString()
1296
1742
  });
@@ -1343,7 +1789,8 @@ export class WalletController {
1343
1789
  activeAccountIndex: state.activeAccountIndex ?? accounts[0]?.index ?? 0,
1344
1790
  activeNetworkId: state.activeNetworkId,
1345
1791
  networkPresets: state.networkPresets.filter((p) => !p.builtin),
1346
- watchedAssets: state.watchedAssets
1792
+ watchedAssets: state.watchedAssets,
1793
+ assetNetworkStates: state.assetNetworkStates
1347
1794
  };
1348
1795
  if (state.encryptedMnemonic) {
1349
1796
  backup.mnemonic = await decryptMnemonicWithSessionKey(state.encryptedMnemonic, sessionKey);
@@ -1439,7 +1886,10 @@ export class WalletController {
1439
1886
  activeNetworkId: activePreset.id,
1440
1887
  networkPresets: presets,
1441
1888
  watchedAssets,
1889
+ assetNetworkStates: backup.assetNetworkStates,
1442
1890
  shieldedWalletSnapshots,
1891
+ trustedDappPolicies: [],
1892
+ connectedDappMetadata: {},
1443
1893
  connectedOrigins: [],
1444
1894
  createdAt: nowIso
1445
1895
  });
@@ -1686,12 +2136,29 @@ export class WalletController {
1686
2136
  }
1687
2137
  const nextState = {
1688
2138
  ...state,
1689
- connectedOrigins: []
2139
+ connectedOrigins: [],
2140
+ trustedDappPolicies: [],
2141
+ connectedDappMetadata: {}
1690
2142
  };
1691
2143
  await this.store.saveState(nextState);
1692
2144
  await Promise.all(state.connectedOrigins.map((origin) => this.emitDisconnectLifecycle(origin)));
1693
2145
  return this.getPopupState();
1694
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
+ }
1695
2162
  async removeWatchedAsset(contract) {
1696
2163
  const trimmed = contract.trim();
1697
2164
  if (trimmed.length === 0) {
@@ -1704,10 +2171,10 @@ export class WalletController {
1704
2171
  if (trimmed === "currency") {
1705
2172
  throw new Error("the native XIAN asset is pinned in the wallet");
1706
2173
  }
1707
- return this.persistWalletState({
2174
+ return this.persistWalletState(removeAssetNetworkStateFromWallet({
1708
2175
  ...state,
1709
2176
  watchedAssets: state.watchedAssets.filter((asset) => asset.contract !== trimmed)
1710
- });
2177
+ }, trimmed));
1711
2178
  }
1712
2179
  async saveNetworkPreset(input) {
1713
2180
  const state = this.requireStoredWallet(await this.loadWalletState());
@@ -1755,7 +2222,7 @@ export class WalletController {
1755
2222
  await this.emitChainChangedForConnectedOrigins(nextState, previousChainId);
1756
2223
  return this.getPopupState();
1757
2224
  }
1758
- async startProviderRequest(requestId, origin, request) {
2225
+ async startProviderRequest(requestId, origin, request, options) {
1759
2226
  const existing = await this.store.loadRequestState(requestId);
1760
2227
  if (existing) {
1761
2228
  if (existing.status === "pending") {
@@ -1782,13 +2249,14 @@ export class WalletController {
1782
2249
  requestId,
1783
2250
  origin,
1784
2251
  request,
2252
+ dappMetadata: normalizeConnectedDappMetadataEntry(options?.dappMetadata) ?? undefined,
1785
2253
  createdAt: this.now(),
1786
2254
  updatedAt: this.now(),
1787
2255
  status: "pending"
1788
2256
  };
1789
2257
  await this.store.saveRequestState(requestState);
1790
2258
  try {
1791
- const immediate = await this.executeImmediateRequest(await this.loadWalletState(), origin, request);
2259
+ const immediate = await this.executeImmediateRequest(await this.loadWalletState(), origin, request, requestState.dappMetadata);
1792
2260
  if (immediate.kind === "result") {
1793
2261
  const fulfilled = await this.fulfillRequest(requestState, immediate.value);
1794
2262
  if (fulfilled.status !== "fulfilled") {
@@ -1856,7 +2324,7 @@ export class WalletController {
1856
2324
  windowId
1857
2325
  });
1858
2326
  }
1859
- async resolveApproval(approvalId, approved) {
2327
+ async resolveApproval(approvalId, approved, options) {
1860
2328
  const approval = await this.store.loadApprovalState(approvalId);
1861
2329
  if (!approval) {
1862
2330
  throw new Error("approval request not found");
@@ -1872,8 +2340,14 @@ export class WalletController {
1872
2340
  return null;
1873
2341
  }
1874
2342
  try {
1875
- 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);
1876
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
+ }
1877
2351
  return null;
1878
2352
  }
1879
2353
  catch (error) {