@xian-tech/wallet-core 0.4.3 → 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.
@@ -1,12 +1,21 @@
1
1
  import { beginApprovalResolution, isApprovalResolutionActive } from "./approval-execution.js";
2
- import { createXianMessageSigningPayload, prepareTransaction, Ed25519Signer, shieldedSyncHintFromViewingPrivateKey, XianClient } from "@xian-tech/client";
3
- import { createXianDappPolicyForRequest, findMatchingXianDappPolicy, ProviderChainMismatchError, ProviderUnauthorizedError, ProviderUnsupportedMethodError, xianDappPoliciesHaveSameScope } from "@xian-tech/provider";
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";
4
4
  import { approvalKindFromMethod, buildApprovalView } from "./approvals.js";
5
+ import { assertSimulationSucceeds } from "./simulation.js";
5
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";
6
7
  import { assertRpcTransportAllowed } from "./network.js";
7
- 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";
8
10
  const SAFE_CHAIN_ID_LOOKUP_TIMEOUT_MS = 2_000;
9
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
+ }
10
19
  const MAX_DAPP_METADATA_TEXT_LENGTH = 120;
11
20
  const MAX_DAPP_ICON_URL_LENGTH = 2048;
12
21
  const DEX_ROUTER_CONTRACT = "con_dex";
@@ -46,6 +55,50 @@ function parseIntentNumber(value, fieldName) {
46
55
  }
47
56
  throw new TypeError(`${fieldName} must be a non-negative integer`);
48
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
+ }
49
102
  function trimOptionalString(value) {
50
103
  const trimmed = value?.trim();
51
104
  return trimmed ? trimmed : undefined;
@@ -659,58 +712,86 @@ export class WalletController {
659
712
  message: String(error)
660
713
  };
661
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
+ }
662
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;
663
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();
664
773
  if (!session) {
665
- this.unlockedPrivateKey = null;
666
- this.unlockedSigner = null;
667
- this.unlockedMnemonic = null;
668
- this.unlockedSessionKey = null;
669
- this.unlockedSessionExpiresAt = null;
774
+ this.resetSessionSecrets();
670
775
  return false;
671
776
  }
672
777
  if (session.expiresAt <= this.now()) {
673
778
  await this.expireUnlockedSession();
674
779
  return false;
675
780
  }
676
- if ((!this.unlockedPrivateKey || !this.unlockedSessionKey) && session.sessionKey) {
677
- const state = await this.loadWalletState();
678
- if (!state || state.publicKey !== session.publicKey) {
679
- await this.clearUnlockedSession();
680
- return false;
681
- }
682
- try {
683
- const privateKey = await decryptPrivateKeyWithSessionKey(state.encryptedPrivateKey, session.sessionKey);
684
- const signer = new Ed25519Signer(privateKey);
685
- if (signer.address !== session.publicKey) {
686
- await this.clearUnlockedSession();
687
- return false;
688
- }
689
- this.unlockedPrivateKey = privateKey;
690
- this.unlockedSigner = signer;
691
- this.unlockedSessionKey = session.sessionKey;
692
- if (state.encryptedMnemonic) {
693
- this.unlockedMnemonic = await decryptMnemonicWithSessionKey(state.encryptedMnemonic, session.sessionKey).catch(() => null);
694
- }
695
- else {
696
- this.unlockedMnemonic = null;
697
- }
698
- }
699
- catch {
700
- await this.clearUnlockedSession();
701
- return false;
702
- }
703
- }
704
- if (!this.unlockedPrivateKey || !this.unlockedSessionKey) {
705
- 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)) {
706
785
  return false;
707
786
  }
