@xian-tech/wallet-core 0.1.4 → 0.3.2

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,8 @@
1
- import { Ed25519Signer, XianClient } from "@xian-tech/client";
1
+ import { Ed25519Signer, shieldedSyncHintFromViewingPrivateKey, XianClient } from "@xian-tech/client";
2
2
  import { 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 { createWalletSecret, decryptMnemonic, decryptPrivateKey, derivePrivateKeyFromMnemonic, encryptMnemonic, encryptPrivateKey, 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
7
  function firstParamObject(params) {
8
8
  if (Array.isArray(params)) {
@@ -36,6 +36,13 @@ function trimOptionalString(value) {
36
36
  const trimmed = value?.trim();
37
37
  return trimmed ? trimmed : undefined;
38
38
  }
39
+ function trimNullableString(value) {
40
+ if (typeof value !== "string") {
41
+ return null;
42
+ }
43
+ const trimmed = value.trim();
44
+ return trimmed.length > 0 ? trimmed : null;
45
+ }
39
46
  function normalizeTrackedAsset(asset) {
40
47
  return {
41
48
  contract: asset.contract.trim(),
@@ -134,6 +141,64 @@ function normalizeStoredWalletNetworks(state) {
134
141
  networkPresets: [...presets.values()]
135
142
  };
136
143
  }
144
+ function parseShieldedWalletSnapshot(stateSnapshot) {
145
+ let decoded;
146
+ try {
147
+ decoded = JSON.parse(stateSnapshot);
148
+ }
149
+ catch {
150
+ throw new Error("shielded wallet snapshot must be valid JSON");
151
+ }
152
+ if (typeof decoded !== "object" || decoded == null || Array.isArray(decoded)) {
153
+ throw new Error("shielded wallet snapshot must be a JSON object");
154
+ }
155
+ const record = decoded;
156
+ const assetId = typeof record.asset_id === "string" ? trimOptionalString(record.asset_id) : undefined;
157
+ if (!assetId) {
158
+ throw new Error("shielded wallet snapshot must contain asset_id");
159
+ }
160
+ if (typeof record.owner_secret !== "string" || record.owner_secret.length === 0) {
161
+ throw new Error("shielded wallet snapshot must contain owner_secret");
162
+ }
163
+ if (typeof record.viewing_private_key !== "string" ||
164
+ record.viewing_private_key.length === 0) {
165
+ throw new Error("shielded wallet snapshot must contain viewing_private_key");
166
+ }
167
+ const notes = record.notes ?? [];
168
+ if (!Array.isArray(notes)) {
169
+ throw new Error("shielded wallet snapshot notes must be an array");
170
+ }
171
+ const commitments = record.commitments ?? [];
172
+ if (!Array.isArray(commitments) || commitments.some((value) => typeof value !== "string")) {
173
+ throw new Error("shielded wallet snapshot commitments must be an array of strings");
174
+ }
175
+ const lastScannedValue = record.last_scanned_index;
176
+ const lastScannedIndex = typeof lastScannedValue === "number" &&
177
+ Number.isInteger(lastScannedValue) &&
178
+ lastScannedValue >= 0
179
+ ? lastScannedValue
180
+ : commitments.length;
181
+ return {
182
+ normalizedSnapshot: JSON.stringify(record),
183
+ assetId,
184
+ syncHint: shieldedSyncHintFromViewingPrivateKey(record.viewing_private_key),
185
+ noteCount: notes.length,
186
+ commitmentCount: commitments.length,
187
+ lastScannedIndex,
188
+ };
189
+ }
190
+ function shieldedWalletSnapshotSummary(record) {
191
+ return {
192
+ id: record.id,
193
+ label: record.label,
194
+ assetId: record.assetId,
195
+ syncHint: record.syncHint,
196
+ noteCount: record.noteCount,
197
+ commitmentCount: record.commitmentCount,
198
+ lastScannedIndex: record.lastScannedIndex,
199
+ updatedAt: record.updatedAt,
200
+ };
201
+ }
137
202
  function hydrateError(error) {
138
203
  const hydrated = new Error(error.message);
139
204
  hydrated.name = error.name ?? "Error";
@@ -146,6 +211,8 @@ export class WalletController {
146
211
  requestWaiters = new Map();
147
212
  unlockedPrivateKey = null;
148
213
  unlockedSigner = null;
214
+ unlockedSessionKey = null;
215
+ unlockedMnemonic = null;
149
216
  constructor(options) {
150
217
  this.options = options;
151
218
  }
@@ -195,19 +262,29 @@ export class WalletController {
195
262
  if (session.mnemonic) {
196
263
  this.unlockedMnemonic = session.mnemonic;
197
264
  }
198
- if (session.password) {
199
- this.unlockedPassword = session.password;
200
- }
265
+ this.unlockedSessionKey = session.sessionKey;
201
266
  return true;
202
267
  }
203
- unlockedMnemonic = null;
204
- unlockedPassword = null;
205
- async persistUnlockedSession(privateKey, expiresAt = this.now() + UNLOCKED_SESSION_TIMEOUT_MS) {
268
+ async resolveUnlockedSessionExpiry() {
269
+ const now = this.now();
270
+ const expiresAt = await this.options.getUnlockedSessionExpiry?.(now);
271
+ return typeof expiresAt === "number" && Number.isFinite(expiresAt)
272
+ ? expiresAt
273
+ : now + UNLOCKED_SESSION_TIMEOUT_MS;
274
+ }
275
+ async persistUnlockedSession(privateKey, expiresAt) {
276
+ const resolvedExpiresAt = expiresAt ?? (await this.resolveUnlockedSessionExpiry());
277
+ const currentSession = await this.store.loadUnlockedSession();
278
+ const nextExpiresAt = currentSession?.privateKey === privateKey &&
279
+ currentSession.sessionKey === this.unlockedSessionKey &&
280
+ currentSession.expiresAt > resolvedExpiresAt
281
+ ? currentSession.expiresAt
282
+ : resolvedExpiresAt;
206
283
  const session = {
207
284
  privateKey,
208
285
  mnemonic: this.unlockedMnemonic ?? undefined,
209
- password: this.unlockedPassword ?? undefined,
210
- expiresAt
286
+ sessionKey: this.unlockedSessionKey,
287
+ expiresAt: nextExpiresAt
211
288
  };
212
289
  await this.store.saveUnlockedSession(session);
213
290
  }
@@ -215,7 +292,7 @@ export class WalletController {
215
292
  this.unlockedPrivateKey = null;
216
293
  this.unlockedSigner = null;
217
294
  this.unlockedMnemonic = null;
218
- this.unlockedPassword = null;
295
+ this.unlockedSessionKey = null;
219
296
  await this.store.clearUnlockedSession();
220
297
  }
221
298
  async getUnlockedSigner() {
@@ -244,6 +321,118 @@ export class WalletController {
244
321
  }
245
322
  return normalizeStoredWalletNetworks(state);
246
323
  }
324
+ async resolveTokenMetadataForState(state, contract) {
325
+ const normalizedContract = contract.trim();
326
+ const client = this.currentClient(state);
327
+ const metadata = await client.getTokenMetadata(normalizedContract);
328
+ return {
329
+ contract: normalizedContract,
330
+ name: trimNullableString(metadata.name),
331
+ symbol: trimNullableString(metadata.symbol),
332
+ logoUrl: trimNullableString(metadata.logoUrl),
333
+ logoSvg: trimNullableString(metadata.logoSvg)
334
+ };
335
+ }
336
+ async hydrateWatchedAssetIcons(state) {
337
+ const assetsMissingIcons = state.watchedAssets.some((asset) => !trimOptionalString(asset.icon));
338
+ if (!assetsMissingIcons) {
339
+ return state;
340
+ }
341
+ let changed = false;
342
+ const watchedAssets = await Promise.all(state.watchedAssets.map(async (asset) => {
343
+ if (trimOptionalString(asset.icon)) {
344
+ return asset;
345
+ }
346
+ try {
347
+ const metadata = await this.resolveTokenMetadataForState(state, asset.contract);
348
+ const icon = metadata.logoUrl ?? metadata.logoSvg ?? undefined;
349
+ if (!icon) {
350
+ return asset;
351
+ }
352
+ changed = true;
353
+ return {
354
+ ...asset,
355
+ icon
356
+ };
357
+ }
358
+ catch {
359
+ return asset;
360
+ }
361
+ }));
362
+ if (!changed) {
363
+ return state;
364
+ }
365
+ const nextState = {
366
+ ...state,
367
+ watchedAssets
368
+ };
369
+ await this.store.saveState(nextState);
370
+ return nextState;
371
+ }
372
+ requireAccounts(state) {
373
+ if (!state.accounts || state.accounts.length === 0) {
374
+ throw new Error("wallet state has no accounts");
375
+ }
376
+ return state.accounts;
377
+ }
378
+ async sessionKeyForState(state, password) {
379
+ return deriveWalletSessionKey(password, state.walletEncryptionSalt);
380
+ }
381
+ async decryptPrivateKeyForState(state, password) {
382
+ return decryptPrivateKeyWithSessionKey(state.encryptedPrivateKey, await this.sessionKeyForState(state, password));
383
+ }
384
+ async decryptMnemonicForState(state, password) {
385
+ if (!state.encryptedMnemonic) {
386
+ throw new Error("wallet does not have a recovery phrase");
387
+ }
388
+ return decryptMnemonicWithSessionKey(state.encryptedMnemonic, await this.sessionKeyForState(state, password));
389
+ }
390
+ async requireUnlockedSessionKey() {
391
+ if (!(await this.restoreUnlockedSession()) || !this.unlockedSessionKey) {
392
+ throw new ProviderUnauthorizedError("wallet is locked");
393
+ }
394
+ return this.unlockedSessionKey;
395
+ }
396
+ storedShieldedWalletSnapshots(state) {
397
+ return [...(state.shieldedWalletSnapshots ?? [])].sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
398
+ }
399
+ shieldedWalletSnapshotSummaries(state) {
400
+ return this.storedShieldedWalletSnapshots(state).map(shieldedWalletSnapshotSummary);
401
+ }
402
+ async exportShieldedWalletSnapshots(state, sessionKey) {
403
+ const exported = [];
404
+ for (const record of this.storedShieldedWalletSnapshots(state)) {
405
+ exported.push({
406
+ label: record.label,
407
+ stateSnapshot: await decryptSecretTextWithSessionKey(record.encryptedStateSnapshot, sessionKey),
408
+ });
409
+ }
410
+ return exported;
411
+ }
412
+ async importShieldedWalletSnapshots(snapshots, sessionKey, nowIso) {
413
+ const imported = [];
414
+ for (const item of snapshots ?? []) {
415
+ if (typeof item !== "object" ||
416
+ item == null ||
417
+ typeof item.label !== "string" ||
418
+ typeof item.stateSnapshot !== "string") {
419
+ throw new Error("backup shieldedStateSnapshots must contain label and stateSnapshot");
420
+ }
421
+ const parsed = parseShieldedWalletSnapshot(item.stateSnapshot);
422
+ imported.push({
423
+ id: this.createId(),
424
+ label: trimOptionalString(item.label) ?? parsed.assetId,
425
+ assetId: parsed.assetId,
426
+ syncHint: parsed.syncHint,
427
+ encryptedStateSnapshot: await encryptSecretTextWithSessionKey(parsed.normalizedSnapshot, sessionKey),
428
+ noteCount: parsed.noteCount,
429
+ commitmentCount: parsed.commitmentCount,
430
+ lastScannedIndex: parsed.lastScannedIndex,
431
+ updatedAt: nowIso,
432
+ });
433
+ }
434
+ return imported;
435
+ }
247
436
  activeNetworkPreset(state) {
248
437
  const normalized = normalizeStoredWalletNetworks(state);
249
438
  return (normalized.networkPresets.find((preset) => preset.id === normalized.activeNetworkId) ??
@@ -539,8 +728,8 @@ export class WalletController {
539
728
  function: intent.function,
540
729
  kwargs: intent.kwargs,
541
730
  chainId: activeChainId,
542
- stamps: parseIntentNumber(intent.stamps, "stamps"),
543
- stampsSupplied: parseIntentNumber(intent.stampsSupplied, "stampsSupplied")
731
+ chi: parseIntentNumber(intent.chi, "chi"),
732
+ chiSupplied: parseIntentNumber(intent.chiSupplied, "chiSupplied")
544
733
  });
545
734
  }
546
735
  async signPreparedTransaction(state, tx) {
@@ -833,14 +1022,17 @@ export class WalletController {
833
1022
  }
834
1023
  }
835
1024
  getAccountsList(state) {
836
- if (state.accounts && state.accounts.length > 0) {
837
- return state.accounts.map((a) => ({ index: a.index, publicKey: a.publicKey, name: a.name }));
838
- }
839
- // Backward compat: create virtual account from legacy fields
840
- return [{ index: 0, publicKey: state.publicKey, name: "Account 1" }];
1025
+ return this.requireAccounts(state).map((account) => ({
1026
+ index: account.index,
1027
+ publicKey: account.publicKey,
1028
+ name: account.name
1029
+ }));
841
1030
  }
842
1031
  async getPopupState() {
843
- const state = await this.loadWalletState();
1032
+ const loadedState = await this.loadWalletState();
1033
+ const state = loadedState
1034
+ ? await this.hydrateWatchedAssetIcons(loadedState)
1035
+ : null;
844
1036
  const approvals = await this.store.listApprovalStates();
845
1037
  const pendingApprovals = approvals
846
1038
  .map((approval) => approval.view)
@@ -878,6 +1070,9 @@ export class WalletController {
878
1070
  mnemonicWordCount: state?.mnemonicWordCount,
879
1071
  accounts: state ? this.getAccountsList(state) : [],
880
1072
  activeAccountIndex: state?.activeAccountIndex ?? 0,
1073
+ shieldedWalletSnapshots: state
1074
+ ? this.shieldedWalletSnapshotSummaries(state)
1075
+ : [],
881
1076
  version: this.options.version
882
1077
  };
883
1078
  }
@@ -890,7 +1085,7 @@ export class WalletController {
890
1085
  }
891
1086
  async getTokenMetadata(contract) {
892
1087
  const state = this.requireStoredWallet(await this.loadWalletState());
893
- return this.currentClient(state).getTokenMetadata(contract);
1088
+ return this.resolveTokenMetadataForState(state, contract);
894
1089
  }
895
1090
  async getDetectedAssets() {
896
1091
  const state = await this.loadWalletState();
@@ -909,6 +1104,24 @@ export class WalletController {
909
1104
  if (!normalized.contract) {
910
1105
  throw new TypeError("asset contract is required");
911
1106
  }
1107
+ // Auto-fetch metadata if any display metadata is missing.
1108
+ if (!normalized.name || !normalized.symbol || !normalized.icon) {
1109
+ try {
1110
+ const state = this.requireStoredWallet(await this.loadWalletState());
1111
+ const meta = await this.resolveTokenMetadataForState(state, normalized.contract);
1112
+ if (meta.name && !normalized.name)
1113
+ normalized.name = meta.name;
1114
+ if (meta.symbol && !normalized.symbol)
1115
+ normalized.symbol = meta.symbol;
1116
+ if (meta.logoUrl && !normalized.icon)
1117
+ normalized.icon = meta.logoUrl;
1118
+ if (meta.logoSvg && !normalized.icon)
1119
+ normalized.icon = meta.logoSvg;
1120
+ }
1121
+ catch {
1122
+ // Metadata fetch failed — use contract name as fallback
1123
+ }
1124
+ }
912
1125
  await this.updateWatchedAssets((assets) => {
913
1126
  const next = assets.filter((entry) => entry.contract !== normalized.contract);
914
1127
  next.push(normalized);
@@ -943,16 +1156,32 @@ export class WalletController {
943
1156
  await this.store.saveState(state);
944
1157
  return this.getPopupState();
945
1158
  }
946
- async estimateTransactionStamps(request) {
1159
+ async estimateTransactionChi(request) {
947
1160
  const state = this.requireStoredWallet(await this.loadWalletState());
948
1161
  const client = this.currentClient(state);
949
- return client.estimateStamps({
1162
+ return client.estimateChi({
950
1163
  sender: state.publicKey,
951
1164
  contract: request.contract,
952
1165
  function: request.function,
953
1166
  kwargs: request.kwargs
954
1167
  });
955
1168
  }
1169
+ async getChiRate() {
1170
+ const state = await this.loadWalletState();
1171
+ if (!state)
1172
+ return null;
1173
+ try {
1174
+ const client = this.currentClient(state);
1175
+ if (typeof client.getChiRate !== "function") {
1176
+ return null;
1177
+ }
1178
+ const rate = await client.getChiRate();
1179
+ return rate != null ? Number(rate) : null;
1180
+ }
1181
+ catch {
1182
+ return null;
1183
+ }
1184
+ }
956
1185
  async sendDirectTransaction(intent) {
957
1186
  const state = this.requireStoredWallet(await this.loadWalletState());
958
1187
  await this.getUnlockedSigner();
@@ -960,7 +1189,7 @@ export class WalletController {
960
1189
  contract: intent.contract,
961
1190
  function: intent.function,
962
1191
  kwargs: intent.kwargs,
963
- stamps: intent.stamps
1192
+ chi: intent.chi
964
1193
  });
965
1194
  return this.sendPreparedTransaction(state, tx, { mode: "commit" });
966
1195
  }
@@ -1000,14 +1229,15 @@ export class WalletController {
1000
1229
  createWithMnemonic: input.createWithMnemonic
1001
1230
  });
1002
1231
  const signer = new Ed25519Signer(secret.privateKey);
1003
- const encryptedPrivateKey = await encryptPrivateKey(secret.privateKey, input.password);
1232
+ const { walletEncryptionSalt, sessionKey } = await createWalletSessionKey(input.password);
1233
+ const encryptedPrivateKey = await encryptPrivateKeyWithSessionKey(secret.privateKey, sessionKey);
1004
1234
  const encryptedMnemonic = secret.mnemonic
1005
- ? await encryptMnemonic(secret.mnemonic, input.password)
1235
+ ? await encryptMnemonicWithSessionKey(secret.mnemonic, sessionKey)
1006
1236
  : undefined;
1007
1237
  this.unlockedPrivateKey = secret.privateKey;
1008
1238
  this.unlockedSigner = signer;
1009
1239
  this.unlockedMnemonic = secret.mnemonic ?? null;
1010
- this.unlockedPassword = input.password;
1240
+ this.unlockedSessionKey = sessionKey;
1011
1241
  await this.persistUnlockedSession(secret.privateKey);
1012
1242
  await this.invalidatePendingRequests(new ProviderUnauthorizedError("wallet was replaced"));
1013
1243
  const setupRpcUrl = trimOptionalString(input.rpcUrl) ?? DEFAULT_RPC_URL;
@@ -1045,6 +1275,7 @@ export class WalletController {
1045
1275
  publicKey: signer.address,
1046
1276
  encryptedPrivateKey,
1047
1277
  encryptedMnemonic,
1278
+ walletEncryptionSalt,
1048
1279
  seedSource: secret.seedSource,
1049
1280
  mnemonicWordCount: secret.mnemonicWordCount,
1050
1281
  accounts: [initialAccount],
@@ -1071,18 +1302,19 @@ export class WalletController {
1071
1302
  }
1072
1303
  async unlockWallet(password) {
1073
1304
  const state = this.requireStoredWallet(await this.loadWalletState());
1074
- const privateKey = await decryptPrivateKey(state.encryptedPrivateKey, password);
1305
+ const sessionKey = await this.sessionKeyForState(state, password);
1306
+ const privateKey = await decryptPrivateKeyWithSessionKey(state.encryptedPrivateKey, sessionKey);
1075
1307
  const signer = new Ed25519Signer(privateKey);
1076
1308
  if (signer.address !== state.publicKey) {
1077
1309
  throw new Error("decrypted private key does not match stored wallet");
1078
1310
  }
1079
1311
  this.unlockedPrivateKey = privateKey;
1080
1312
  this.unlockedSigner = signer;
1081
- this.unlockedPassword = password;
1313
+ this.unlockedSessionKey = sessionKey;
1082
1314
  // Decrypt mnemonic into session for account switching
1083
1315
  if (state.encryptedMnemonic) {
1084
1316
  try {
1085
- this.unlockedMnemonic = await decryptMnemonic(state.encryptedMnemonic, password);
1317
+ this.unlockedMnemonic = await decryptMnemonicWithSessionKey(state.encryptedMnemonic, sessionKey);
1086
1318
  }
1087
1319
  catch {
1088
1320
  this.unlockedMnemonic = null;
@@ -1094,20 +1326,16 @@ export class WalletController {
1094
1326
  }
1095
1327
  async revealMnemonic(password) {
1096
1328
  const state = this.requireStoredWallet(await this.loadWalletState());
1097
- if (!state.encryptedMnemonic) {
1098
- throw new Error("wallet does not have a recovery phrase");
1099
- }
1100
- return decryptMnemonic(state.encryptedMnemonic, password);
1329
+ return this.decryptMnemonicForState(state, password);
1101
1330
  }
1102
1331
  async revealPrivateKey(password) {
1103
1332
  const state = this.requireStoredWallet(await this.loadWalletState());
1104
- return decryptPrivateKey(state.encryptedPrivateKey, password);
1333
+ return this.decryptPrivateKeyForState(state, password);
1105
1334
  }
1106
1335
  async exportWallet(password) {
1107
1336
  const state = this.requireStoredWallet(await this.loadWalletState());
1108
- const accounts = state.accounts ?? [
1109
- { index: 0, publicKey: state.publicKey, encryptedPrivateKey: state.encryptedPrivateKey, name: "Account 1" }
1110
- ];
1337
+ const accounts = this.requireAccounts(state);
1338
+ const sessionKey = await this.sessionKeyForState(state, password);
1111
1339
  const backup = {
1112
1340
  version: 1,
1113
1341
  type: state.seedSource,
@@ -1118,10 +1346,14 @@ export class WalletController {
1118
1346
  watchedAssets: state.watchedAssets
1119
1347
  };
1120
1348
  if (state.encryptedMnemonic) {
1121
- backup.mnemonic = await decryptMnemonic(state.encryptedMnemonic, password);
1349
+ backup.mnemonic = await decryptMnemonicWithSessionKey(state.encryptedMnemonic, sessionKey);
1122
1350
  }
1123
1351
  else {
1124
- backup.privateKey = await decryptPrivateKey(state.encryptedPrivateKey, password);
1352
+ backup.privateKey = await decryptPrivateKeyWithSessionKey(state.encryptedPrivateKey, sessionKey);
1353
+ }
1354
+ const shieldedStateSnapshots = await this.exportShieldedWalletSnapshots(state, sessionKey);
1355
+ if (shieldedStateSnapshots.length > 0) {
1356
+ backup.shieldedStateSnapshots = shieldedStateSnapshots;
1125
1357
  }
1126
1358
  return backup;
1127
1359
  }
@@ -1139,11 +1371,16 @@ export class WalletController {
1139
1371
  else {
1140
1372
  throw new Error("backup must contain a mnemonic or private key");
1141
1373
  }
1374
+ const { walletEncryptionSalt, sessionKey } = await createWalletSessionKey(password);
1375
+ const nowIso = new Date().toISOString();
1142
1376
  const encryptedMnemonic = mnemonic
1143
- ? await encryptMnemonic(mnemonic, password)
1377
+ ? await encryptMnemonicWithSessionKey(mnemonic, sessionKey)
1144
1378
  : undefined;
1145
1379
  // Build accounts list
1146
- const accountEntries = backup.accounts ?? [{ index: 0, name: "Account 1" }];
1380
+ const accountEntries = backup.accounts;
1381
+ if (!accountEntries || accountEntries.length === 0) {
1382
+ throw new Error("backup must contain at least one account");
1383
+ }
1147
1384
  const accounts = [];
1148
1385
  const privateKeysByIndex = new Map();
1149
1386
  for (const entry of accountEntries) {
@@ -1155,7 +1392,7 @@ export class WalletController {
1155
1392
  accounts.push({
1156
1393
  index: entry.index,
1157
1394
  publicKey: acctSigner.address,
1158
- encryptedPrivateKey: await encryptPrivateKey(key, password),
1395
+ encryptedPrivateKey: await encryptPrivateKeyWithSessionKey(key, sessionKey),
1159
1396
  name: entry.name
1160
1397
  });
1161
1398
  }
@@ -1169,7 +1406,7 @@ export class WalletController {
1169
1406
  this.unlockedPrivateKey = activePrivateKey;
1170
1407
  this.unlockedSigner = signer;
1171
1408
  this.unlockedMnemonic = mnemonic ?? null;
1172
- this.unlockedPassword = password;
1409
+ this.unlockedSessionKey = sessionKey;
1173
1410
  await this.persistUnlockedSession(activePrivateKey);
1174
1411
  await this.invalidatePendingRequests(new ProviderUnauthorizedError("wallet was replaced"));
1175
1412
  // Merge network presets
@@ -1187,10 +1424,12 @@ export class WalletController {
1187
1424
  const watchedAssets = backup.watchedAssets?.length
1188
1425
  ? backup.watchedAssets
1189
1426
  : [{ contract: "currency", name: "Xian", symbol: "XIAN" }];
1427
+ const shieldedWalletSnapshots = await this.importShieldedWalletSnapshots(backup.shieldedStateSnapshots, sessionKey, nowIso);
1190
1428
  await this.persistWalletState({
1191
1429
  publicKey: activeAccount.publicKey,
1192
1430
  encryptedPrivateKey: activeAccount.encryptedPrivateKey,
1193
1431
  encryptedMnemonic,
1432
+ walletEncryptionSalt,
1194
1433
  seedSource: backup.type,
1195
1434
  mnemonicWordCount: mnemonic ? mnemonic.split(" ").length : undefined,
1196
1435
  accounts,
@@ -1200,24 +1439,110 @@ export class WalletController {
1200
1439
  activeNetworkId: activePreset.id,
1201
1440
  networkPresets: presets,
1202
1441
  watchedAssets,
1442
+ shieldedWalletSnapshots,
1203
1443
  connectedOrigins: [],
1204
- createdAt: new Date().toISOString()
1444
+ createdAt: nowIso
1205
1445
  });
1206
1446
  return this.getPopupState();
1207
1447
  }
1448
+ async saveShieldedWalletSnapshot(stateSnapshot, label) {
1449
+ const state = this.requireStoredWallet(await this.loadWalletState());
1450
+ const sessionKey = await this.requireUnlockedSessionKey();
1451
+ const parsed = parseShieldedWalletSnapshot(stateSnapshot);
1452
+ const resolvedLabel = trimOptionalString(label) ?? parsed.assetId;
1453
+ const existing = this.storedShieldedWalletSnapshots(state).find((record) => record.assetId === parsed.assetId && record.label === resolvedLabel);
1454
+ const updatedAt = new Date().toISOString();
1455
+ const nextRecord = {
1456
+ id: existing?.id ?? this.createId(),
1457
+ label: resolvedLabel,
1458
+ assetId: parsed.assetId,
1459
+ syncHint: parsed.syncHint,
1460
+ encryptedStateSnapshot: await encryptSecretTextWithSessionKey(parsed.normalizedSnapshot, sessionKey),
1461
+ noteCount: parsed.noteCount,
1462
+ commitmentCount: parsed.commitmentCount,
1463
+ lastScannedIndex: parsed.lastScannedIndex,
1464
+ updatedAt,
1465
+ };
1466
+ state.shieldedWalletSnapshots = [
1467
+ nextRecord,
1468
+ ...this.storedShieldedWalletSnapshots(state).filter((record) => record.id !== nextRecord.id),
1469
+ ];
1470
+ await this.persistWalletState(state);
1471
+ return this.getPopupState();
1472
+ }
1473
+ async exportShieldedWalletSnapshot(snapshotId, password) {
1474
+ const state = this.requireStoredWallet(await this.loadWalletState());
1475
+ const record = this.storedShieldedWalletSnapshots(state).find((item) => item.id === snapshotId);
1476
+ if (!record) {
1477
+ throw new Error("shielded wallet snapshot not found");
1478
+ }
1479
+ const sessionKey = await this.sessionKeyForState(state, password);
1480
+ return {
1481
+ label: record.label,
1482
+ stateSnapshot: await decryptSecretTextWithSessionKey(record.encryptedStateSnapshot, sessionKey),
1483
+ };
1484
+ }
1485
+ async removeShieldedWalletSnapshot(snapshotId) {
1486
+ const state = this.requireStoredWallet(await this.loadWalletState());
1487
+ const nextSnapshots = this.storedShieldedWalletSnapshots(state).filter((record) => record.id !== snapshotId);
1488
+ if (nextSnapshots.length === this.storedShieldedWalletSnapshots(state).length) {
1489
+ throw new Error("shielded wallet snapshot not found");
1490
+ }
1491
+ state.shieldedWalletSnapshots = nextSnapshots;
1492
+ await this.persistWalletState(state);
1493
+ return this.getPopupState();
1494
+ }
1495
+ async getShieldedWalletSnapshotHistory(snapshotId, limit = 5) {
1496
+ const state = this.requireStoredWallet(await this.loadWalletState());
1497
+ const record = this.storedShieldedWalletSnapshots(state).find((item) => item.id === snapshotId);
1498
+ if (!record) {
1499
+ throw new Error("shielded wallet snapshot not found");
1500
+ }
1501
+ const client = this.currentClient(state);
1502
+ if (typeof client.getShieldedWalletHistory !== "function") {
1503
+ return {
1504
+ snapshotId: record.id,
1505
+ label: record.label,
1506
+ available: false,
1507
+ hasNewerIndexedHistory: false,
1508
+ checkedAfterNoteIndex: record.lastScannedIndex,
1509
+ newItems: [],
1510
+ };
1511
+ }
1512
+ const history = await client.getShieldedWalletHistory(record.syncHint, {
1513
+ kind: "sync_hint",
1514
+ limit: Math.max(1, Math.min(Math.trunc(limit), 10)),
1515
+ afterNoteIndex: record.lastScannedIndex,
1516
+ });
1517
+ return {
1518
+ snapshotId: record.id,
1519
+ label: record.label,
1520
+ available: history.available,
1521
+ hasNewerIndexedHistory: history.items.length > 0,
1522
+ checkedAfterNoteIndex: record.lastScannedIndex,
1523
+ newItems: history.items.map((item) => ({
1524
+ txHash: item.txHash,
1525
+ blockHeight: item.blockHeight,
1526
+ function: item.function,
1527
+ action: item.action,
1528
+ noteIndex: item.noteIndex,
1529
+ commitment: item.commitment,
1530
+ hasPayload: item.outputPayload != null && item.outputPayload !== "",
1531
+ createdAt: item.createdAt,
1532
+ })),
1533
+ };
1534
+ }
1208
1535
  async addAccount() {
1209
1536
  await this.restoreUnlockedSession();
1210
- if (!this.unlockedMnemonic || !this.unlockedPassword) {
1537
+ if (!this.unlockedMnemonic || !this.unlockedSessionKey) {
1211
1538
  throw new Error("wallet must be unlocked to add an account");
1212
1539
  }
1213
1540
  const state = this.requireStoredWallet(await this.loadWalletState());
1214
- const accounts = state.accounts ?? [
1215
- { index: 0, publicKey: state.publicKey, encryptedPrivateKey: state.encryptedPrivateKey, name: "Account 1" }
1216
- ];
1541
+ const accounts = this.requireAccounts(state);
1217
1542
  const nextIndex = Math.max(...accounts.map((a) => a.index)) + 1;
1218
1543
  const privateKey = await derivePrivateKeyFromMnemonic(this.unlockedMnemonic, nextIndex);
1219
1544
  const signer = new Ed25519Signer(privateKey);
1220
- const encrypted = await encryptPrivateKey(privateKey, this.unlockedPassword);
1545
+ const encrypted = await encryptPrivateKeyWithSessionKey(privateKey, this.unlockedSessionKey);
1221
1546
  accounts.push({
1222
1547
  index: nextIndex,
1223
1548
  publicKey: signer.address,
@@ -1237,9 +1562,7 @@ export class WalletController {
1237
1562
  }
1238
1563
  async switchAccount(index) {
1239
1564
  const state = this.requireStoredWallet(await this.loadWalletState());
1240
- const accounts = state.accounts ?? [
1241
- { index: 0, publicKey: state.publicKey, encryptedPrivateKey: state.encryptedPrivateKey, name: "Account 1" }
1242
- ];
1565
+ const accounts = this.requireAccounts(state);
1243
1566
  const target = accounts.find((a) => a.index === index);
1244
1567
  if (!target) {
1245
1568
  throw new Error("account not found");
@@ -1265,13 +1588,15 @@ export class WalletController {
1265
1588
  }
1266
1589
  async renameAccount(index, name) {
1267
1590
  const state = this.requireStoredWallet(await this.loadWalletState());
1268
- const accounts = state.accounts ?? [
1269
- { index: 0, publicKey: state.publicKey, encryptedPrivateKey: state.encryptedPrivateKey, name: "Account 1" }
1270
- ];
1591
+ const accounts = this.requireAccounts(state);
1271
1592
  const target = accounts.find((a) => a.index === index);
1272
1593
  if (!target) {
1273
1594
  throw new Error("account not found");
1274
1595
  }
1596
+ const duplicate = accounts.find((a) => a.index !== index && a.name.toLowerCase() === name.toLowerCase());
1597
+ if (duplicate) {
1598
+ throw new Error(`An account named "${name}" already exists`);
1599
+ }
1275
1600
  target.name = name;
1276
1601
  state.accounts = accounts;
1277
1602
  await this.store.saveState(state);
@@ -1282,7 +1607,7 @@ export class WalletController {
1282
1607
  if (index === 0) {
1283
1608
  throw new Error("cannot remove the primary account");
1284
1609
  }
1285
- const accounts = state.accounts ?? [];
1610
+ const accounts = this.requireAccounts(state);
1286
1611
  const nextAccounts = accounts.filter((account) => account.index !== index);
1287
1612
  if (nextAccounts.length === 0) {
1288
1613
  throw new Error("cannot remove the last remaining account");