@xian-tech/wallet-core 0.1.3 → 0.3.0

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,8 +1,9 @@
1
1
  import { Ed25519Signer, XianClient } from "@xian-tech/client";
2
2
  import { ProviderChainMismatchError, ProviderUnauthorizedError, ProviderUnsupportedMethodError } from "@xian-tech/provider";
3
- import { approvalKindFromMethod, buildApprovalView } from "./approvals";
4
- import { DEFAULT_NETWORK_PRESETS, DEFAULT_DASHBOARD_URL, DEFAULT_RPC_URL, LOCAL_NETWORK_PRESET_NAME, DEFAULT_WALLET_CAPABILITIES, LOCAL_NETWORK_PRESET_ID } from "./constants";
5
- import { createWalletSecret, decryptMnemonic, decryptPrivateKey, encryptMnemonic, encryptPrivateKey, isUnsafeMessageToSign } from "./crypto";
3
+ import { approvalKindFromMethod, buildApprovalView } from "./approvals.js";
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";
6
+ const SAFE_CHAIN_ID_LOOKUP_TIMEOUT_MS = 2_000;
6
7
  function firstParamObject(params) {
7
8
  if (Array.isArray(params)) {
8
9
  return (params[0] ?? {});
@@ -35,6 +36,15 @@ function trimOptionalString(value) {
35
36
  const trimmed = value?.trim();
36
37
  return trimmed ? trimmed : undefined;
37
38
  }
39
+ function normalizeTrackedAsset(asset) {
40
+ return {
41
+ contract: asset.contract.trim(),
42
+ name: trimOptionalString(asset.name),
43
+ symbol: trimOptionalString(asset.symbol),
44
+ icon: trimOptionalString(asset.icon),
45
+ decimals: asset.decimals
46
+ };
47
+ }
38
48
  function createLocalNetworkPreset() {
39
49
  const preset = DEFAULT_NETWORK_PRESETS[0];
40
50
  if (preset) {
@@ -136,6 +146,8 @@ export class WalletController {
136
146
  requestWaiters = new Map();
137
147
  unlockedPrivateKey = null;
138
148
  unlockedSigner = null;
149
+ unlockedSessionKey = null;
150
+ unlockedMnemonic = null;
139
151
  constructor(options) {
140
152
  this.options = options;
141
153
  }
@@ -168,13 +180,65 @@ export class WalletController {
168
180
  message: String(error)
169
181
  };
170
182
  }
171
- getUnlockedSigner() {
183
+ async restoreUnlockedSession() {
184
+ if (this.unlockedPrivateKey) {
185
+ return true;
186
+ }
187
+ const session = await this.store.loadUnlockedSession();
188
+ if (!session) {
189
+ return false;
190
+ }
191
+ if (session.expiresAt <= this.now()) {
192
+ await this.store.clearUnlockedSession();
193
+ return false;
194
+ }
195
+ this.unlockedPrivateKey = session.privateKey;
196
+ this.unlockedSigner = new Ed25519Signer(session.privateKey);
197
+ if (session.mnemonic) {
198
+ this.unlockedMnemonic = session.mnemonic;
199
+ }
200
+ this.unlockedSessionKey = session.sessionKey;
201
+ return true;
202
+ }
203
+ async resolveUnlockedSessionExpiry() {
204
+ const now = this.now();
205
+ const expiresAt = await this.options.getUnlockedSessionExpiry?.(now);
206
+ return typeof expiresAt === "number" && Number.isFinite(expiresAt)
207
+ ? expiresAt
208
+ : now + UNLOCKED_SESSION_TIMEOUT_MS;
209
+ }
210
+ async persistUnlockedSession(privateKey, expiresAt) {
211
+ const resolvedExpiresAt = expiresAt ?? (await this.resolveUnlockedSessionExpiry());
212
+ const currentSession = await this.store.loadUnlockedSession();
213
+ const nextExpiresAt = currentSession?.privateKey === privateKey &&
214
+ currentSession.sessionKey === this.unlockedSessionKey &&
215
+ currentSession.expiresAt > resolvedExpiresAt
216
+ ? currentSession.expiresAt
217
+ : resolvedExpiresAt;
218
+ const session = {
219
+ privateKey,
220
+ mnemonic: this.unlockedMnemonic ?? undefined,
221
+ sessionKey: this.unlockedSessionKey,
222
+ expiresAt: nextExpiresAt
223
+ };
224
+ await this.store.saveUnlockedSession(session);
225
+ }
226
+ async clearUnlockedSession() {
227
+ this.unlockedPrivateKey = null;
228
+ this.unlockedSigner = null;
229
+ this.unlockedMnemonic = null;
230
+ this.unlockedSessionKey = null;
231
+ await this.store.clearUnlockedSession();
232
+ }
233
+ async getUnlockedSigner() {
234
+ await this.restoreUnlockedSession();
172
235
  if (!this.unlockedPrivateKey) {
173
236
  throw new ProviderUnauthorizedError("wallet is locked");
174
237
  }
175
238
  if (!this.unlockedSigner) {
176
239
  this.unlockedSigner = new Ed25519Signer(this.unlockedPrivateKey);
177
240
  }
241
+ await this.persistUnlockedSession(this.unlockedPrivateKey);
178
242
  return this.unlockedSigner;
179
243
  }
180
244
  currentClient(state) {
@@ -192,6 +256,24 @@ export class WalletController {
192
256
  }
193
257
  return normalizeStoredWalletNetworks(state);
194
258
  }
259
+ requireAccounts(state) {
260
+ if (!state.accounts || state.accounts.length === 0) {
261
+ throw new Error("wallet state has no accounts");
262
+ }
263
+ return state.accounts;
264
+ }
265
+ async sessionKeyForState(state, password) {
266
+ return deriveWalletSessionKey(password, state.walletEncryptionSalt);
267
+ }
268
+ async decryptPrivateKeyForState(state, password) {
269
+ return decryptPrivateKeyWithSessionKey(state.encryptedPrivateKey, await this.sessionKeyForState(state, password));
270
+ }
271
+ async decryptMnemonicForState(state, password) {
272
+ if (!state.encryptedMnemonic) {
273
+ throw new Error("wallet does not have a recovery phrase");
274
+ }
275
+ return decryptMnemonicWithSessionKey(state.encryptedMnemonic, await this.sessionKeyForState(state, password));
276
+ }
195
277
  activeNetworkPreset(state) {
196
278
  const normalized = normalizeStoredWalletNetworks(state);
197
279
  return (normalized.networkPresets.find((preset) => preset.id === normalized.activeNetworkId) ??
@@ -255,12 +337,30 @@ export class WalletController {
255
337
  return undefined;
256
338
  }
257
339
  try {
258
- return await this.currentClient(state).getChainId();
340
+ return await this.withTimeout(this.currentClient(state).getChainId(), SAFE_CHAIN_ID_LOOKUP_TIMEOUT_MS);
259
341
  }
260
342
  catch {
261
343
  return undefined;
262
344
  }
263
345
  }
346
+ async withTimeout(promise, timeoutMs) {
347
+ let timeoutId;
348
+ try {
349
+ return await Promise.race([
350
+ promise,
351
+ new Promise((_, reject) => {
352
+ timeoutId = globalThis.setTimeout(() => {
353
+ reject(new Error("operation timed out"));
354
+ }, timeoutMs);
355
+ })
356
+ ]);
357
+ }
358
+ finally {
359
+ if (timeoutId !== undefined) {
360
+ globalThis.clearTimeout(timeoutId);
361
+ }
362
+ }
363
+ }
264
364
  async buildWalletInfo(state, origin) {
265
365
  if (!state) {
266
366
  return {
@@ -272,7 +372,7 @@ export class WalletController {
272
372
  };
273
373
  }
274
374
  const connected = state.connectedOrigins.includes(origin);
275
- const unlocked = this.unlockedPrivateKey != null;
375
+ const unlocked = await this.restoreUnlockedSession();
276
376
  const preset = this.activeNetworkPreset(state);
277
377
  const resolvedChainId = await this.safeGetChainId(state);
278
378
  return {
@@ -312,6 +412,50 @@ export class WalletController {
312
412
  watchedAssets: updater(state.watchedAssets)
313
413
  });
314
414
  }
415
+ async fetchDetectedAssets(state) {
416
+ if (!state) {
417
+ return [];
418
+ }
419
+ const client = this.currentClient(state);
420
+ const trackedContracts = new Set(state.watchedAssets.map((asset) => asset.contract));
421
+ const detectedAssets = [];
422
+ const seenContracts = new Set();
423
+ const pageSize = 200;
424
+ let offset = 0;
425
+ while (true) {
426
+ const page = await client.getTokenBalances(state.publicKey, {
427
+ limit: pageSize,
428
+ offset
429
+ });
430
+ for (const item of page.items) {
431
+ const contract = item.contract.trim();
432
+ if (!contract || seenContracts.has(contract)) {
433
+ continue;
434
+ }
435
+ seenContracts.add(contract);
436
+ detectedAssets.push({
437
+ contract,
438
+ name: trimOptionalString(item.name ?? undefined),
439
+ symbol: trimOptionalString(item.symbol ?? undefined),
440
+ icon: trimOptionalString(item.logoUrl ?? undefined),
441
+ balance: item.balance,
442
+ tracked: trackedContracts.has(contract)
443
+ });
444
+ }
445
+ const fetched = page.items.length;
446
+ if (fetched === 0 || offset + fetched >= page.total) {
447
+ break;
448
+ }
449
+ offset += fetched;
450
+ }
451
+ detectedAssets.sort((left, right) => {
452
+ if (left.tracked !== right.tracked) {
453
+ return left.tracked ? 1 : -1;
454
+ }
455
+ return left.contract.localeCompare(right.contract);
456
+ });
457
+ return detectedAssets;
458
+ }
315
459
  sanitizeNetworkPresetInput(input) {
316
460
  const name = input.name.trim();
317
461
  const rpcUrl = input.rpcUrl.trim();
@@ -375,8 +519,45 @@ export class WalletController {
375
519
  await this.broadcastProviderEvent("accountsChanged", [[]], origin);
376
520
  await this.broadcastProviderEvent("disconnect", [{ code: 4100, message: "wallet disconnected" }], origin);
377
521
  }
522
+ async notifyUnlockedOrigins(state) {
523
+ if (state.connectedOrigins.length === 0) {
524
+ return;
525
+ }
526
+ const chainId = this.displayChainId(this.activeNetworkPreset(state), await this.safeGetChainId(state)) ?? "unknown";
527
+ await Promise.allSettled(state.connectedOrigins.map((origin) => this.emitConnectionLifecycle(origin, chainId, state.publicKey)));
528
+ }
529
+ async emitSelectedAccountChangedForConnectedOrigins(state) {
530
+ if (state.connectedOrigins.length === 0) {
531
+ return;
532
+ }
533
+ if (await this.restoreUnlockedSession()) {
534
+ await Promise.allSettled(state.connectedOrigins.map((origin) => this.broadcastProviderEvent("accountsChanged", [[state.publicKey]], origin)));
535
+ return;
536
+ }
537
+ await Promise.allSettled(state.connectedOrigins.map((origin) => this.emitDisconnectLifecycle(origin)));
538
+ }
539
+ async invalidatePendingRequests(reason) {
540
+ const requestStates = await this.store.listRequestStates();
541
+ const settledPendingRequestIds = new Set();
542
+ for (const requestState of requestStates) {
543
+ if (requestState.status !== "pending") {
544
+ continue;
545
+ }
546
+ settledPendingRequestIds.add(requestState.requestId);
547
+ await this.rejectRequest(requestState, reason);
548
+ }
549
+ for (const [requestId, waiter] of this.requestWaiters.entries()) {
550
+ if (!settledPendingRequestIds.has(requestId)) {
551
+ waiter.reject(reason);
552
+ }
553
+ }
554
+ this.requestWaiters.clear();
555
+ for (const approval of await this.store.listApprovalStates()) {
556
+ await this.store.deleteApprovalState(approval.id);
557
+ }
558
+ }
378
559
  async prepareTransaction(state, intent) {
379
- const signer = this.getUnlockedSigner();
560
+ const signer = await this.getUnlockedSigner();
380
561
  const client = this.currentClient(state);
381
562
  const activeChainId = await client.getChainId();
382
563
  if (intent.chainId && intent.chainId !== activeChainId) {
@@ -393,7 +574,7 @@ export class WalletController {
393
574
  });
394
575
  }
395
576
  async signPreparedTransaction(state, tx) {
396
- const signer = this.getUnlockedSigner();
577
+ const signer = await this.getUnlockedSigner();
397
578
  const activeChainId = await this.currentClient(state).getChainId();
398
579
  if (tx.payload.sender !== signer.address) {
399
580
  throw new ProviderUnauthorizedError("transaction sender does not match the active wallet");
@@ -411,7 +592,7 @@ export class WalletController {
411
592
  const state = this.requireStoredWallet(await this.loadWalletState());
412
593
  switch (request.method) {
413
594
  case "xian_requestAccounts": {
414
- this.getUnlockedSigner();
595
+ await this.getUnlockedSigner();
415
596
  const chainId = this.displayChainId(this.activeNetworkPreset(state), await this.safeGetChainId(state));
416
597
  const nextState = await this.updateConnectedOrigin(origin, true);
417
598
  await this.emitConnectionLifecycle(origin, chainId ?? "unknown", nextState.publicKey);
@@ -419,9 +600,9 @@ export class WalletController {
419
600
  }
420
601
  case "xian_watchAsset": {
421
602
  this.requireConnectedOrigin(state, origin);
422
- this.getUnlockedSigner();
603
+ await this.getUnlockedSigner();
423
604
  const assetRequest = firstParamObject(request.params);
424
- const asset = assetRequest.options;
605
+ const asset = normalizeTrackedAsset(assetRequest.options);
425
606
  await this.updateWatchedAssets((assets) => {
426
607
  const next = assets.filter((entry) => entry.contract !== asset.contract);
427
608
  next.push(asset);
@@ -431,7 +612,7 @@ export class WalletController {
431
612
  }
432
613
  case "xian_signMessage": {
433
614
  this.requireConnectedOrigin(state, origin);
434
- const signer = this.getUnlockedSigner();
615
+ const signer = await this.getUnlockedSigner();
435
616
  const { message } = firstParamObject(request.params);
436
617
  if (typeof message !== "string") {
437
618
  throw new TypeError("xian_signMessage requires a message string");
@@ -443,13 +624,13 @@ export class WalletController {
443
624
  }
444
625
  case "xian_signTransaction": {
445
626
  this.requireConnectedOrigin(state, origin);
446
- this.getUnlockedSigner();
627
+ await this.getUnlockedSigner();
447
628
  const { tx } = firstParamObject(request.params);
448
629
  return this.signPreparedTransaction(state, tx);
449
630
  }
450
631
  case "xian_sendTransaction": {
451
632
  this.requireConnectedOrigin(state, origin);
452
- this.getUnlockedSigner();
633
+ await this.getUnlockedSigner();
453
634
  const { tx, mode, waitForTx, timeoutMs, pollIntervalMs } = firstParamObject(request.params);
454
635
  return this.sendPreparedTransaction(state, tx, {
455
636
  mode: mode,
@@ -460,7 +641,7 @@ export class WalletController {
460
641
  }
461
642
  case "xian_sendCall": {
462
643
  this.requireConnectedOrigin(state, origin);
463
- this.getUnlockedSigner();
644
+ await this.getUnlockedSigner();
464
645
  const { intent, mode, waitForTx, timeoutMs, pollIntervalMs } = firstParamObject(request.params);
465
646
  const tx = await this.prepareTransaction(state, intent);
466
647
  return this.sendPreparedTransaction(state, tx, {
@@ -563,7 +744,7 @@ export class WalletController {
563
744
  };
564
745
  case "xian_requestAccounts": {
565
746
  const walletState = this.requireStoredWallet(state);
566
- this.getUnlockedSigner();
747
+ await this.getUnlockedSigner();
567
748
  const approvalChainId = this.displayChainId(this.activeNetworkPreset(walletState), await this.safeGetChainId(walletState));
568
749
  if (walletState.connectedOrigins.includes(origin)) {
569
750
  return {
@@ -592,9 +773,7 @@ export class WalletController {
592
773
  };
593
774
  }
594
775
  case "xian_accounts":
595
- if (!state ||
596
- this.unlockedPrivateKey == null ||
597
- !state.connectedOrigins.includes(origin)) {
776
+ if (!state || !(await this.restoreUnlockedSession()) || !state.connectedOrigins.includes(origin)) {
598
777
  return {
599
778
  kind: "result",
600
779
  value: []
@@ -640,7 +819,7 @@ export class WalletController {
640
819
  case "xian_watchAsset": {
641
820
  const walletState = this.requireStoredWallet(state);
642
821
  this.requireConnectedOrigin(walletState, origin);
643
- this.getUnlockedSigner();
822
+ await this.getUnlockedSigner();
644
823
  return {
645
824
  kind: "approval",
646
825
  account: walletState.publicKey,
@@ -650,7 +829,7 @@ export class WalletController {
650
829
  case "xian_signMessage": {
651
830
  const walletState = this.requireStoredWallet(state);
652
831
  this.requireConnectedOrigin(walletState, origin);
653
- this.getUnlockedSigner();
832
+ await this.getUnlockedSigner();
654
833
  return {
655
834
  kind: "approval",
656
835
  account: walletState.publicKey,
@@ -660,7 +839,7 @@ export class WalletController {
660
839
  case "xian_prepareTransaction": {
661
840
  const walletState = this.requireStoredWallet(state);
662
841
  this.requireConnectedOrigin(walletState, origin);
663
- this.getUnlockedSigner();
842
+ await this.getUnlockedSigner();
664
843
  const { intent } = firstParamObject(request.params);
665
844
  return {
666
845
  kind: "result",
@@ -672,7 +851,7 @@ export class WalletController {
672
851
  case "xian_sendCall": {
673
852
  const walletState = this.requireStoredWallet(state);
674
853
  this.requireConnectedOrigin(walletState, origin);
675
- this.getUnlockedSigner();
854
+ await this.getUnlockedSigner();
676
855
  return {
677
856
  kind: "approval",
678
857
  account: walletState.publicKey,
@@ -683,6 +862,13 @@ export class WalletController {
683
862
  throw new ProviderUnsupportedMethodError(request.method);
684
863
  }
685
864
  }
865
+ getAccountsList(state) {
866
+ return this.requireAccounts(state).map((account) => ({
867
+ index: account.index,
868
+ publicKey: account.publicKey,
869
+ name: account.name
870
+ }));
871
+ }
686
872
  async getPopupState() {
687
873
  const state = await this.loadWalletState();
688
874
  const approvals = await this.store.listApprovalStates();
@@ -691,9 +877,11 @@ export class WalletController {
691
877
  .sort((left, right) => right.createdAt - left.createdAt);
692
878
  const activePreset = state ? this.activeNetworkPreset(state) : undefined;
693
879
  const resolvedChainId = await this.safeGetChainId(state);
880
+ const unlocked = await this.restoreUnlockedSession();
881
+ const watchedAssets = state?.watchedAssets ?? [];
694
882
  return {
695
883
  hasWallet: state != null,
696
- unlocked: this.unlockedPrivateKey != null,
884
+ unlocked,
697
885
  publicKey: state?.publicKey,
698
886
  rpcUrl: state?.rpcUrl ?? DEFAULT_RPC_URL,
699
887
  dashboardUrl: state?.dashboardUrl ?? DEFAULT_DASHBOARD_URL,
@@ -708,16 +896,149 @@ export class WalletController {
708
896
  activeNetworkId: activePreset?.id,
709
897
  activeNetworkName: activePreset?.name,
710
898
  networkPresets: state?.networkPresets ?? DEFAULT_NETWORK_PRESETS,
711
- watchedAssets: state?.watchedAssets ?? [],
899
+ watchedAssets,
900
+ detectedAssets: [],
901
+ assetBalances: {},
902
+ assetFiatValues: {},
712
903
  connectedOrigins: state?.connectedOrigins ?? [],
713
904
  pendingApprovalCount: pendingApprovals.length,
714
905
  pendingApprovals,
715
906
  hasRecoveryPhrase: Boolean(state?.encryptedMnemonic),
716
907
  seedSource: state?.seedSource,
717
908
  mnemonicWordCount: state?.mnemonicWordCount,
909
+ accounts: state ? this.getAccountsList(state) : [],
910
+ activeAccountIndex: state?.activeAccountIndex ?? 0,
718
911
  version: this.options.version
719
912
  };
720
913
  }
914
+ async getAssetBalances() {
915
+ const state = await this.loadWalletState();
916
+ if (!state) {
917
+ return {};
918
+ }
919
+ return this.fetchAssetBalances(state, state.watchedAssets);
920
+ }
921
+ async getTokenMetadata(contract) {
922
+ const state = this.requireStoredWallet(await this.loadWalletState());
923
+ return this.currentClient(state).getTokenMetadata(contract);
924
+ }
925
+ async getDetectedAssets() {
926
+ const state = await this.loadWalletState();
927
+ if (!state) {
928
+ return [];
929
+ }
930
+ try {
931
+ return await this.fetchDetectedAssets(state);
932
+ }
933
+ catch {
934
+ return [];
935
+ }
936
+ }
937
+ async trackAsset(asset) {
938
+ const normalized = normalizeTrackedAsset(asset);
939
+ if (!normalized.contract) {
940
+ throw new TypeError("asset contract is required");
941
+ }
942
+ // Auto-fetch metadata if name/symbol not provided
943
+ if (!normalized.name || !normalized.symbol) {
944
+ try {
945
+ const state = this.requireStoredWallet(await this.loadWalletState());
946
+ const meta = await this.currentClient(state).getTokenMetadata(normalized.contract);
947
+ if (meta.name && !normalized.name)
948
+ normalized.name = meta.name;
949
+ if (meta.symbol && !normalized.symbol)
950
+ normalized.symbol = meta.symbol;
951
+ if (meta.logoUrl && !normalized.icon)
952
+ normalized.icon = meta.logoUrl;
953
+ }
954
+ catch {
955
+ // Metadata fetch failed — use contract name as fallback
956
+ }
957
+ }
958
+ await this.updateWatchedAssets((assets) => {
959
+ const next = assets.filter((entry) => entry.contract !== normalized.contract);
960
+ next.push(normalized);
961
+ return next;
962
+ });
963
+ return this.getPopupState();
964
+ }
965
+ async updateAssetSettings(assets) {
966
+ const state = this.requireStoredWallet(await this.loadWalletState());
967
+ for (const update of assets) {
968
+ const asset = state.watchedAssets.find((a) => a.contract === update.contract);
969
+ if (asset) {
970
+ if (update.hidden !== undefined) {
971
+ asset.hidden = update.hidden;
972
+ }
973
+ if (update.order !== undefined) {
974
+ asset.order = update.order;
975
+ }
976
+ }
977
+ }
978
+ await this.store.saveState(state);
979
+ return this.getPopupState();
980
+ }
981
+ async updateWatchedAssetDecimals(contract, decimals) {
982
+ const state = this.requireStoredWallet(await this.loadWalletState());
983
+ const idx = state.watchedAssets.findIndex((asset) => asset.contract === contract);
984
+ if (idx === -1) {
985
+ throw new Error(`asset ${contract} is not watched`);
986
+ }
987
+ const existing = state.watchedAssets[idx];
988
+ state.watchedAssets[idx] = { ...existing, decimals };
989
+ await this.store.saveState(state);
990
+ return this.getPopupState();
991
+ }
992
+ async estimateTransactionStamps(request) {
993
+ const state = this.requireStoredWallet(await this.loadWalletState());
994
+ const client = this.currentClient(state);
995
+ return client.estimateStamps({
996
+ sender: state.publicKey,
997
+ contract: request.contract,
998
+ function: request.function,
999
+ kwargs: request.kwargs
1000
+ });
1001
+ }
1002
+ async sendDirectTransaction(intent) {
1003
+ const state = this.requireStoredWallet(await this.loadWalletState());
1004
+ await this.getUnlockedSigner();
1005
+ const tx = await this.prepareTransaction(state, {
1006
+ contract: intent.contract,
1007
+ function: intent.function,
1008
+ kwargs: intent.kwargs,
1009
+ stamps: intent.stamps
1010
+ });
1011
+ return this.sendPreparedTransaction(state, tx, { mode: "commit" });
1012
+ }
1013
+ async getContractMethods(contract) {
1014
+ const state = this.requireStoredWallet(await this.loadWalletState());
1015
+ return this.currentClient(state).getContractMethods(contract);
1016
+ }
1017
+ async fetchAssetBalances(state, assets) {
1018
+ const balances = {};
1019
+ if (!state || assets.length === 0) {
1020
+ return balances;
1021
+ }
1022
+ const client = this.currentClient(state);
1023
+ const results = await Promise.allSettled(assets.map(async (asset) => {
1024
+ const raw = await client.getBalance(state.publicKey, {
1025
+ contract: asset.contract
1026
+ });
1027
+ return { contract: asset.contract, raw };
1028
+ }));
1029
+ for (const result of results) {
1030
+ if (result.status === "fulfilled") {
1031
+ const { contract, raw } = result.value;
1032
+ balances[contract] =
1033
+ raw != null ? String(raw) : null;
1034
+ }
1035
+ else {
1036
+ // If a single balance fetch fails, mark it null rather than
1037
+ // failing the entire popup state.
1038
+ }
1039
+ }
1040
+ return balances;
1041
+ }
721
1042
  async createOrImportWallet(input) {
722
1043
  const secret = await createWalletSecret({
723
1044
  privateKey: input.privateKey,
@@ -725,23 +1046,17 @@ export class WalletController {
725
1046
  createWithMnemonic: input.createWithMnemonic
726
1047
  });
727
1048
  const signer = new Ed25519Signer(secret.privateKey);
728
- const encryptedPrivateKey = await encryptPrivateKey(secret.privateKey, input.password);
1049
+ const { walletEncryptionSalt, sessionKey } = await createWalletSessionKey(input.password);
1050
+ const encryptedPrivateKey = await encryptPrivateKeyWithSessionKey(secret.privateKey, sessionKey);
729
1051
  const encryptedMnemonic = secret.mnemonic
730
- ? await encryptMnemonic(secret.mnemonic, input.password)
1052
+ ? await encryptMnemonicWithSessionKey(secret.mnemonic, sessionKey)
731
1053
  : undefined;
732
1054
  this.unlockedPrivateKey = secret.privateKey;
733
1055
  this.unlockedSigner = signer;
734
- const waiters = [...this.requestWaiters.values()];
735
- this.requestWaiters.clear();
736
- for (const waiter of waiters) {
737
- waiter.reject(new ProviderUnauthorizedError("wallet was replaced"));
738
- }
739
- for (const requestState of await this.store.listRequestStates()) {
740
- await this.store.deleteRequestState(requestState.requestId);
741
- }
742
- for (const approval of await this.store.listApprovalStates()) {
743
- await this.store.deleteApprovalState(approval.id);
744
- }
1056
+ this.unlockedMnemonic = secret.mnemonic ?? null;
1057
+ this.unlockedSessionKey = sessionKey;
1058
+ await this.persistUnlockedSession(secret.privateKey);
1059
+ await this.invalidatePendingRequests(new ProviderUnauthorizedError("wallet was replaced"));
745
1060
  const setupRpcUrl = trimOptionalString(input.rpcUrl) ?? DEFAULT_RPC_URL;
746
1061
  const setupDashboardUrl = trimOptionalString(input.dashboardUrl) ?? DEFAULT_DASHBOARD_URL;
747
1062
  const localPreset = createLocalNetworkPreset();
@@ -767,12 +1082,21 @@ export class WalletController {
767
1082
  const networkPresets = useLocalPreset
768
1083
  ? [localPreset]
769
1084
  : [localPreset, activePreset];
1085
+ const initialAccount = {
1086
+ index: 0,
1087
+ publicKey: signer.address,
1088
+ encryptedPrivateKey,
1089
+ name: "Account 1"
1090
+ };
770
1091
  const popupState = await this.persistWalletState({
771
1092
  publicKey: signer.address,
772
1093
  encryptedPrivateKey,
773
1094
  encryptedMnemonic,
1095
+ walletEncryptionSalt,
774
1096
  seedSource: secret.seedSource,
775
1097
  mnemonicWordCount: secret.mnemonicWordCount,
1098
+ accounts: [initialAccount],
1099
+ activeAccountIndex: 0,
776
1100
  rpcUrl: activePreset.rpcUrl,
777
1101
  dashboardUrl: activePreset.dashboardUrl,
778
1102
  activeNetworkId: activePreset.id,
@@ -795,31 +1119,260 @@ export class WalletController {
795
1119
  }
796
1120
  async unlockWallet(password) {
797
1121
  const state = this.requireStoredWallet(await this.loadWalletState());
798
- const privateKey = await decryptPrivateKey(state.encryptedPrivateKey, password);
1122
+ const sessionKey = await this.sessionKeyForState(state, password);
1123
+ const privateKey = await decryptPrivateKeyWithSessionKey(state.encryptedPrivateKey, sessionKey);
799
1124
  const signer = new Ed25519Signer(privateKey);
800
1125
  if (signer.address !== state.publicKey) {
801
1126
  throw new Error("decrypted private key does not match stored wallet");
802
1127
  }
803
1128
  this.unlockedPrivateKey = privateKey;
804
1129
  this.unlockedSigner = signer;
805
- const chainId = this.displayChainId(this.activeNetworkPreset(state), await this.safeGetChainId(state));
806
- await Promise.all(state.connectedOrigins.map((origin) => this.emitConnectionLifecycle(origin, chainId ?? "unknown", state.publicKey)));
1130
+ this.unlockedSessionKey = sessionKey;
1131
+ // Decrypt mnemonic into session for account switching
1132
+ if (state.encryptedMnemonic) {
1133
+ try {
1134
+ this.unlockedMnemonic = await decryptMnemonicWithSessionKey(state.encryptedMnemonic, sessionKey);
1135
+ }
1136
+ catch {
1137
+ this.unlockedMnemonic = null;
1138
+ }
1139
+ }
1140
+ await this.persistUnlockedSession(privateKey);
1141
+ void this.notifyUnlockedOrigins(state);
807
1142
  return this.getPopupState();
808
1143
  }
809
1144
  async revealMnemonic(password) {
810
1145
  const state = this.requireStoredWallet(await this.loadWalletState());
811
- if (!state.encryptedMnemonic) {
812
- throw new Error("wallet does not have a recovery phrase");
1146
+ return this.decryptMnemonicForState(state, password);
1147
+ }
1148
+ async revealPrivateKey(password) {
1149
+ const state = this.requireStoredWallet(await this.loadWalletState());
1150
+ return this.decryptPrivateKeyForState(state, password);
1151
+ }
1152
+ async exportWallet(password) {
1153
+ const state = this.requireStoredWallet(await this.loadWalletState());
1154
+ const accounts = this.requireAccounts(state);
1155
+ const backup = {
1156
+ version: 1,
1157
+ type: state.seedSource,
1158
+ accounts: accounts.map((a) => ({ index: a.index, name: a.name })),
1159
+ activeAccountIndex: state.activeAccountIndex ?? accounts[0]?.index ?? 0,
1160
+ activeNetworkId: state.activeNetworkId,
1161
+ networkPresets: state.networkPresets.filter((p) => !p.builtin),
1162
+ watchedAssets: state.watchedAssets
1163
+ };
1164
+ if (state.encryptedMnemonic) {
1165
+ backup.mnemonic = await this.decryptMnemonicForState(state, password);
1166
+ }
1167
+ else {
1168
+ backup.privateKey = await this.decryptPrivateKeyForState(state, password);
1169
+ }
1170
+ return backup;
1171
+ }
1172
+ async importWalletBackup(backup, password) {
1173
+ // Derive or use the provided private key
1174
+ let primaryKey;
1175
+ let mnemonic;
1176
+ if (backup.type === "mnemonic" && backup.mnemonic) {
1177
+ mnemonic = backup.mnemonic;
1178
+ primaryKey = await derivePrivateKeyFromMnemonic(mnemonic, 0);
1179
+ }
1180
+ else if (backup.privateKey) {
1181
+ primaryKey = backup.privateKey;
1182
+ }
1183
+ else {
1184
+ throw new Error("backup must contain a mnemonic or private key");
1185
+ }
1186
+ const { walletEncryptionSalt, sessionKey } = await createWalletSessionKey(password);
1187
+ const encryptedMnemonic = mnemonic
1188
+ ? await encryptMnemonicWithSessionKey(mnemonic, sessionKey)
1189
+ : undefined;
1190
+ // Build accounts list
1191
+ const accountEntries = backup.accounts;
1192
+ if (!accountEntries || accountEntries.length === 0) {
1193
+ throw new Error("backup must contain at least one account");
1194
+ }
1195
+ const accounts = [];
1196
+ const privateKeysByIndex = new Map();
1197
+ for (const entry of accountEntries) {
1198
+ const key = mnemonic
1199
+ ? await derivePrivateKeyFromMnemonic(mnemonic, entry.index)
1200
+ : primaryKey;
1201
+ privateKeysByIndex.set(entry.index, key);
1202
+ const acctSigner = new Ed25519Signer(key);
1203
+ accounts.push({
1204
+ index: entry.index,
1205
+ publicKey: acctSigner.address,
1206
+ encryptedPrivateKey: await encryptPrivateKeyWithSessionKey(key, sessionKey),
1207
+ name: entry.name
1208
+ });
1209
+ }
1210
+ const activeAccount = accounts.find((account) => account.index === backup.activeAccountIndex) ??
1211
+ accounts[0];
1212
+ if (!activeAccount) {
1213
+ throw new Error("backup must contain at least one account");
1214
+ }
1215
+ const activePrivateKey = privateKeysByIndex.get(activeAccount.index) ?? primaryKey;
1216
+ const signer = new Ed25519Signer(activePrivateKey);
1217
+ this.unlockedPrivateKey = activePrivateKey;
1218
+ this.unlockedSigner = signer;
1219
+ this.unlockedMnemonic = mnemonic ?? null;
1220
+ this.unlockedSessionKey = sessionKey;
1221
+ await this.persistUnlockedSession(activePrivateKey);
1222
+ await this.invalidatePendingRequests(new ProviderUnauthorizedError("wallet was replaced"));
1223
+ // Merge network presets
1224
+ const presets = [...DEFAULT_NETWORK_PRESETS];
1225
+ for (const p of backup.networkPresets ?? []) {
1226
+ if (!presets.some((existing) => existing.id === p.id)) {
1227
+ presets.push(p);
1228
+ }
1229
+ }
1230
+ const activePreset = presets.find((preset) => preset.id === backup.activeNetworkId) ??
1231
+ presets[0];
1232
+ if (!activePreset) {
1233
+ throw new Error("backup must contain at least one network preset");
1234
+ }
1235
+ const watchedAssets = backup.watchedAssets?.length
1236
+ ? backup.watchedAssets
1237
+ : [{ contract: "currency", name: "Xian", symbol: "XIAN" }];
1238
+ await this.persistWalletState({
1239
+ publicKey: activeAccount.publicKey,
1240
+ encryptedPrivateKey: activeAccount.encryptedPrivateKey,
1241
+ encryptedMnemonic,
1242
+ walletEncryptionSalt,
1243
+ seedSource: backup.type,
1244
+ mnemonicWordCount: mnemonic ? mnemonic.split(" ").length : undefined,
1245
+ accounts,
1246
+ activeAccountIndex: activeAccount.index,
1247
+ rpcUrl: activePreset.rpcUrl,
1248
+ dashboardUrl: activePreset.dashboardUrl,
1249
+ activeNetworkId: activePreset.id,
1250
+ networkPresets: presets,
1251
+ watchedAssets,
1252
+ connectedOrigins: [],
1253
+ createdAt: new Date().toISOString()
1254
+ });
1255
+ return this.getPopupState();
1256
+ }
1257
+ async addAccount() {
1258
+ await this.restoreUnlockedSession();
1259
+ if (!this.unlockedMnemonic || !this.unlockedSessionKey) {
1260
+ throw new Error("wallet must be unlocked to add an account");
1261
+ }
1262
+ const state = this.requireStoredWallet(await this.loadWalletState());
1263
+ const accounts = this.requireAccounts(state);
1264
+ const nextIndex = Math.max(...accounts.map((a) => a.index)) + 1;
1265
+ const privateKey = await derivePrivateKeyFromMnemonic(this.unlockedMnemonic, nextIndex);
1266
+ const signer = new Ed25519Signer(privateKey);
1267
+ const encrypted = await encryptPrivateKeyWithSessionKey(privateKey, this.unlockedSessionKey);
1268
+ accounts.push({
1269
+ index: nextIndex,
1270
+ publicKey: signer.address,
1271
+ encryptedPrivateKey: encrypted,
1272
+ name: `Account ${accounts.length + 1}`
1273
+ });
1274
+ state.publicKey = signer.address;
1275
+ state.encryptedPrivateKey = encrypted;
1276
+ state.activeAccountIndex = nextIndex;
1277
+ state.accounts = accounts;
1278
+ await this.store.saveState(state);
1279
+ this.unlockedPrivateKey = privateKey;
1280
+ this.unlockedSigner = signer;
1281
+ await this.persistUnlockedSession(privateKey);
1282
+ await this.emitSelectedAccountChangedForConnectedOrigins(state);
1283
+ return this.getPopupState();
1284
+ }
1285
+ async switchAccount(index) {
1286
+ const state = this.requireStoredWallet(await this.loadWalletState());
1287
+ const accounts = this.requireAccounts(state);
1288
+ const target = accounts.find((a) => a.index === index);
1289
+ if (!target) {
1290
+ throw new Error("account not found");
1291
+ }
1292
+ // Update active account in state
1293
+ state.publicKey = target.publicKey;
1294
+ state.encryptedPrivateKey = target.encryptedPrivateKey;
1295
+ state.activeAccountIndex = index;
1296
+ await this.store.saveState(state);
1297
+ // If unlocked, switch the in-memory signer
1298
+ if (this.unlockedMnemonic) {
1299
+ const privateKey = await derivePrivateKeyFromMnemonic(this.unlockedMnemonic, index);
1300
+ this.unlockedPrivateKey = privateKey;
1301
+ this.unlockedSigner = new Ed25519Signer(privateKey);
1302
+ await this.persistUnlockedSession(privateKey);
1303
+ }
1304
+ else if (this.unlockedPrivateKey) {
1305
+ // No mnemonic in session — clear unlock (requires re-auth)
1306
+ await this.clearUnlockedSession();
1307
+ }
1308
+ await this.emitSelectedAccountChangedForConnectedOrigins(state);
1309
+ return this.getPopupState();
1310
+ }
1311
+ async renameAccount(index, name) {
1312
+ const state = this.requireStoredWallet(await this.loadWalletState());
1313
+ const accounts = this.requireAccounts(state);
1314
+ const target = accounts.find((a) => a.index === index);
1315
+ if (!target) {
1316
+ throw new Error("account not found");
1317
+ }
1318
+ const duplicate = accounts.find((a) => a.index !== index && a.name.toLowerCase() === name.toLowerCase());
1319
+ if (duplicate) {
1320
+ throw new Error(`An account named "${name}" already exists`);
1321
+ }
1322
+ target.name = name;
1323
+ state.accounts = accounts;
1324
+ await this.store.saveState(state);
1325
+ return this.getPopupState();
1326
+ }
1327
+ async removeAccount(index) {
1328
+ const state = this.requireStoredWallet(await this.loadWalletState());
1329
+ if (index === 0) {
1330
+ throw new Error("cannot remove the primary account");
1331
+ }
1332
+ const accounts = this.requireAccounts(state);
1333
+ const nextAccounts = accounts.filter((account) => account.index !== index);
1334
+ if (nextAccounts.length === 0) {
1335
+ throw new Error("cannot remove the last remaining account");
1336
+ }
1337
+ const removedActiveAccount = state.activeAccountIndex === index;
1338
+ state.accounts = nextAccounts;
1339
+ if (removedActiveAccount) {
1340
+ const nextActiveAccount = nextAccounts[0];
1341
+ state.publicKey = nextActiveAccount.publicKey;
1342
+ state.encryptedPrivateKey = nextActiveAccount.encryptedPrivateKey;
1343
+ state.activeAccountIndex = nextActiveAccount.index;
1344
+ if (this.unlockedMnemonic) {
1345
+ const privateKey = await derivePrivateKeyFromMnemonic(this.unlockedMnemonic, nextActiveAccount.index);
1346
+ this.unlockedPrivateKey = privateKey;
1347
+ this.unlockedSigner = new Ed25519Signer(privateKey);
1348
+ await this.persistUnlockedSession(privateKey);
1349
+ }
1350
+ else if (this.unlockedPrivateKey) {
1351
+ await this.clearUnlockedSession();
1352
+ }
1353
+ }
1354
+ await this.store.saveState(state);
1355
+ if (removedActiveAccount) {
1356
+ await this.emitSelectedAccountChangedForConnectedOrigins(state);
813
1357
  }
814
- return decryptMnemonic(state.encryptedMnemonic, password);
1358
+ return this.getPopupState();
815
1359
  }
816
1360
  async lockWallet() {
817
1361
  const state = await this.loadWalletState();
818
- this.unlockedPrivateKey = null;
819
- this.unlockedSigner = null;
1362
+ await this.clearUnlockedSession();
1363
+ if (state) {
1364
+ await Promise.all(state.connectedOrigins.map((origin) => this.emitDisconnectLifecycle(origin)));
1365
+ }
1366
+ return this.getPopupState();
1367
+ }
1368
+ async removeWallet() {
1369
+ const state = await this.loadWalletState();
1370
+ await this.clearUnlockedSession();
820
1371
  if (state) {
821
1372
  await Promise.all(state.connectedOrigins.map((origin) => this.emitDisconnectLifecycle(origin)));
822
1373
  }
1374
+ await this.invalidatePendingRequests(new ProviderUnauthorizedError("wallet was removed"));
1375
+ await this.store.clearState();
823
1376
  return this.getPopupState();
824
1377
  }
825
1378
  async updateSettings(input) {