708
- if (!this.unlockedSigner) {
709
- this.unlockedSigner = new Ed25519Signer(this.unlockedPrivateKey);
710
- }
711
- if (this.unlockedSigner.address !== session.publicKey) {
712
- await this.clearUnlockedSession();
787
+ return this.acceptRestoredSession(session, generation);
788
+ }
789
+ async acceptRestoredSession(session, generation) {
790
+ if (generation !== this.sessionGeneration)
713
791
  return false;
792
+ this.unlockedSigner ??= new Ed25519Signer(this.unlockedPrivateKey);
793
+ if (this.unlockedSigner.address !== session.publicKey) {
794
+ return this.discardRestoredSession(generation);
714
795
  }
715
796
  this.unlockedSessionExpiresAt = session.expiresAt;
716
797
  return true;
@@ -722,31 +803,45 @@ export class WalletController {
722
803
  ? expiresAt
723
804
  : now + UNLOCKED_SESSION_TIMEOUT_MS;
724
805
  }
725
- async persistUnlockedSession(expiresAt) {
726
- if (!this.unlockedSigner || !this.unlockedSessionKey) {
727
- 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;
728
825
  }
729
- const resolvedExpiresAt = expiresAt ?? (await this.resolveUnlockedSessionExpiry());
730
- const currentSession = await this.store.loadUnlockedSession();
731
- const nextExpiresAt = currentSession?.publicKey === this.unlockedSigner.address &&
732
- currentSession.expiresAt > resolvedExpiresAt
733
- ? currentSession.expiresAt
734
- : resolvedExpiresAt;
735
- const session = {
736
- publicKey: this.unlockedSigner.address,
737
- expiresAt: nextExpiresAt,
738
- sessionKey: this.unlockedSessionKey
739
- };
740
- await this.store.saveUnlockedSession(session);
741
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
+ }
742
840
  }
743
841
  async clearUnlockedSession() {
744
- this.unlockedPrivateKey = null;
745
- this.unlockedSigner = null;
746
- this.unlockedMnemonic = null;
747
- this.unlockedSessionKey = null;
748
- this.unlockedSessionExpiresAt = null;
749
- await this.store.clearUnlockedSession();
842
+ this.sessionGeneration++;
843
+ this.resetSessionSecrets();
844
+ await this.runAutomaticSendExclusive("wallet-session", () => this.store.clearUnlockedSession());
750
845
  }
751
846
  async expireUnlockedSession() {
752
847
  await this.clearUnlockedSession();
@@ -756,17 +851,32 @@ export class WalletController {
756
851
  }
757
852
  await Promise.allSettled(state.connectedOrigins.map((origin) => this.emitDisconnectLifecycle(origin)));
758
853
  }
