@xian-tech/wallet-core 0.4.2 → 0.4.4

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.
Files changed (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +18 -0
  3. package/dist/approval-execution.d.ts +5 -0
  4. package/dist/approval-execution.d.ts.map +1 -0
  5. package/dist/approval-execution.js +17 -0
  6. package/dist/approval-execution.js.map +1 -0
  7. package/dist/approvals.d.ts +26 -2
  8. package/dist/approvals.d.ts.map +1 -1
  9. package/dist/approvals.js +358 -280
  10. package/dist/approvals.js.map +1 -1
  11. package/dist/controller.d.ts +40 -3
  12. package/dist/controller.d.ts.map +1 -1
  13. package/dist/controller.js +426 -169
  14. package/dist/controller.js.map +1 -1
  15. package/dist/crypto.d.ts +7 -1
  16. package/dist/crypto.d.ts.map +1 -1
  17. package/dist/crypto.js +39 -13
  18. package/dist/crypto.js.map +1 -1
  19. package/dist/index.d.ts +1 -0
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +1 -0
  22. package/dist/index.js.map +1 -1
  23. package/dist/network.d.ts.map +1 -1
  24. package/dist/network.js +3 -0
  25. package/dist/network.js.map +1 -1
  26. package/dist/signing-context.d.ts +5 -0
  27. package/dist/signing-context.d.ts.map +1 -0
  28. package/dist/signing-context.js +22 -0
  29. package/dist/signing-context.js.map +1 -0
  30. package/dist/simulation.d.ts +10 -0
  31. package/dist/simulation.d.ts.map +1 -0
  32. package/dist/simulation.js +25 -0
  33. package/dist/simulation.js.map +1 -0
  34. package/dist/text-safety.d.ts +4 -0
  35. package/dist/text-safety.d.ts.map +1 -0
  36. package/dist/text-safety.js +15 -0
  37. package/dist/text-safety.js.map +1 -0
  38. package/dist/types.d.ts +22 -6
  39. package/dist/types.d.ts.map +1 -1
  40. package/dist/wallet-encryption.d.ts +7 -0
  41. package/dist/wallet-encryption.d.ts.map +1 -0
  42. package/dist/wallet-encryption.js +23 -0
  43. package/dist/wallet-encryption.js.map +1 -0
  44. package/package.json +7 -5
@@ -1,11 +1,21 @@
1
- import { createXianMessageSigningPayload, Ed25519Signer, shieldedSyncHintFromViewingPrivateKey, XianClient } from "@xian-tech/client";
2
- import { createXianDappPolicyForRequest, findMatchingXianDappPolicy, ProviderChainMismatchError, ProviderUnauthorizedError, ProviderUnsupportedMethodError, xianDappPoliciesHaveSameScope } from "@xian-tech/provider";
1
+ import { beginApprovalResolution, isApprovalResolutionActive } from "./approval-execution.js";
2
+ import { chiToSupply, createXianMessageSigningPayload, prepareTransaction, Ed25519Signer, shieldedSyncHintFromViewingPrivateKey, XianClient } from "@xian-tech/client";
3
+ import { createXianDappPolicyForRequest, findMatchingXianDappPolicy, parseXianDappAction, ProviderChainMismatchError, ProviderUnauthorizedError, ProviderUnsupportedMethodError, xianDappPoliciesHaveSameScope, XianProviderError } from "@xian-tech/provider";
3
4
  import { approvalKindFromMethod, buildApprovalView } from "./approvals.js";
5
+ import { assertSimulationSucceeds } from "./simulation.js";
4
6
  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
7
  import { assertRpcTransportAllowed } from "./network.js";
6
- import { createWalletSessionKey, decryptSecretTextWithSessionKey, createWalletSecret, decryptMnemonicWithSessionKey, decryptPrivateKeyWithSessionKey, decryptWalletBackup, deriveWalletSessionKey, derivePrivateKeyFromMnemonic, encryptSecretTextWithSessionKey, encryptMnemonicWithSessionKey, encryptPrivateKeyWithSessionKey, encryptWalletBackupPayload, isUnsafeMessageToSign } from "./crypto.js";
8
+ import { reencryptWalletState } from "./wallet-encryption.js";
9
+ import { createWalletSessionKey, WALLET_KDF_ITERATIONS, LEGACY_WALLET_KDF_ITERATIONS, decryptSecretTextWithSessionKey, createWalletSecret, decryptMnemonicWithSessionKey, decryptPrivateKeyWithSessionKey, decryptWalletBackup, deriveWalletSessionKey, derivePrivateKeyFromMnemonic, encryptSecretTextWithSessionKey, encryptMnemonicWithSessionKey, encryptPrivateKeyWithSessionKey, encryptWalletBackupPayload, isUnsafeMessageToSign } from "./crypto.js";
7
10
  const SAFE_CHAIN_ID_LOOKUP_TIMEOUT_MS = 2_000;
8
11
  const TRUSTED_DAPP_POLICY_TTL_MS = 30 * 24 * 60 * 60 * 1000;
12
+ // A site may have one connect prompt and a few other prompts open at a time.
13
+ const MAX_PENDING_APPROVALS_PER_ORIGIN = 3;
14
+ class ProviderRequestPendingError extends XianProviderError {
15
+ constructor(message) {
16
+ super(-32002, message);
17
+ }
18
+ }
9
19
  const MAX_DAPP_METADATA_TEXT_LENGTH = 120;
10
20
  const MAX_DAPP_ICON_URL_LENGTH = 2048;
11
21
  const DEX_ROUTER_CONTRACT = "con_dex";
@@ -45,6 +55,50 @@ function parseIntentNumber(value, fieldName) {
45
55
  }
46
56
  throw new TypeError(`${fieldName} must be a non-negative integer`);
47
57
  }
58
+ // A send-call whose intent names a contract and function.
59
+ function sendCallTarget(request) {
60
+ if (request.method !== "xian_sendCall") {
61
+ return null;
62
+ }
63
+ const firstParam = firstParamObject(request.params);
64
+ const intent = firstParam.intent;
65
+ if (!isRecord(intent) || typeof intent.contract !== "string" || typeof intent.function !== "string") {
66
+ return null;
67
+ }
68
+ return { firstParam, intent: intent };
69
+ }
70
+ // A send-call without chi: the wallet estimates chi for it before review.
71
+ function sendCallIntentWithoutChi(request) {
72
+ const target = sendCallTarget(request);
73
+ return target && target.intent.chi == null && target.intent.chiSupplied == null ? target : null;
74
+ }
75
+ // A send-call whose site chose the chi limit: the wallet simulates it so the
76
+ // review can say what the unused chi costs.
77
+ function sendCallIntentWithSiteChi(request) {
78
+ const target = sendCallTarget(request);
79
+ return target && typeof (target.intent.chiSupplied ?? target.intent.chi) === "number" ? target : null;
80
+ }
81
+ /** The chi to supply for a positive estimate, or null (none, or above the per-transaction limit). */
82
+ function supplyFor(estimated) {
83
+ if (!Number.isFinite(estimated) || estimated <= 0) {
84
+ return null;
85
+ }
86
+ try {
87
+ return chiToSupply(estimated);
88
+ }
89
+ catch {
90
+ return null;
91
+ }
92
+ }
93
+ function withSendCallIntent(request, firstParam, intent) {
94
+ const nextFirstParam = { ...firstParam, intent };
95
+ return {
96
+ ...request,
97
+ params: Array.isArray(request.params)
98
+ ? [nextFirstParam, ...request.params.slice(1)]
99
+ : nextFirstParam
100
+ };
101
+ }
48
102
  function trimOptionalString(value) {
49
103
  const trimmed = value?.trim();
50
104
  return trimmed ? trimmed : undefined;
@@ -658,58 +712,86 @@ export class WalletController {
658
712
  message: String(error)
659
713
  };
660
714
  }