759
- 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() {
760
857
  await this.restoreUnlockedSession();
761
- if (!this.unlockedPrivateKey) {
762
- throw new ProviderUnauthorizedError("wallet is locked");
763
- }
858
+ // The key and its signer are always set and cleared together.
764
859
  if (!this.unlockedSigner) {
765
- this.unlockedSigner = new Ed25519Signer(this.unlockedPrivateKey);
860
+ throw new ProviderUnauthorizedError("wallet is locked");
766
861
  }
767
- await this.persistUnlockedSession();
768
862
  return this.unlockedSigner;
769
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
+ }
770
880
  currentClient(state) {
771
881
  const activePreset = this.activeNetworkPreset(state);
772
882
  assertRpcTransportAllowed(state.rpcUrl, activePreset.allowInsecureHttp);
@@ -783,6 +893,7 @@ export class WalletController {
783
893
  const client = this.options.createClient
784
894
  ? this.options.createClient(state)
785
895
  : new XianClient({
896
+ vmProfile: "xian_vm_v2",
786
897
  rpcUrl: state.rpcUrl,
787
898
  dashboardUrl: state.dashboardUrl
788
899
  });
@@ -850,7 +961,7 @@ export class WalletController {
850
961
  return state.accounts;
851
962
  }
852
963
  async sessionKeyForState(state, password) {
853
- return deriveWalletSessionKey(password, state.walletEncryptionSalt);
964
+ return deriveWalletSessionKey(password, state.walletEncryptionSalt, state.walletEncryptionIterations);
854
965
  }
855
966
  async decryptPrivateKeyForState(state, password) {
856
967
  return decryptPrivateKeyWithSessionKey(state.encryptedPrivateKey, await this.sessionKeyForState(state, password));
@@ -927,6 +1038,18 @@ export class WalletController {
927
1038
  displayChainId(preset, resolvedChainId) {
928
1039
  return resolvedChainId ?? preset.chainId;
929
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
+ }
930
1053
  async captureApprovalNetworkContext(state, preset) {
931
1054
  const networkState = this.activeNetworkPreset(state).id === preset.id
932
1055
  ? state
@@ -962,11 +1085,7 @@ export class WalletController {
962
1085
  !approval.context.targetNetwork) {
963
1086
  throw new ProviderUnauthorizedError("chain-switch approval has no bound target network; request it again");
964
1087
  }
965
- const current = await this.captureApprovalContext(state);
966
- if (approval.context.account !== current.account ||
967
- !this.approvalNetworkContextsMatch(approval.context.network, current.network)) {
968
- throw new ProviderUnauthorizedError("wallet account or network changed after this request was reviewed");
969
- }
1088
+ await this.assertSigningContext(approval.context, state);
970
1089
  if (approval.context.targetNetwork) {
971
1090
  const targetPreset = state.networkPresets.find((preset) => preset.id === approval.context?.targetNetwork?.presetId);
972
1091
  if (!targetPreset) {
@@ -979,6 +1098,15 @@ export class WalletController {
979
1098
  }
980
1099
  return approval.context;
981
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
+ }
982
1110
  networkStatus(preset, resolvedChainId) {
983
1111
  if (!resolvedChainId) {
984
1112
  return "unreachable";
@@ -1070,8 +1198,8 @@ export class WalletController {
1070
1198
  wallet: this.options.wallet
1071
1199
  };
1072
1200
  }
1073
- async persistWalletState(state) {
1074
- await this.store.saveState(normalizeStoredWalletNetworks(state));
1201
+ async persistWalletState(state, replace = false) {
1202
+ await this.store.saveState(normalizeStoredWalletNetworks(state), { replace });
1075
1203
  return this.getPopupState();
1076
1204
  }
1077
1205
  async updateConnectedOrigin(origin, connected, dappMetadata) {
@@ -1137,7 +1265,9 @@ export class WalletController {
1137
1265
  if (!chainId) {
1138
1266
  return null;
1139
1267
  }
1140
- 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), {
1141
1271
  origin,
1142
1272
  account,
1143
1273
  chainId,
@@ -1158,6 +1288,10 @@ export class WalletController {
1158
1288
  if (!context?.network.chainId) {
1159
1289
  return null;
1160
1290
  }
1291
+ const chi = parseXianDappAction(approval.record.request)?.chi;
1292
+ if (chi == null || chi === "") {
1293
+ return null;
1294
+ }
1161
1295
  const activeChainId = context.network.chainId;
1162
1296
  return createXianDappPolicyForRequest({
1163
1297
  id: this.createId(),
@@ -1327,9 +1461,9 @@ export class WalletController {
1327
1461
  }
1328
1462
  }
1329
1463
  async prepareTransaction(state, intent) {
1330
- const signer = await this.getUnlockedSigner();
1464
+ const signer = await this.requireSignerForState(state);
1331
1465
  const client = this.currentClient(state);
1332
- const activeChainId = await client.getChainId();
1466
+ const activeChainId = await this.signingChainId(state);
1333
1467
  if (intent.chainId && intent.chainId !== activeChainId) {
1334
1468
  throw new ProviderChainMismatchError("wallet is connected to a different chain");
1335
1469
  }
@@ -1363,9 +1497,9 @@ export class WalletController {
1363
1497
  }
1364
1498
  }
1365
1499
  async sendCallTransaction(state, intent, options) {
1366
- const signer = await this.getUnlockedSigner();
1500
+ const signer = await this.requireSignerForState(state);
1367
1501
  const client = this.currentClient(state);
1368
- const activeChainId = await client.getChainId();
1502
+ const activeChainId = await this.signingChainId(state);
1369
1503
  if (intent.chainId && intent.chainId !== activeChainId) {
1370
1504
  throw new ProviderChainMismatchError("wallet is connected to a different chain");
1371
1505
  }
@@ -1396,8 +1530,8 @@ export class WalletController {
1396
1530
  });
1397
1531
  }
1398
1532
  async signPreparedTransaction(state, tx) {
1399
- const signer = await this.getUnlockedSigner();
1400
- const activeChainId = await this.currentClient(state).getChainId();
1533
+ const signer = await this.requireSignerForState(state);
1534
+ const activeChainId = await this.signingChainId(state);
1401
1535
  if (tx.payload.sender !== signer.address) {
1402
1536
  throw new ProviderUnauthorizedError("transaction sender does not match the active wallet");
1403
1537
  }
@@ -1415,7 +1549,7 @@ export class WalletController {
1415
1549
  this.preparedSendsInFlight.add(scope);
1416
1550
  try {
1417
1551
  const signedTx = await this.signPreparedTransaction(state, tx);
1418
- await options?.onPreparedTransaction?.(prepareTransaction(signedTx));
1552
+ await options?.onPreparedTransaction?.(prepareTransaction(signedTx, "xian_vm_v2"));
1419
1553
  const { onPreparedTransaction: _observer, ...broadcastOptions } = options ?? {};
1420
1554
  return await this.currentClient(state).broadcastTx(signedTx, broadcastOptions);
1421
1555
  }
@@ -1439,7 +1573,7 @@ export class WalletController {
1439
1573
  } : undefined;
1440
1574
  switch (request.method) {
1441
1575
  case "xian_requestAccounts": {
1442
- await this.getUnlockedSigner();
1576
+ await this.requireUnlockedSigner();
1443
1577
  const chainId = this.displayChainId(this.activeNetworkPreset(state), await this.safeGetChainId(state));
1444
1578
  const nextState = await this.updateConnectedOrigin(origin, true, dappMetadata);
1445
1579
  await this.emitConnectionLifecycle(origin, chainId ?? "unknown", nextState.publicKey);
@@ -1447,7 +1581,7 @@ export class WalletController {
1447
1581
  }
1448
1582
  case "xian_switchChain": {
1449
1583
  this.requireConnectedOrigin(state, origin);
1450
- await this.getUnlockedSigner();
1584
+ await this.requireUnlockedSigner();
1451
1585
  const { chainId } = firstParamObject(request.params);
1452
1586
  const requestedChainId = typeof chainId === "string" ? chainId.trim() : "";
1453
1587
  if (!requestedChainId) {
@@ -1472,7 +1606,7 @@ export class WalletController {
1472
1606
  }
1473
1607
  case "xian_watchAsset": {
1474
1608
  this.requireConnectedOrigin(state, origin);
1475
- await this.getUnlockedSigner();
1609
+ await this.requireUnlockedSigner();
1476
1610
  const assetRequest = firstParamObject(request.params);
1477
1611
  const asset = normalizeTrackedAsset(assetRequest.options);
1478
1612
  await this.updateWatchedAssets((assets) => {
@@ -1484,7 +1618,7 @@ export class WalletController {
1484
1618
  }
1485
1619
  case "xian_signMessage": {
1486
1620
  this.requireConnectedOrigin(state, origin);
1487
- const signer = await this.getUnlockedSigner();
1621
+ const signer = await this.requireSignerForState(state);
1488
1622
  const { message } = firstParamObject(request.params);
1489
1623
  if (typeof message !== "string") {
1490
1624
  throw new TypeError("xian_signMessage requires a message string");
@@ -1492,7 +1626,7 @@ export class WalletController {
1492
1626
  if (isUnsafeMessageToSign(message)) {
1493
1627
  throw new Error("refusing to sign a transaction-like payload as a plain message");
1494
1628
  }
1495
- const chainId = await this.currentClient(state).getChainId();
1629
+ const chainId = await this.signingChainId(state);
1496
1630
  return signer.signMessage(createXianMessageSigningPayload({
1497
1631
  account: state.publicKey,
1498
1632
  chainId,
@@ -1501,13 +1635,13 @@ export class WalletController {
1501
1635
  }
1502
1636
  case "xian_signTransaction": {
1503
1637
  this.requireConnectedOrigin(state, origin);
1504
- await this.getUnlockedSigner();
1638
+ await this.requireUnlockedSigner();
1505
1639
  const { tx } = firstParamObject(request.params);
1506
1640
  return this.signPreparedTransaction(state, tx);
1507
1641
  }
1508
1642
  case "xian_sendTransaction": {
1509
1643
  this.requireConnectedOrigin(state, origin);
1510
- await this.getUnlockedSigner();
1644
+ await this.requireUnlockedSigner();
1511
1645
  const { tx, mode, waitForTx, timeoutMs, pollIntervalMs } = firstParamObject(request.params);
1512
1646
  return this.sendPreparedTransaction(state, tx, {
1513
1647
  onPreparedTransaction,
@@ -1519,7 +1653,7 @@ export class WalletController {
1519
1653
  }
1520
1654
  case "xian_sendCall": {
1521
1655
  this.requireConnectedOrigin(state, origin);
1522
- await this.getUnlockedSigner();
1656
+ await this.requireUnlockedSigner();
1523
1657
  const { intent, mode, waitForTx, timeoutMs, pollIntervalMs } = firstParamObject(request.params);
1524
1658
  return this.sendCallTransaction(state, intent, {
1525
1659
  onPreparedTransaction,
@@ -1582,52 +1716,79 @@ export class WalletController {
1582
1716
  error: serialized
1583
1717
  };
1584
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
+ */
1585
1724
  async requestWithEstimatedSendCallChi(request, account) {
1586
- if (request.method !== "xian_sendCall" || !account) {
1725
+ const target = sendCallIntentWithoutChi(request);
1726
+ if (!account || !target) {
1587
1727
  return request;
1588
1728
  }
1589
- const firstParam = firstParamObject(request.params);
1590
- const intent = isRecord(firstParam.intent) ? firstParam.intent : null;
1591
- if (!intent ||
1592
- intent.chi != null ||
1593
- intent.chiSupplied != null ||
1594
- typeof intent.contract !== "string" ||
1595
- 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) {
1596
1732
  return request;
1597
1733
  }
1598
- 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) {
1599
1752
  try {
1600
1753
  const state = this.requireStoredWallet(await this.loadWalletState());
1601
- const estimated = await this.currentClient(state).estimateChi({
1754
+ return await this.currentClient(state).estimateChi({
1602
1755
  sender: account,
1603
1756
  contract: intent.contract,
1604
1757
  function: intent.function,
1605
1758
  kwargs
1606
1759
  });
1607
- if (!Number.isFinite(estimated.estimated) || estimated.estimated <= 0) {
1608
- return request;
1609
- }
1610
- const nextFirstParam = {
1611
- ...firstParam,
1612
- intent: {
1613
- ...intent,
1614
- kwargs,
1615
- chi: estimated.estimated
1616
- }
1617
- };
1618
- return {
1619
- ...request,
1620
- params: Array.isArray(request.params)
1621
- ? [nextFirstParam, ...request.params.slice(1)]
1622
- : nextFirstParam
1623
- };
1624
1760
  }
1625
1761
  catch {
1626
- return request;
1762
+ return null;
1627
1763
  }
1628
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
+ }
1629
1784
  async createApprovalRequest(requestState, context) {
1630
- 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
+ }
1631
1792
  const record = {
1632
1793
  id: this.createId(),
1633
1794
  origin: requestState.origin,
@@ -1644,7 +1805,8 @@ export class WalletController {
1644
1805
  account: context.account,
1645
1806
  chainId: context.network.chainId,
1646
1807
  targetChainId: context.targetNetwork?.chainId,
1647
- chiRate
1808
+ chiRate,
1809
+ estimatedChi: await this.estimateSiteChosenChi(request, context.account)
1648
1810
  });
1649
1811
  const approval = {
1650
1812
  id: record.id,
@@ -1670,14 +1832,7 @@ export class WalletController {
1670
1832
  }
1671
1833
  catch (error) {
1672
1834
  await this.store.deleteApprovalState(record.id);
1673
- const rejected = await this.rejectRequest({
1674
- ...requestState,
1675
- approvalId: record.id
1676
- }, error);
1677
- if (rejected.status !== "rejected") {
1678
- throw new Error("approval request rejection did not settle correctly");
1679
- }
1680
- return rejected;
1835
+ return this.rejectStart({ ...requestState, approvalId: record.id }, error);
1681
1836
  }
1682
1837
  }
1683
1838
  async executeImmediateRequest(state, origin, request, dappMetadata) {
@@ -1689,7 +1844,7 @@ export class WalletController {
1689
1844
  };
1690
1845
  case "xian_requestAccounts": {
1691
1846
  const walletState = this.requireStoredWallet(state);
1692
- await this.getUnlockedSigner();
1847
+ await this.requireUnlockedSigner();
1693
1848
  if (walletState.connectedOrigins.includes(origin)) {
1694
1849
  const nextState = await this.updateConnectedOrigin(origin, true, dappMetadata);
1695
1850
  return {
@@ -1738,7 +1893,7 @@ export class WalletController {
1738
1893
  case "xian_switchChain": {
1739
1894
  const walletState = this.requireStoredWallet(state);
1740
1895
  this.requireConnectedOrigin(walletState, origin);
1741
- await this.getUnlockedSigner();
1896
+ await this.requireUnlockedSigner();
1742
1897
  const { chainId } = firstParamObject(request.params);
1743
1898
  const requestedChainId = typeof chainId === "string" ? chainId.trim() : "";
1744
1899
  if (!requestedChainId) {
@@ -1767,7 +1922,7 @@ export class WalletController {
1767
1922
  case "xian_watchAsset": {
1768
1923
  const walletState = this.requireStoredWallet(state);
1769
1924
  this.requireConnectedOrigin(walletState, origin);
1770
- await this.getUnlockedSigner();
1925
+ await this.requireUnlockedSigner();
1771
1926
  return {
1772
1927
  kind: "approval",
1773
1928
  context: await this.captureApprovalContext(walletState)
@@ -1776,7 +1931,7 @@ export class WalletController {
1776
1931
  case "xian_signMessage": {
1777
1932
  const walletState = this.requireStoredWallet(state);
1778
1933
  this.requireConnectedOrigin(walletState, origin);
1779
- await this.getUnlockedSigner();
1934
+ await this.requireUnlockedSigner();
1780
1935
  return {
1781
1936
  kind: "approval",
1782
1937
  context: await this.captureApprovalContext(walletState)
@@ -1785,7 +1940,7 @@ export class WalletController {
1785
1940
  case "xian_prepareTransaction": {
1786
1941
  const walletState = this.requireStoredWallet(state);
1787
1942
  this.requireConnectedOrigin(walletState, origin);
1788
- await this.getUnlockedSigner();
1943
+ await this.requireUnlockedSigner();
1789
1944
  const { intent } = firstParamObject(request.params);
1790
1945
  return {
1791
1946
  kind: "result",
@@ -1797,7 +1952,7 @@ export class WalletController {
1797
1952
  case "xian_sendCall": {
1798
1953
  const walletState = this.requireStoredWallet(state);
1799
1954
  this.requireConnectedOrigin(walletState, origin);
1800
- await this.getUnlockedSigner();
1955
+ await this.requireUnlockedSigner();
1801
1956
  const activeChainId = this.displayChainId(this.activeNetworkPreset(walletState), await this.safeGetChainId(walletState));
1802
1957
  const trustedResult = await this.maybeExecuteTrustedDappRequest(walletState, origin, request, walletState.publicKey, activeChainId);
1803
1958
  if (trustedResult) {
@@ -1972,12 +2127,14 @@ export class WalletController {
1972
2127
  async estimateTransactionChi(request) {
1973
2128
  const state = this.requireStoredWallet(await this.loadWalletState());
1974
2129
  const client = this.currentClient(state);
1975
- return client.estimateChi({
2130
+ const { estimated, simulation } = await client.estimateChi({
1976
2131
  sender: state.publicKey,
1977
2132
  contract: request.contract,
1978
2133
  function: request.function,
1979
2134
  kwargs: request.kwargs
1980
2135
  });
2136
+ assertSimulationSucceeds(simulation);
2137
+ return { estimated, supply: chiToSupply(estimated) };
1981
2138
  }
1982
2139
  async getChiRate() {
1983
2140
  const state = await this.loadWalletState();
@@ -1997,13 +2154,17 @@ export class WalletController {
1997
2154
  }
1998
2155
  async sendDirectTransaction(intent) {
1999
2156
  const state = this.requireStoredWallet(await this.loadWalletState());
2000
- await this.getUnlockedSigner();
2157
+ await this.requireUnlockedSigner();
2158
+ await this.assertSigningContext(intent.reviewedContext, state);
2001
2159
  return this.sendCallTransaction(state, {
2002
2160
  contract: intent.contract,
2003
2161
  function: intent.function,
2004
2162
  kwargs: intent.kwargs,
2005
2163
  chi: intent.chi
2006
- }, { 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 });
2007
2168
  }
2008
2169
  async getDexSnapshot() {
2009
2170
  const state = this.requireStoredWallet(await this.loadWalletState());
@@ -2093,9 +2254,9 @@ export class WalletController {
2093
2254
  id,
2094
2255
  token0,
2095
2256
  token1,
2096
- reserve0: numberFromUnknown(reserve0),
2097
- reserve1: numberFromUnknown(reserve1),
2098
- totalSupply: numberFromUnknown(totalSupply),
2257
+ reserve0: String(reserve0 ?? 0),
2258
+ reserve1: String(reserve1 ?? 0),
2259
+ totalSupply: String(totalSupply ?? 0),
2099
2260
  blockTimestampLast: blockTimestampLast == null ? null : String(blockTimestampLast),
2100
2261
  creationTime: creationTime == null ? null : String(creationTime)
2101
2262
  };
@@ -2160,8 +2321,8 @@ export class WalletController {
2160
2321
  logoUrl: metadata.logoUrl,
2161
2322
  logoSvg: metadata.logoSvg,
2162
2323
  precision,
2163
- balance: numberFromUnknown(balanceRaw),
2164
- allowance: numberFromUnknown(allowanceRaw),
2324
+ balance: String(balanceRaw ?? 0),
2325
+ allowance: String(allowanceRaw ?? 0),
2165
2326
  feeOnTransfer: feeOnTransferRaw === true
2166
2327
  };
2167
2328
  }
@@ -2271,7 +2432,7 @@ export class WalletController {
2271
2432
  createWithMnemonic: input.createWithMnemonic
2272
2433
  });
2273
2434
  const signer = new Ed25519Signer(secret.privateKey);
2274
- const { walletEncryptionSalt, sessionKey } = await createWalletSessionKey(input.password);
2435
+ const { walletEncryptionSalt, walletEncryptionIterations, sessionKey } = await createWalletSessionKey(input.password);
2275
2436
  const encryptedPrivateKey = await encryptPrivateKeyWithSessionKey(secret.privateKey, sessionKey);
2276
2437
  const encryptedMnemonic = secret.mnemonic
2277
2438
  ? await encryptMnemonicWithSessionKey(secret.mnemonic, sessionKey)
@@ -2322,6 +2483,7 @@ export class WalletController {
2322
2483
  encryptedPrivateKey,
2323
2484
  encryptedMnemonic,
2324
2485
  walletEncryptionSalt,
2486
+ walletEncryptionIterations,
2325
2487
  seedSource: secret.seedSource,
2326
2488
  mnemonicWordCount: secret.mnemonicWordCount,
2327
2489
  accounts: [initialAccount],
@@ -2348,33 +2510,56 @@ export class WalletController {
2348
2510
  connectedDappMetadata: {},
2349
2511
  connectedOrigins: [],
2350
2512
  createdAt: new Date().toISOString()
2351
- });
2513
+ }, true);
2352
2514
  return {
2353
2515
  popupState,
2354
2516
  generatedMnemonic: secret.generatedMnemonic,
2355
2517
  importedSeedSource: secret.seedSource
2356
2518
  };
2357
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
+ }
2358
2537
  async unlockWallet(password) {
2359
- const state = this.requireStoredWallet(await this.loadWalletState());
2360
- 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);
2361
2541
  const privateKey = await decryptPrivateKeyWithSessionKey(state.encryptedPrivateKey, sessionKey);
2362
2542
  const signer = new Ed25519Signer(privateKey);
2363
2543
  if (signer.address !== state.publicKey) {
2364
2544
  throw new Error("decrypted private key does not match stored wallet");
2365
2545
  }
2366
- this.unlockedPrivateKey = privateKey;
2367
- this.unlockedSigner = signer;
2368
- this.unlockedSessionKey = sessionKey;
2546
+ ({ state, sessionKey, generation } = await this.upgradeWalletEncryption(state, password, sessionKey, generation));
2369
2547
  // Decrypt mnemonic into session for account switching
2548
+ let mnemonic = null;
2370
2549
  if (state.encryptedMnemonic) {
2371
2550
  try {
2372
- this.unlockedMnemonic = await decryptMnemonicWithSessionKey(state.encryptedMnemonic, sessionKey);
2551
+ mnemonic = await decryptMnemonicWithSessionKey(state.encryptedMnemonic, sessionKey);
2373
2552
  }
2374
2553
  catch {
2375
- this.unlockedMnemonic = null;
2554
+ mnemonic = null;
2376
2555
  }
2377
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;
2378
2563
  await this.persistUnlockedSession();
2379
2564
  void this.notifyUnlockedOrigins(state);
2380
2565
  return this.getPopupState();
@@ -2432,7 +2617,7 @@ export class WalletController {
2432
2617
  else {
2433
2618
  throw new Error("backup must contain a mnemonic or private key");
2434
2619
  }
2435
- const { walletEncryptionSalt, sessionKey } = await createWalletSessionKey(password);
2620
+ const { walletEncryptionSalt, walletEncryptionIterations, sessionKey } = await createWalletSessionKey(password);
2436
2621
  const nowIso = new Date().toISOString();
2437
2622
  const encryptedMnemonic = mnemonic
2438
2623
  ? await encryptMnemonicWithSessionKey(mnemonic, sessionKey)
@@ -2499,6 +2684,7 @@ export class WalletController {
2499
2684
  encryptedPrivateKey: activeAccount.encryptedPrivateKey,
2500
2685
  encryptedMnemonic,
2501
2686
  walletEncryptionSalt,
2687
+ walletEncryptionIterations,
2502
2688
  seedSource: decryptedBackup.type,
2503
2689
  mnemonicWordCount: mnemonic ? mnemonic.split(" ").length : undefined,
2504
2690
  accounts,
@@ -2514,7 +2700,7 @@ export class WalletController {
2514
2700
  connectedDappMetadata: {},
2515
2701
  connectedOrigins: [],
2516
2702
  createdAt: nowIso
2517
- });
2703
+ }, true);
2518
2704
  return this.getPopupState();
2519
2705
  }
2520
2706
  async saveShieldedWalletSnapshot(stateSnapshot, label) {
@@ -2908,7 +3094,10 @@ export class WalletController {
2908
3094
  }
2909
3095
  return fulfilled;
2910
3096
  }
2911
- 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
+ });
2912
3101
  }
2913
3102
  catch (error) {
2914
3103
  const rejected = await this.rejectRequest(requestState, error);
@@ -2985,6 +3174,7 @@ export class WalletController {
2985
3174
  if (!release)
2986
3175
  return null;
2987
3176
  try {
3177
+ await this.touchUnlockedSession();
2988
3178
  return await this.resolveClaimedApproval(approvalId, approved, options);
2989
3179
  }
2990
3180
  finally {