715
+ sessionGeneration = 0;
716
+ resetSessionSecrets() {
717
+ this.unlockedPrivateKey = null;
718
+ this.unlockedSigner = null;
719
+ this.unlockedMnemonic = null;
720
+ this.unlockedSessionKey = null;
721
+ this.unlockedSessionExpiresAt = null;
722
+ }
723
+ async discardRestoredSession(generation) {
724
+ if (generation === this.sessionGeneration) {
725
+ await this.clearUnlockedSession();
726
+ }
727
+ return false;
728
+ }
729
+ async restoreSessionSecrets(session, generation) {
730
+ const { sessionKey } = session;
731
+ if (!sessionKey)
732
+ return this.discardRestoredSession(generation);
733
+ try {
734
+ const state = await this.loadWalletState();
735
+ if (!state || state.publicKey !== session.publicKey) {
736
+ return this.discardRestoredSession(generation);
737
+ }
738
+ const privateKey = await decryptPrivateKeyWithSessionKey(state.encryptedPrivateKey, sessionKey);
739
+ const signer = new Ed25519Signer(privateKey);
740
+ if (signer.address !== session.publicKey) {
741
+ return this.discardRestoredSession(generation);
742
+ }
743
+ const mnemonic = state.encryptedMnemonic
744
+ ? await decryptMnemonicWithSessionKey(state.encryptedMnemonic, sessionKey).catch(() => null)
745
+ : null;
746
+ if (generation !== this.sessionGeneration)
747
+ return false;
748
+ this.unlockedPrivateKey = privateKey;
749
+ this.unlockedSigner = signer;
750
+ this.unlockedSessionKey = sessionKey;
751
+ this.unlockedMnemonic = mnemonic;
752
+ return true;
753
+ }
754
+ catch {
755
+ return this.discardRestoredSession(generation);
756
+ }
757
+ }
661
758
  async restoreUnlockedSession() {
759
+ // Let a lock clear an in-flight save before restoring persisted credentials.
760
+ const generation = this.sessionGeneration;
761
+ const signer = this.unlockedSigner;
762
+ await this.automaticSendTails.get("wallet-session");
763
+ if (generation !== this.sessionGeneration)
764
+ return false;
662
765
  const session = await this.store.loadUnlockedSession();
766
+ if (generation !== this.sessionGeneration)
767
+ return false;
768
+ // An account switch, unlock or import replaced the signer while the
769
+ // session was read, so the read predates that writer's queued save:
770
+ // re-read instead of judging the new signer by the old session.
771
+ if (this.unlockedSigner !== signer)
772
+ return this.restoreUnlockedSession();
663
773
  if (!session) {
664
- this.unlockedPrivateKey = null;
665
- this.unlockedSigner = null;
666
- this.unlockedMnemonic = null;
667
- this.unlockedSessionKey = null;
668
- this.unlockedSessionExpiresAt = null;
774
+ this.resetSessionSecrets();
669
775
  return false;
670
776
  }
671
777
  if (session.expiresAt <= this.now()) {
672
778
  await this.expireUnlockedSession();
673
779
  return false;
674
780
  }
675
- if ((!this.unlockedPrivateKey || !this.unlockedSessionKey) && session.sessionKey) {
676
- const state = await this.loadWalletState();
677
- if (!state || state.publicKey !== session.publicKey) {
678
- await this.clearUnlockedSession();
679
- return false;
680
- }
681
- try {
682
- const privateKey = await decryptPrivateKeyWithSessionKey(state.encryptedPrivateKey, session.sessionKey);
683
- const signer = new Ed25519Signer(privateKey);
684
- if (signer.address !== session.publicKey) {
685
- await this.clearUnlockedSession();
686
- return false;
687
- }
688
- this.unlockedPrivateKey = privateKey;
689
- this.unlockedSigner = signer;
690
- this.unlockedSessionKey = session.sessionKey;
691
- if (state.encryptedMnemonic) {
692
- this.unlockedMnemonic = await decryptMnemonicWithSessionKey(state.encryptedMnemonic, session.sessionKey).catch(() => null);
693
- }
694
- else {
695
- this.unlockedMnemonic = null;
696
- }
697
- }
698
- catch {
699
- await this.clearUnlockedSession();
700
- return false;
701
- }
702
- }
703
- if (!this.unlockedPrivateKey || !this.unlockedSessionKey) {
704
- await this.clearUnlockedSession();
781
+ // A restarted worker holds no secrets yet. Skipping the await when it
782
+ // does keeps the signer check above and the comparison below in one turn.
783
+ if (!(this.unlockedPrivateKey && this.unlockedSessionKey) &&
784
+ !await this.restoreSessionSecrets(session, generation)) {
705
785
  return false;
706
786
  }
707
- if (!this.unlockedSigner) {
708
- this.unlockedSigner = new Ed25519Signer(this.unlockedPrivateKey);
709
- }
710
- if (this.unlockedSigner.address !== session.publicKey) {
711
- await this.clearUnlockedSession();
787
+ return this.acceptRestoredSession(session, generation);
788
+ }
789
+ async acceptRestoredSession(session, generation) {
790
+ if (generation !== this.sessionGeneration)
712
791
  return false;
792
+ this.unlockedSigner ??= new Ed25519Signer(this.unlockedPrivateKey);
793
+ if (this.unlockedSigner.address !== session.publicKey) {
794
+ return this.discardRestoredSession(generation);
713
795
  }
714
796
  this.unlockedSessionExpiresAt = session.expiresAt;
715
797
  return true;
@@ -721,31 +803,45 @@ export class WalletController {
721
803
  ? expiresAt
722
804
  : now + UNLOCKED_SESSION_TIMEOUT_MS;
723
805
  }
724
- async persistUnlockedSession(expiresAt) {
725
- if (!this.unlockedSigner || !this.unlockedSessionKey) {
726
- throw new ProviderUnauthorizedError("wallet is locked");
806
+ isSessionCurrent(generation, publicKey, sessionKey) {
807
+ return generation === this.sessionGeneration && this.unlockedSigner?.address === publicKey &&
808
+ this.unlockedSessionKey === sessionKey;
809
+ }
810
+ async sessionExpiry(publicKey, expiresAt) {
811
+ const resolved = expiresAt ?? await this.resolveUnlockedSessionExpiry();
812
+ const current = await this.store.loadUnlockedSession();
813
+ return current?.publicKey === publicKey && current.expiresAt > resolved ? current.expiresAt : resolved;
814
+ }
815
+ /** Saves the session it was queued for; false when a lock or new signer overtook it. */
816
+ async saveCurrentSession(generation, publicKey, sessionKey, expiresAt) {
817
+ const nextExpiresAt = await this.sessionExpiry(publicKey, expiresAt);
818
+ if (!this.isSessionCurrent(generation, publicKey, sessionKey))
819
+ return false;
820
+ await this.store.saveUnlockedSession({ publicKey, expiresAt: nextExpiresAt, sessionKey });
821
+ if (!this.isSessionCurrent(generation, publicKey, sessionKey)) {
822
+ // Still inside the session queue: cleanup cannot erase a newer save.
823
+ await this.store.clearUnlockedSession();
824
+ return false;
727
825
  }
728
- const resolvedExpiresAt = expiresAt ?? (await this.resolveUnlockedSessionExpiry());
729
- const currentSession = await this.store.loadUnlockedSession();
730
- const nextExpiresAt = currentSession?.publicKey === this.unlockedSigner.address &&
731
- currentSession.expiresAt > resolvedExpiresAt
732
- ? currentSession.expiresAt
733
- : resolvedExpiresAt;
734
- const session = {
735
- publicKey: this.unlockedSigner.address,
736
- expiresAt: nextExpiresAt,
737
- sessionKey: this.unlockedSessionKey
738
- };
739
- await this.store.saveUnlockedSession(session);
740
826
  this.unlockedSessionExpiresAt = nextExpiresAt;
827
+ return true;
828
+ }
829
+ async writeUnlockedSession(expiresAt) {
830
+ const signer = this.unlockedSigner, sessionKey = this.unlockedSessionKey;
831
+ if (!signer || !sessionKey)
832
+ return false;
833
+ const generation = this.sessionGeneration;
834
+ return this.runAutomaticSendExclusive("wallet-session", () => this.saveCurrentSession(generation, signer.address, sessionKey, expiresAt));
835
+ }
836
+ async persistUnlockedSession(expiresAt) {
837
+ if (!await this.writeUnlockedSession(expiresAt)) {
838
+ throw new ProviderUnauthorizedError("wallet locked or changed during session save");
839
+ }
741
840
  }
742
841
  async clearUnlockedSession() {
743
- this.unlockedPrivateKey = null;
744
- this.unlockedSigner = null;
745
- this.unlockedMnemonic = null;
746
- this.unlockedSessionKey = null;
747
- this.unlockedSessionExpiresAt = null;
748
- await this.store.clearUnlockedSession();
842
+ this.sessionGeneration++;
843
+ this.resetSessionSecrets();
844
+ await this.runAutomaticSendExclusive("wallet-session", () => this.store.clearUnlockedSession());
749
845
  }
750
846
  async expireUnlockedSession() {
751
847
  await this.clearUnlockedSession();
@@ -755,17 +851,32 @@ export class WalletController {
755
851
  }
756
852
  await Promise.allSettled(state.connectedOrigins.map((origin) => this.emitDisconnectLifecycle(origin)));
757
853
  }
758
- async getUnlockedSigner() {
854
+ // Requires an unlocked wallet without counting as user activity: dapp
855
+ // requests must not keep the auto-lock timer from expiring.
856
+ async requireUnlockedSigner() {
759
857
  await this.restoreUnlockedSession();
760
- if (!this.unlockedPrivateKey) {
761
- throw new ProviderUnauthorizedError("wallet is locked");
762
- }
858
+ // The key and its signer are always set and cleared together.
763
859
  if (!this.unlockedSigner) {
764
- this.unlockedSigner = new Ed25519Signer(this.unlockedPrivateKey);
860
+ throw new ProviderUnauthorizedError("wallet is locked");
765
861
  }
766
- await this.persistUnlockedSession();
767
862
  return this.unlockedSigner;
768
863
  }
864
+ async requireSignerForState(state) {
865
+ const signer = await this.requireUnlockedSigner();
866
+ if (signer.address !== state.publicKey) {
867
+ throw new ProviderUnauthorizedError("wallet account changed; review the transaction again");
868
+ }
869
+ return signer;
870
+ }
871
+ /** Record explicit wallet activity: extends an unlocked session's auto-lock timer. */
872
+ async touchUnlockedSession() {
873
+ if (!(await this.restoreUnlockedSession())) {
874
+ return false;
875
+ }
876
+ // A lock or account switch that overtakes the extension queued its own
877
+ // session write behind it: re-read the session that writer leaves.
878
+ return await this.writeUnlockedSession() || this.restoreUnlockedSession();
879
+ }
769
880
  currentClient(state) {
770
881
  const activePreset = this.activeNetworkPreset(state);
771
882
  assertRpcTransportAllowed(state.rpcUrl, activePreset.allowInsecureHttp);
@@ -782,6 +893,7 @@ export class WalletController {
782
893
  const client = this.options.createClient
783
894
  ? this.options.createClient(state)
784
895
  : new XianClient({
896
+ vmProfile: "xian_vm_v2",
785
897
  rpcUrl: state.rpcUrl,
786
898
  dashboardUrl: state.dashboardUrl
787
899
  });
@@ -849,7 +961,7 @@ export class WalletController {
849
961
  return state.accounts;
850
962
  }
851
963
  async sessionKeyForState(state, password) {
852
- return deriveWalletSessionKey(password, state.walletEncryptionSalt);
964
+ return deriveWalletSessionKey(password, state.walletEncryptionSalt, state.walletEncryptionIterations);
853
965
  }
854
966
  async decryptPrivateKeyForState(state, password) {
855
967
  return decryptPrivateKeyWithSessionKey(state.encryptedPrivateKey, await this.sessionKeyForState(state, password));
@@ -926,6 +1038,18 @@ export class WalletController {
926
1038
  displayChainId(preset, resolvedChainId) {
927
1039
  return resolvedChainId ?? preset.chainId;
928
1040
  }
1041
+ /**
1042
+ * The chain the active network's RPC serves, the one every signature is
1043
+ * bound to; refused when the network was configured for another chain.
1044
+ */
1045
+ async signingChainId(state) {
1046
+ const chainId = await this.currentClient(state).getChainId();
1047
+ const configured = this.activeNetworkPreset(state).chainId;
1048
+ if (configured && configured !== chainId) {
1049
+ throw new ProviderChainMismatchError(`the network RPC serves chain ${chainId}, not the configured ${configured}; refusing to sign`);
1050
+ }
1051
+ return chainId;
1052
+ }
929
1053
  async captureApprovalNetworkContext(state, preset) {
930
1054
  const networkState = this.activeNetworkPreset(state).id === preset.id
931
1055
  ? state
@@ -961,11 +1085,7 @@ export class WalletController {
961
1085
  !approval.context.targetNetwork) {
962
1086
  throw new ProviderUnauthorizedError("chain-switch approval has no bound target network; request it again");
963
1087
  }
964
- const current = await this.captureApprovalContext(state);
965
- if (approval.context.account !== current.account ||
966
- !this.approvalNetworkContextsMatch(approval.context.network, current.network)) {
967
- throw new ProviderUnauthorizedError("wallet account or network changed after this request was reviewed");
968
- }
1088
+ await this.assertSigningContext(approval.context, state);
969
1089
  if (approval.context.targetNetwork) {
970
1090
  const targetPreset = state.networkPresets.find((preset) => preset.id === approval.context?.targetNetwork?.presetId);
971
1091
  if (!targetPreset) {
@@ -978,6 +1098,15 @@ export class WalletController {
978
1098
  }
979
1099
  return approval.context;
980
1100
  }
1101
+ async assertSigningContext(context, state) {
1102
+ if (!isApprovalContext(context)) {
1103
+ throw new ProviderUnauthorizedError("wallet signing context is unavailable; review the transaction again");
1104
+ }
1105
+ const current = await this.captureApprovalContext(state);
1106
+ if (context.account !== current.account || !this.approvalNetworkContextsMatch(context.network, current.network)) {
1107
+ throw new ProviderUnauthorizedError("wallet account or network changed after this request was reviewed");
1108
+ }
1109
+ }
981
1110
  networkStatus(preset, resolvedChainId) {
982
1111
  if (!resolvedChainId) {
983
1112
  return "unreachable";
@@ -1069,8 +1198,8 @@ export class WalletController {
1069
1198
  wallet: this.options.wallet
1070
1199
  };
1071
1200
  }
1072
- async persistWalletState(state) {
1073
- await this.store.saveState(normalizeStoredWalletNetworks(state));
1201
+ async persistWalletState(state, replace = false) {
1202
+ await this.store.saveState(normalizeStoredWalletNetworks(state), { replace });
1074
1203
  return this.getPopupState();
1075
1204
  }
1076
1205
  async updateConnectedOrigin(origin, connected, dappMetadata) {
@@ -1136,7 +1265,9 @@ export class WalletController {
1136
1265
  if (!chainId) {
1137
1266
  return null;
1138
1267
  }
1139
- const match = findMatchingXianDappPolicy(state.trustedDappPolicies ?? [], {
1268
+ const match = findMatchingXianDappPolicy(
1269
+ // Rules without a chi cap predate the cap requirement and are not honoured.
1270
+ (state.trustedDappPolicies ?? []).filter((policy) => policy.maxChi != null), {
1140
1271
  origin,
1141
1272
  account,
1142
1273
  chainId,
@@ -1157,6 +1288,10 @@ export class WalletController {
1157
1288
  if (!context?.network.chainId) {
1158
1289
  return null;
1159
1290
  }
1291
+ const chi = parseXianDappAction(approval.record.request)?.chi;
1292
+ if (chi == null || chi === "") {
1293
+ return null;
1294
+ }
1160
1295
  const activeChainId = context.network.chainId;
1161
1296
  return createXianDappPolicyForRequest({
1162
1297
  id: this.createId(),
@@ -1326,9 +1461,9 @@ export class WalletController {
1326
1461
  }
1327
1462
  }
1328
1463
  async prepareTransaction(state, intent) {
1329
- const signer = await this.getUnlockedSigner();
1464
+ const signer = await this.requireSignerForState(state);
1330
1465
  const client = this.currentClient(state);
1331
- const activeChainId = await client.getChainId();
1466
+ const activeChainId = await this.signingChainId(state);
1332
1467
  if (intent.chainId && intent.chainId !== activeChainId) {
1333
1468
  throw new ProviderChainMismatchError("wallet is connected to a different chain");
1334
1469
  }
@@ -1362,9 +1497,9 @@ export class WalletController {
1362
1497
  }
1363
1498
  }
1364
1499
  async sendCallTransaction(state, intent, options) {
1365
- const signer = await this.getUnlockedSigner();
1500
+ const signer = await this.requireSignerForState(state);
1366
1501
  const client = this.currentClient(state);
1367
- const activeChainId = await client.getChainId();
1502
+ const activeChainId = await this.signingChainId(state);
1368
1503
  if (intent.chainId && intent.chainId !== activeChainId) {
1369
1504
  throw new ProviderChainMismatchError("wallet is connected to a different chain");
1370
1505
  }
@@ -1395,8 +1530,8 @@ export class WalletController {
1395
1530
  });
1396
1531
  }
1397
1532
  async signPreparedTransaction(state, tx) {
1398
- const signer = await this.getUnlockedSigner();
1399
- const activeChainId = await this.currentClient(state).getChainId();
1533
+ const signer = await this.requireSignerForState(state);
1534
+ const activeChainId = await this.signingChainId(state);
1400
1535
  if (tx.payload.sender !== signer.address) {
1401
1536
  throw new ProviderUnauthorizedError("transaction sender does not match the active wallet");
1402
1537
  }
@@ -1414,7 +1549,9 @@ export class WalletController {
1414
1549
  this.preparedSendsInFlight.add(scope);
1415
1550
  try {
1416
1551
  const signedTx = await this.signPreparedTransaction(state, tx);
1417
- return await this.currentClient(state).broadcastTx(signedTx, options);
1552
+ await options?.onPreparedTransaction?.(prepareTransaction(signedTx, "xian_vm_v2"));
1553
+ const { onPreparedTransaction: _observer, ...broadcastOptions } = options ?? {};
1554
+ return await this.currentClient(state).broadcastTx(signedTx, broadcastOptions);
1418
1555
  }
1419
1556
  finally {
1420
1557
  this.preparedSendsInFlight.delete(scope);
@@ -1425,9 +1562,18 @@ export class WalletController {
1425
1562
  if (approval) {
1426
1563
  await this.assertApprovalContext(approval, state);
1427
1564
  }
1565
+ const onPreparedTransaction = approval ? async (prepared) => {
1566
+ const pending = await this.store.loadRequestState(approval.requestId);
1567
+ if (!pending || pending.status !== "pending" || !pending.execution) {
1568
+ throw new Error("approval execution is no longer active");
1569
+ }
1570
+ await this.store.saveRequestState({ ...pending, execution: {
1571
+ ...pending.execution, txHash: prepared.txHash, signedJson: prepared.json
1572
+ } });
1573
+ } : undefined;
1428
1574
  switch (request.method) {
1429
1575
  case "xian_requestAccounts": {
1430
- await this.getUnlockedSigner();
1576
+ await this.requireUnlockedSigner();
1431
1577
  const chainId = this.displayChainId(this.activeNetworkPreset(state), await this.safeGetChainId(state));
1432
1578
  const nextState = await this.updateConnectedOrigin(origin, true, dappMetadata);
1433
1579
  await this.emitConnectionLifecycle(origin, chainId ?? "unknown", nextState.publicKey);
@@ -1435,7 +1581,7 @@ export class WalletController {
1435
1581
  }
1436
1582
  case "xian_switchChain": {
1437
1583
  this.requireConnectedOrigin(state, origin);
1438
- await this.getUnlockedSigner();
1584
+ await this.requireUnlockedSigner();
1439
1585
  const { chainId } = firstParamObject(request.params);
1440
1586
  const requestedChainId = typeof chainId === "string" ? chainId.trim() : "";
1441
1587
  if (!requestedChainId) {
@@ -1460,7 +1606,7 @@ export class WalletController {
1460
1606
  }
1461
1607
  case "xian_watchAsset": {
1462
1608
  this.requireConnectedOrigin(state, origin);
1463
- await this.getUnlockedSigner();
1609
+ await this.requireUnlockedSigner();
1464
1610
  const assetRequest = firstParamObject(request.params);
1465
1611
  const asset = normalizeTrackedAsset(assetRequest.options);
1466
1612
  await this.updateWatchedAssets((assets) => {
@@ -1472,7 +1618,7 @@ export class WalletController {
1472
1618
  }
1473
1619
  case "xian_signMessage": {
1474
1620
  this.requireConnectedOrigin(state, origin);
1475
- const signer = await this.getUnlockedSigner();
1621
+ const signer = await this.requireSignerForState(state);
1476
1622
  const { message } = firstParamObject(request.params);
1477
1623
  if (typeof message !== "string") {
1478
1624
  throw new TypeError("xian_signMessage requires a message string");
@@ -1480,7 +1626,7 @@ export class WalletController {
1480
1626
  if (isUnsafeMessageToSign(message)) {
1481
1627
  throw new Error("refusing to sign a transaction-like payload as a plain message");
1482
1628
  }
1483
- const chainId = await this.currentClient(state).getChainId();
1629
+ const chainId = await this.signingChainId(state);
1484
1630
  return signer.signMessage(createXianMessageSigningPayload({
1485
1631
  account: state.publicKey,
1486
1632
  chainId,
@@ -1489,15 +1635,16 @@ export class WalletController {
1489
1635
  }
1490
1636
  case "xian_signTransaction": {
1491
1637
  this.requireConnectedOrigin(state, origin);
1492
- await this.getUnlockedSigner();
1638
+ await this.requireUnlockedSigner();
1493
1639
  const { tx } = firstParamObject(request.params);
1494
1640
  return this.signPreparedTransaction(state, tx);
1495
1641
  }
1496
1642
  case "xian_sendTransaction": {
1497
1643
  this.requireConnectedOrigin(state, origin);
1498
- await this.getUnlockedSigner();
1644
+ await this.requireUnlockedSigner();
1499
1645
  const { tx, mode, waitForTx, timeoutMs, pollIntervalMs } = firstParamObject(request.params);
1500
1646
  return this.sendPreparedTransaction(state, tx, {
1647
+ onPreparedTransaction,
1501
1648
  mode: mode,
1502
1649
  waitForTx: waitForTx,
1503
1650
  timeoutMs: timeoutMs,
@@ -1506,9 +1653,10 @@ export class WalletController {
1506
1653
  }
1507
1654
  case "xian_sendCall": {
1508
1655
  this.requireConnectedOrigin(state, origin);
1509
- await this.getUnlockedSigner();
1656
+ await this.requireUnlockedSigner();
1510
1657
  const { intent, mode, waitForTx, timeoutMs, pollIntervalMs } = firstParamObject(request.params);
1511
1658
  return this.sendCallTransaction(state, intent, {
1659
+ onPreparedTransaction,
1512
1660
  mode: mode,
1513
1661
  waitForTx: waitForTx,
1514
1662
  timeoutMs: timeoutMs,
@@ -1522,6 +1670,7 @@ export class WalletController {
1522
1670
  async fulfillRequest(requestState, result) {
1523
1671
  const nextState = {
1524
1672
  ...requestState,
1673
+ execution: (await this.store.loadRequestState(requestState.requestId))?.execution,
1525
1674
  updatedAt: this.now(),
1526
1675
  status: "fulfilled",
1527
1676
  result,
@@ -1539,9 +1688,18 @@ export class WalletController {
1539
1688
  };
1540
1689
  }
1541
1690
  async rejectRequest(requestState, error) {
1691
+ const execution = (await this.store.loadRequestState(requestState.requestId))?.execution;
1542
1692
  const serialized = this.serializeError(error);
1693
+ if (execution?.txHash) {
1694
+ serialized.data = {
1695
+ ...(isRecord(serialized.data) ? serialized.data : {}),
1696
+ txHash: execution.txHash,
1697
+ submissionMayHaveOccurred: true
1698
+ };
1699
+ }
1543
1700
  const nextState = {
1544
1701
  ...requestState,
1702
+ execution,
1545
1703
  updatedAt: this.now(),
1546
1704
  status: "rejected",
1547
1705
  result: undefined,
@@ -1558,52 +1716,79 @@ export class WalletController {
1558
1716
  error: serialized
1559
1717
  };
1560
1718
  }
1719
+ /**
1720
+ * The request with the chi the wallet supplies for its simulated cost;
1721
+ * unchanged when it cannot be estimated. A call whose simulation fails is
1722
+ * refused: sending it would execute, fail and pay its chi.
1723
+ */
1561
1724
  async requestWithEstimatedSendCallChi(request, account) {
1562
- if (request.method !== "xian_sendCall" || !account) {
1725
+ const target = sendCallIntentWithoutChi(request);
1726
+ if (!account || !target) {
1563
1727
  return request;
1564
1728
  }
1565
- const firstParam = firstParamObject(request.params);
1566
- const intent = isRecord(firstParam.intent) ? firstParam.intent : null;
1567
- if (!intent ||
1568
- intent.chi != null ||
1569
- intent.chiSupplied != null ||
1570
- typeof intent.contract !== "string" ||
1571
- typeof intent.function !== "string") {
1729
+ const kwargs = isRecord(target.intent.kwargs) ? target.intent.kwargs : {};
1730
+ const estimate = await this.estimateSendCall(account, target.intent, kwargs);
1731
+ if (estimate === null) {
1572
1732
  return request;
1573
1733
  }
1574
- const kwargs = isRecord(intent.kwargs) ? intent.kwargs : {};
1734
+ assertSimulationSucceeds(estimate.simulation);
1735
+ const chi = supplyFor(estimate.estimated);
1736
+ return chi === null
1737
+ ? request
1738
+ : withSendCallIntent(request, target.firstParam, { ...target.intent, kwargs, chi });
1739
+ }
1740
+ /** The simulated chi of a send-call whose site chose the chi, or null. */
1741
+ async estimateSiteChosenChi(request, account) {
1742
+ const target = sendCallIntentWithSiteChi(request);
1743
+ if (!account || !target) {
1744
+ return null;
1745
+ }
1746
+ const kwargs = isRecord(target.intent.kwargs) ? target.intent.kwargs : {};
1747
+ const estimate = await this.estimateSendCall(account, target.intent, kwargs);
1748
+ return estimate?.estimated ?? null;
1749
+ }
1750
+ /** The simulation of a send-call, or null when it cannot be run. */
1751
+ async estimateSendCall(account, intent, kwargs) {
1575
1752
  try {
1576
1753
  const state = this.requireStoredWallet(await this.loadWalletState());
1577
- const estimated = await this.currentClient(state).estimateChi({
1754
+ return await this.currentClient(state).estimateChi({
1578
1755
  sender: account,
1579
1756
  contract: intent.contract,
1580
1757
  function: intent.function,
1581
1758
  kwargs
1582
1759
  });
1583
- if (!Number.isFinite(estimated.estimated) || estimated.estimated <= 0) {
1584
- return request;
1585
- }
1586
- const nextFirstParam = {
1587
- ...firstParam,
1588
- intent: {
1589
- ...intent,
1590
- kwargs,
1591
- chi: estimated.estimated
1592
- }
1593
- };
1594
- return {
1595
- ...request,
1596
- params: Array.isArray(request.params)
1597
- ? [nextFirstParam, ...request.params.slice(1)]
1598
- : nextFirstParam
1599
- };
1600
1760
  }
1601
1761
  catch {
1602
- return request;
1762
+ return null;
1603
1763
  }
1604
1764
  }
1765
+ async assertApprovalCapacity(origin, method) {
1766
+ const kind = approvalKindFromMethod(method);
1767
+ const pending = (await this.store.listApprovalStates()).filter((approval) => approval.record.origin === origin);
1768
+ const pendingOfKind = pending.filter((approval) => kind === "connect" ? approval.record.kind === "connect" : approval.record.kind !== "connect").length;
1769
+ const limit = kind === "connect" ? 1 : MAX_PENDING_APPROVALS_PER_ORIGIN;
1770
+ if (pendingOfKind >= limit) {
1771
+ throw new ProviderRequestPendingError(kind === "connect"
1772
+ ? "a connect request from this site is already pending"
1773
+ : "too many requests from this site are already pending");
1774
+ }
1775
+ }
1776
+ /** Rejects a request while it is being started. */
1777
+ async rejectStart(requestState, error) {
1778
+ const rejected = await this.rejectRequest(requestState, error);
1779
+ if (rejected.status !== "rejected") {
1780
+ throw new Error("approval request rejection did not settle correctly");
1781
+ }
1782
+ return rejected;
1783
+ }
1605
1784
  async createApprovalRequest(requestState, context) {
1606
- const request = await this.requestWithEstimatedSendCallChi(requestState.request, context.account);
1785
+ let request;
1786
+ try {
1787
+ request = await this.requestWithEstimatedSendCallChi(requestState.request, context.account);
1788
+ }
1789
+ catch (error) {
1790
+ return this.rejectStart(requestState, error);
1791
+ }
1607
1792
  const record = {
1608
1793
  id: this.createId(),
1609
1794
  origin: requestState.origin,
@@ -1620,7 +1805,8 @@ export class WalletController {
1620
1805
  account: context.account,
1621
1806
  chainId: context.network.chainId,
1622
1807
  targetChainId: context.targetNetwork?.chainId,
1623
- chiRate
1808
+ chiRate,
1809
+ estimatedChi: await this.estimateSiteChosenChi(request, context.account)
1624
1810
  });
1625
1811
  const approval = {
1626
1812
  id: record.id,
@@ -1646,14 +1832,7 @@ export class WalletController {
1646
1832
  }
1647
1833
  catch (error) {
1648
1834
  await this.store.deleteApprovalState(record.id);
1649
- const rejected = await this.rejectRequest({
1650
- ...requestState,
1651
- approvalId: record.id
1652
- }, error);
1653
- if (rejected.status !== "rejected") {
1654
- throw new Error("approval request rejection did not settle correctly");
1655
- }
1656
- return rejected;
1835
+ return this.rejectStart({ ...requestState, approvalId: record.id }, error);
1657
1836
  }
1658
1837
  }
1659
1838
  async executeImmediateRequest(state, origin, request, dappMetadata) {
@@ -1665,7 +1844,7 @@ export class WalletController {
1665
1844
  };
1666
1845
  case "xian_requestAccounts": {
1667
1846
  const walletState = this.requireStoredWallet(state);
1668
- await this.getUnlockedSigner();
1847
+ await this.requireUnlockedSigner();
1669
1848
  if (walletState.connectedOrigins.includes(origin)) {
1670
1849
  const nextState = await this.updateConnectedOrigin(origin, true, dappMetadata);
1671
1850
  return {
@@ -1714,7 +1893,7 @@ export class WalletController {
1714
1893
  case "xian_switchChain": {
1715
1894
  const walletState = this.requireStoredWallet(state);
1716
1895
  this.requireConnectedOrigin(walletState, origin);
1717
- await this.getUnlockedSigner();
1896
+ await this.requireUnlockedSigner();
1718
1897
  const { chainId } = firstParamObject(request.params);
1719
1898
  const requestedChainId = typeof chainId === "string" ? chainId.trim() : "";
1720
1899
  if (!requestedChainId) {
@@ -1743,7 +1922,7 @@ export class WalletController {
1743
1922
  case "xian_watchAsset": {
1744
1923
  const walletState = this.requireStoredWallet(state);
1745
1924
  this.requireConnectedOrigin(walletState, origin);
1746
- await this.getUnlockedSigner();
1925
+ await this.requireUnlockedSigner();
1747
1926
  return {
1748
1927
  kind: "approval",
1749
1928
  context: await this.captureApprovalContext(walletState)
@@ -1752,7 +1931,7 @@ export class WalletController {
1752
1931
  case "xian_signMessage": {
1753
1932
  const walletState = this.requireStoredWallet(state);
1754
1933
  this.requireConnectedOrigin(walletState, origin);
1755
- await this.getUnlockedSigner();
1934
+ await this.requireUnlockedSigner();
1756
1935
  return {
1757
1936
  kind: "approval",
1758
1937
  context: await this.captureApprovalContext(walletState)
@@ -1761,7 +1940,7 @@ export class WalletController {
1761
1940
  case "xian_prepareTransaction": {
1762
1941
  const walletState = this.requireStoredWallet(state);
1763
1942
  this.requireConnectedOrigin(walletState, origin);
1764
- await this.getUnlockedSigner();
1943
+ await this.requireUnlockedSigner();
1765
1944
  const { intent } = firstParamObject(request.params);
1766
1945
  return {
1767
1946
  kind: "result",
@@ -1773,7 +1952,7 @@ export class WalletController {
1773
1952
  case "xian_sendCall": {
1774
1953
  const walletState = this.requireStoredWallet(state);
1775
1954
  this.requireConnectedOrigin(walletState, origin);
1776
- await this.getUnlockedSigner();
1955
+ await this.requireUnlockedSigner();
1777
1956
  const activeChainId = this.displayChainId(this.activeNetworkPreset(walletState), await this.safeGetChainId(walletState));
1778
1957
  const trustedResult = await this.maybeExecuteTrustedDappRequest(walletState, origin, request, walletState.publicKey, activeChainId);
1779
1958
  if (trustedResult) {
@@ -1948,12 +2127,14 @@ export class WalletController {
1948
2127
  async estimateTransactionChi(request) {
1949
2128
  const state = this.requireStoredWallet(await this.loadWalletState());
1950
2129
  const client = this.currentClient(state);
1951
- return client.estimateChi({
2130
+ const { estimated, simulation } = await client.estimateChi({
1952
2131
  sender: state.publicKey,
1953
2132
  contract: request.contract,
1954
2133
  function: request.function,
1955
2134
  kwargs: request.kwargs
1956
2135
  });
2136
+ assertSimulationSucceeds(simulation);
2137
+ return { estimated, supply: chiToSupply(estimated) };
1957
2138
  }
1958
2139
  async getChiRate() {
1959
2140
  const state = await this.loadWalletState();
@@ -1973,13 +2154,17 @@ export class WalletController {
1973
2154
  }
1974
2155
  async sendDirectTransaction(intent) {
1975
2156
  const state = this.requireStoredWallet(await this.loadWalletState());
1976
- await this.getUnlockedSigner();
2157
+ await this.requireUnlockedSigner();
2158
+ await this.assertSigningContext(intent.reviewedContext, state);
1977
2159
  return this.sendCallTransaction(state, {
1978
2160
  contract: intent.contract,
1979
2161
  function: intent.function,
1980
2162
  kwargs: intent.kwargs,
1981
2163
  chi: intent.chi
1982
- }, { mode: "commit" });
2164
+ },
2165
+ // Wait for the receipt: it carries an execution failure such as
2166
+ // "Out of chi.", which a commit-mode submission does not surface.
2167
+ { mode: "checktx", waitForTx: true });
1983
2168
  }
1984
2169
  async getDexSnapshot() {
1985
2170
  const state = this.requireStoredWallet(await this.loadWalletState());
@@ -2069,9 +2254,9 @@ export class WalletController {
2069
2254
  id,
2070
2255
  token0,
2071
2256
  token1,
2072
- reserve0: numberFromUnknown(reserve0),
2073
- reserve1: numberFromUnknown(reserve1),
2074
- totalSupply: numberFromUnknown(totalSupply),
2257
+ reserve0: String(reserve0 ?? 0),
2258
+ reserve1: String(reserve1 ?? 0),
2259
+ totalSupply: String(totalSupply ?? 0),
2075
2260
  blockTimestampLast: blockTimestampLast == null ? null : String(blockTimestampLast),
2076
2261
  creationTime: creationTime == null ? null : String(creationTime)
2077
2262
  };
@@ -2136,8 +2321,8 @@ export class WalletController {
2136
2321
  logoUrl: metadata.logoUrl,
2137
2322
  logoSvg: metadata.logoSvg,
2138
2323
  precision,
2139
- balance: numberFromUnknown(balanceRaw),
2140
- allowance: numberFromUnknown(allowanceRaw),
2324
+ balance: String(balanceRaw ?? 0),
2325
+ allowance: String(allowanceRaw ?? 0),
2141
2326
  feeOnTransfer: feeOnTransferRaw === true
2142
2327
  };
2143
2328
  }
@@ -2247,7 +2432,7 @@ export class WalletController {
2247
2432
  createWithMnemonic: input.createWithMnemonic
2248
2433
  });
2249
2434
  const signer = new Ed25519Signer(secret.privateKey);
2250
- const { walletEncryptionSalt, sessionKey } = await createWalletSessionKey(input.password);
2435
+ const { walletEncryptionSalt, walletEncryptionIterations, sessionKey } = await createWalletSessionKey(input.password);
2251
2436
  const encryptedPrivateKey = await encryptPrivateKeyWithSessionKey(secret.privateKey, sessionKey);
2252
2437
  const encryptedMnemonic = secret.mnemonic
2253
2438
  ? await encryptMnemonicWithSessionKey(secret.mnemonic, sessionKey)
@@ -2298,6 +2483,7 @@ export class WalletController {
2298
2483
  encryptedPrivateKey,
2299
2484
  encryptedMnemonic,
2300
2485
  walletEncryptionSalt,
2486
+ walletEncryptionIterations,
2301
2487
  seedSource: secret.seedSource,
2302
2488
  mnemonicWordCount: secret.mnemonicWordCount,
2303
2489
  accounts: [initialAccount],
@@ -2324,33 +2510,56 @@ export class WalletController {
2324
2510
  connectedDappMetadata: {},
2325
2511
  connectedOrigins: [],
2326
2512
  createdAt: new Date().toISOString()
2327
- });
2513
+ }, true);
2328
2514
  return {
2329
2515
  popupState,
2330
2516
  generatedMnemonic: secret.generatedMnemonic,
2331
2517
  importedSeedSource: secret.seedSource
2332
2518
  };
2333
2519
  }
2520
+ async upgradeWalletEncryption(state, password, sessionKey, generation) {
2521
+ const iterations = state.walletEncryptionIterations ?? LEGACY_WALLET_KDF_ITERATIONS;
2522
+ if (iterations >= WALLET_KDF_ITERATIONS || !this.store.replaceState) {
2523
+ return { state, sessionKey, generation };
2524
+ }
2525
+ const upgraded = await reencryptWalletState(state, password, sessionKey);
2526
+ if (generation !== this.sessionGeneration)
2527
+ throw new Error("wallet locked during unlock");
2528
+ generation++;
2529
+ await this.clearUnlockedSession();
2530
+ if (generation !== this.sessionGeneration)
2531
+ throw new Error("wallet locked during unlock");
2532
+ if (!await this.store.replaceState(state, upgraded.state)) {
2533
+ throw new Error("wallet changed during unlock; please retry");
2534
+ }
2535
+ return { ...upgraded, generation };
2536
+ }
2334
2537
  async unlockWallet(password) {
2335
- const state = this.requireStoredWallet(await this.loadWalletState());
2336
- const sessionKey = await this.sessionKeyForState(state, password);
2538
+ let generation = this.sessionGeneration;
2539
+ let state = this.requireStoredWallet(await this.loadWalletState());
2540
+ let sessionKey = await this.sessionKeyForState(state, password);
2337
2541
  const privateKey = await decryptPrivateKeyWithSessionKey(state.encryptedPrivateKey, sessionKey);
2338
2542
  const signer = new Ed25519Signer(privateKey);
2339
2543
  if (signer.address !== state.publicKey) {
2340
2544
  throw new Error("decrypted private key does not match stored wallet");
2341
2545
  }
2342
- this.unlockedPrivateKey = privateKey;
2343
- this.unlockedSigner = signer;
2344
- this.unlockedSessionKey = sessionKey;
2546
+ ({ state, sessionKey, generation } = await this.upgradeWalletEncryption(state, password, sessionKey, generation));
2345
2547
  // Decrypt mnemonic into session for account switching
2548
+ let mnemonic = null;
2346
2549
  if (state.encryptedMnemonic) {
2347
2550
  try {
2348
- this.unlockedMnemonic = await decryptMnemonicWithSessionKey(state.encryptedMnemonic, sessionKey);
2551
+ mnemonic = await decryptMnemonicWithSessionKey(state.encryptedMnemonic, sessionKey);
2349
2552
  }
2350
2553
  catch {
2351
- this.unlockedMnemonic = null;
2554
+ mnemonic = null;
2352
2555
  }
2353
2556
  }
2557
+ if (generation !== this.sessionGeneration)
2558
+ throw new Error("wallet locked during unlock");
2559
+ this.unlockedPrivateKey = privateKey;
2560
+ this.unlockedSigner = signer;
2561
+ this.unlockedSessionKey = sessionKey;
2562
+ this.unlockedMnemonic = mnemonic;
2354
2563
  await this.persistUnlockedSession();
2355
2564
  void this.notifyUnlockedOrigins(state);
2356
2565
  return this.getPopupState();
@@ -2408,7 +2617,7 @@ export class WalletController {
2408
2617
  else {
2409
2618
  throw new Error("backup must contain a mnemonic or private key");
2410
2619
  }
2411
- const { walletEncryptionSalt, sessionKey } = await createWalletSessionKey(password);
2620
+ const { walletEncryptionSalt, walletEncryptionIterations, sessionKey } = await createWalletSessionKey(password);
2412
2621
  const nowIso = new Date().toISOString();
2413
2622
  const encryptedMnemonic = mnemonic
2414
2623
  ? await encryptMnemonicWithSessionKey(mnemonic, sessionKey)
@@ -2475,6 +2684,7 @@ export class WalletController {
2475
2684
  encryptedPrivateKey: activeAccount.encryptedPrivateKey,
2476
2685
  encryptedMnemonic,
2477
2686
  walletEncryptionSalt,
2687
+ walletEncryptionIterations,
2478
2688
  seedSource: decryptedBackup.type,
2479
2689
  mnemonicWordCount: mnemonic ? mnemonic.split(" ").length : undefined,
2480
2690
  accounts,
@@ -2490,7 +2700,7 @@ export class WalletController {
2490
2700
  connectedDappMetadata: {},
2491
2701
  connectedOrigins: [],
2492
2702
  createdAt: nowIso
2493
- });
2703
+ }, true);
2494
2704
  return this.getPopupState();
2495
2705
  }
2496
2706
  async saveShieldedWalletSnapshot(stateSnapshot, label) {
@@ -2840,6 +3050,11 @@ export class WalletController {
2840
3050
  }
2841
3051
  };
2842
3052
  }
3053
+ if (existing.status === "pending" && existing.execution && !isApprovalResolutionActive(this.store, existing.approvalId)) {
3054
+ const recovered = await this.getProviderRequestStatus(requestId);
3055
+ if (recovered.status === "rejected")
3056
+ return recovered;
3057
+ }
2843
3058
  if (existing.status === "pending") {
2844
3059
  return {
2845
3060
  status: "pending",
@@ -2879,7 +3094,10 @@ export class WalletController {
2879
3094
  }
2880
3095
  return fulfilled;
2881
3096
  }
2882
- return this.createApprovalRequest(requestState, immediate.context);
3097
+ return await this.runAutomaticSendExclusive(`approvals\u0000${origin}`, async () => {
3098
+ await this.assertApprovalCapacity(origin, request.method);
3099
+ return this.createApprovalRequest(requestState, immediate.context);
3100
+ });
2883
3101
  }
2884
3102
  catch (error) {
2885
3103
  const rejected = await this.rejectRequest(requestState, error);
@@ -2901,6 +3119,13 @@ export class WalletController {
2901
3119
  status: "not_found"
2902
3120
  };
2903
3121
  }
3122
+ if (state.status === "pending" && state.execution && !isApprovalResolutionActive(this.store, state.approvalId)) {
3123
+ return this.rejectRequest(state, {
3124
+ name: "SubmissionInterruptedError",
3125
+ message: "Wallet execution was interrupted; check the transaction before creating another request",
3126
+ data: { txHash: state.execution.txHash, submissionMayHaveOccurred: true }
3127
+ });
3128
+ }
2904
3129
  if (state.status === "pending") {
2905
3130
  return {
2906
3131
  status: "pending",
@@ -2945,16 +3170,37 @@ export class WalletController {
2945
3170
  });
2946
3171
  }
2947
3172
  async resolveApproval(approvalId, approved, options) {
2948
- const approval = await this.store.loadApprovalState(approvalId);
3173
+ const release = beginApprovalResolution(this.store, approvalId);
3174
+ if (!release)
3175
+ return null;
3176
+ try {
3177
+ await this.touchUnlockedSession();
3178
+ return await this.resolveClaimedApproval(approvalId, approved, options);
3179
+ }
3180
+ finally {
3181
+ release();
3182
+ }
3183
+ }
3184
+ async resolveClaimedApproval(approvalId, approved, options) {
3185
+ const claimed = await this.store.claimApprovalExecution?.(approvalId, this.now());
3186
+ if (this.store.claimApprovalExecution && !claimed)
3187
+ return null;
3188
+ const approval = claimed?.approval ?? await this.store.loadApprovalState(approvalId);
2949
3189
  if (!approval) {
2950
- throw new Error("approval request not found");
3190
+ return null;
2951
3191
  }
2952
- const requestState = await this.store.loadRequestState(approval.requestId);
3192
+ const requestState = claimed?.request ?? await this.store.loadRequestState(approval.requestId);
2953
3193
  if (!requestState) {
2954
3194
  await this.store.deleteApprovalState(approval.id);
2955
3195
  throw new Error("approval request is no longer active");
2956
3196
  }
2957
- await this.store.deleteApprovalState(approvalId);
3197
+ if (!claimed) {
3198
+ if (requestState.status !== "pending" || requestState.execution)
3199
+ return null;
3200
+ requestState.execution = { startedAt: this.now() };
3201
+ await this.store.saveRequestState(requestState);
3202
+ await this.store.deleteApprovalState(approvalId);
3203
+ }
2958
3204
  if (!approved) {
2959
3205
  await this.rejectRequest(requestState, new ProviderUnauthorizedError("user rejected the request"));
2960
3206
  return null;
@@ -2977,16 +3223,27 @@ export class WalletController {
2977
3223
  }
2978
3224
  }
2979
3225
  async dismissApproval(approvalId, reason = new ProviderUnauthorizedError("approval dismissed")) {
2980
- const approval = await this.store.loadApprovalState(approvalId);
2981
- if (!approval) {
3226
+ const release = beginApprovalResolution(this.store, approvalId);
3227
+ if (!release)
2982
3228
  return false;
3229
+ try {
3230
+ const claimed = await this.store.claimApprovalExecution?.(approvalId, this.now());
3231
+ if (this.store.claimApprovalExecution && !claimed)
3232
+ return false;
3233
+ const approval = claimed?.approval ?? await this.store.loadApprovalState(approvalId);
3234
+ if (!approval)
3235
+ return false;
3236
+ const requestState = claimed?.request ?? await this.store.loadRequestState(approval.requestId);
3237
+ if (!claimed && requestState?.execution)
3238
+ return false;
3239
+ await this.store.deleteApprovalState(approvalId);
3240
+ if (requestState)
3241
+ await this.rejectRequest(requestState, reason);
3242
+ return true;
2983
3243
  }
2984
- const requestState = await this.store.loadRequestState(approval.requestId);
2985
- await this.store.deleteApprovalState(approvalId);
2986
- if (requestState) {
2987
- await this.rejectRequest(requestState, reason);
3244
+ finally {
3245
+ release();
2988
3246
  }
2989
- return true;
2990
3247
  }
2991
3248
  async handleProviderRequest(origin, request) {
2992
3249
  const requestId = this.createId();