@xian-tech/wallet-core 0.3.8-beta.3 → 0.4.1

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,7 +1,8 @@
1
- import { Ed25519Signer, shieldedSyncHintFromViewingPrivateKey, XianClient } from "@xian-tech/client";
2
- import { createXianDappPolicyForRequest, findMatchingXianDappPolicy, ProviderChainMismatchError, ProviderUnauthorizedError, ProviderUnsupportedMethodError } from "@xian-tech/provider";
1
+ import { createXianMessageSigningPayload, Ed25519Signer, shieldedSyncHintFromViewingPrivateKey, XianClient } from "@xian-tech/client";
2
+ import { createXianDappPolicyForRequest, findMatchingXianDappPolicy, ProviderChainMismatchError, ProviderUnauthorizedError, ProviderUnsupportedMethodError, xianDappPoliciesHaveSameScope } from "@xian-tech/provider";
3
3
  import { approvalKindFromMethod, buildApprovalView } from "./approvals.js";
4
4
  import { DEFAULT_NETWORK_PRESETS, DEFAULT_DASHBOARD_URL, DEFAULT_RPC_URL, LOCAL_NETWORK_PRESET_NAME, DEFAULT_WALLET_CAPABILITIES, LOCAL_NETWORK_PRESET_ID, UNLOCKED_SESSION_TIMEOUT_MS } from "./constants.js";
5
+ import { assertRpcTransportAllowed } from "./network.js";
5
6
  import { createWalletSessionKey, decryptSecretTextWithSessionKey, createWalletSecret, decryptMnemonicWithSessionKey, decryptPrivateKeyWithSessionKey, decryptWalletBackup, deriveWalletSessionKey, derivePrivateKeyFromMnemonic, encryptSecretTextWithSessionKey, encryptMnemonicWithSessionKey, encryptPrivateKeyWithSessionKey, encryptWalletBackupPayload, isUnsafeMessageToSign } from "./crypto.js";
6
7
  const SAFE_CHAIN_ID_LOOKUP_TIMEOUT_MS = 2_000;
7
8
  const TRUSTED_DAPP_POLICY_TTL_MS = 30 * 24 * 60 * 60 * 1000;
@@ -48,32 +49,6 @@ function trimOptionalString(value) {
48
49
  const trimmed = value?.trim();
49
50
  return trimmed ? trimmed : undefined;
50
51
  }
51
- function isLoopbackHttpUrl(value) {
52
- try {
53
- const url = new URL(value);
54
- return (url.protocol === "http:" &&
55
- (url.hostname === "localhost" ||
56
- url.hostname === "::1" ||
57
- /^127(?:\.\d{1,3}){3}$/.test(url.hostname)));
58
- }
59
- catch {
60
- return false;
61
- }
62
- }
63
- function assertRpcTransportAllowed(rpcUrl, allowInsecureHttp) {
64
- let parsed;
65
- try {
66
- parsed = new URL(rpcUrl);
67
- }
68
- catch {
69
- throw new TypeError("network preset rpcUrl must be a valid URL");
70
- }
71
- if (parsed.protocol === "http:" &&
72
- !allowInsecureHttp &&
73
- !isLoopbackHttpUrl(rpcUrl)) {
74
- throw new Error("HTTP RPC URLs are disabled for this network. Enable HTTP data transfers only for endpoints you trust.");
75
- }
76
- }
77
52
  function trimOptionalIndexedString(value) {
78
53
  const trimmed = value?.trim();
79
54
  if (!trimmed) {
@@ -142,6 +117,24 @@ function isMissingContractResult(value) {
142
117
  function isRecord(value) {
143
118
  return typeof value === "object" && value != null;
144
119
  }
120
+ function isApprovalNetworkContext(value) {
121
+ return (isRecord(value) &&
122
+ typeof value.presetId === "string" &&
123
+ value.presetId.length > 0 &&
124
+ typeof value.rpcUrl === "string" &&
125
+ value.rpcUrl.length > 0 &&
126
+ (value.configuredChainId == null ||
127
+ typeof value.configuredChainId === "string") &&
128
+ (value.chainId == null || typeof value.chainId === "string"));
129
+ }
130
+ function isApprovalContext(value) {
131
+ return (isRecord(value) &&
132
+ typeof value.account === "string" &&
133
+ value.account.length > 0 &&
134
+ isApprovalNetworkContext(value.network) &&
135
+ (value.targetNetwork == null ||
136
+ isApprovalNetworkContext(value.targetNetwork)));
137
+ }
145
138
  function readExportDecoratorFlag(value) {
146
139
  if (typeof value === "string") {
147
140
  return value === "export";
@@ -240,6 +233,7 @@ function normalizeTrustedDappPolicies(value) {
240
233
  typeof entry.maxChi === "string"
241
234
  ? entry.maxChi
242
235
  : undefined,
236
+ argumentScope: entry.argumentScope === "any" ? "any" : "exact",
243
237
  kwargs: isRecord(entry.kwargs) ? entry.kwargs : undefined,
244
238
  label: trimNullableString(entry.label) ?? undefined,
245
239
  createdAt: entry.createdAt,
@@ -531,6 +525,15 @@ function updateAssetNetworkStateInWallet(state, networkId, contract, update) {
531
525
  changed: true
532
526
  };
533
527
  }
528
+ function normalizeApprovalTrustScope(trust) {
529
+ if (trust === true) {
530
+ return "exact";
531
+ }
532
+ if (trust === "exact" || trust === "any") {
533
+ return trust;
534
+ }
535
+ return null;
536
+ }
534
537
  function removeAssetNetworkStateFromWallet(state, contract) {
535
538
  const currentStates = normalizeAssetNetworkStates(state.assetNetworkStates);
536
539
  let changed = false;
@@ -547,15 +550,6 @@ function removeAssetNetworkStateFromWallet(state, contract) {
547
550
  }));
548
551
  return changed ? { ...state, assetNetworkStates } : state;
549
552
  }
550
- function sameTrustedDappPolicyScope(left, right) {
551
- return (left.origin === right.origin &&
552
- left.account === right.account &&
553
- left.chainId === right.chainId &&
554
- left.contract === right.contract &&
555
- left.function === right.function &&
556
- left.methods.length === right.methods.length &&
557
- left.methods.every((method) => right.methods.includes(method)));
558
- }
559
553
  function parseShieldedWalletSnapshot(stateSnapshot) {
560
554
  let decoded;
561
555
  try {
@@ -624,6 +618,9 @@ function hydrateError(error) {
624
618
  export class WalletController {
625
619
  options;
626
620
  requestWaiters = new Map();
621
+ clients = new Map();
622
+ automaticSendTails = new Map();
623
+ preparedSendsInFlight = new Set();
627
624
  unlockedPrivateKey = null;
628
625
  unlockedSigner = null;
629
626
  unlockedSessionKey = null;
@@ -772,13 +769,24 @@ export class WalletController {
772
769
  currentClient(state) {
773
770
  const activePreset = this.activeNetworkPreset(state);
774
771
  assertRpcTransportAllowed(state.rpcUrl, activePreset.allowInsecureHttp);
775
- if (this.options.createClient) {
776
- return this.options.createClient(state);
777
- }
778
- return new XianClient({
779
- rpcUrl: state.rpcUrl,
780
- dashboardUrl: state.dashboardUrl
781
- });
772
+ const cacheKey = JSON.stringify([
773
+ activePreset.id,
774
+ state.rpcUrl,
775
+ state.dashboardUrl ?? null,
776
+ activePreset.allowInsecureHttp === true
777
+ ]);
778
+ const cached = this.clients.get(cacheKey);
779
+ if (cached) {
780
+ return cached;
781
+ }
782
+ const client = this.options.createClient
783
+ ? this.options.createClient(state)
784
+ : new XianClient({
785
+ rpcUrl: state.rpcUrl,
786
+ dashboardUrl: state.dashboardUrl
787
+ });
788
+ this.clients.set(cacheKey, client);
789
+ return client;
782
790
  }
783
791
  requireStoredWallet(state) {
784
792
  if (!state) {
@@ -918,6 +926,58 @@ export class WalletController {
918
926
  displayChainId(preset, resolvedChainId) {
919
927
  return resolvedChainId ?? preset.chainId;
920
928
  }
929
+ async captureApprovalNetworkContext(state, preset) {
930
+ const networkState = this.activeNetworkPreset(state).id === preset.id
931
+ ? state
932
+ : this.applyActivePreset(state, preset.id);
933
+ return {
934
+ presetId: preset.id,
935
+ rpcUrl: preset.rpcUrl,
936
+ configuredChainId: preset.chainId,
937
+ chainId: this.displayChainId(preset, await this.safeGetChainId(networkState))
938
+ };
939
+ }
940
+ async captureApprovalContext(state, targetPreset) {
941
+ const activePreset = this.activeNetworkPreset(state);
942
+ return {
943
+ account: state.publicKey,
944
+ network: await this.captureApprovalNetworkContext(state, activePreset),
945
+ targetNetwork: targetPreset
946
+ ? await this.captureApprovalNetworkContext(state, targetPreset)
947
+ : undefined
948
+ };
949
+ }
950
+ approvalNetworkContextsMatch(expected, actual) {
951
+ return (expected.presetId === actual.presetId &&
952
+ expected.rpcUrl === actual.rpcUrl &&
953
+ expected.configuredChainId === actual.configuredChainId &&
954
+ expected.chainId === actual.chainId);
955
+ }
956
+ async assertApprovalContext(approval, state) {
957
+ if (!isApprovalContext(approval.context)) {
958
+ throw new ProviderUnauthorizedError("approval predates wallet context binding; request it again");
959
+ }
960
+ if (approval.record.kind === "switchChain" &&
961
+ !approval.context.targetNetwork) {
962
+ throw new ProviderUnauthorizedError("chain-switch approval has no bound target network; request it again");
963
+ }
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
+ }
969
+ if (approval.context.targetNetwork) {
970
+ const targetPreset = state.networkPresets.find((preset) => preset.id === approval.context?.targetNetwork?.presetId);
971
+ if (!targetPreset) {
972
+ throw new ProviderUnauthorizedError("requested network changed after this request was reviewed");
973
+ }
974
+ const target = await this.captureApprovalNetworkContext(state, targetPreset);
975
+ if (!this.approvalNetworkContextsMatch(approval.context.targetNetwork, target)) {
976
+ throw new ProviderUnauthorizedError("requested network changed after this request was reviewed");
977
+ }
978
+ }
979
+ return approval.context;
980
+ }
921
981
  networkStatus(preset, resolvedChainId) {
922
982
  if (!resolvedChainId) {
923
983
  return "unreachable";
@@ -936,7 +996,7 @@ export class WalletController {
936
996
  if (!nextChainId || nextChainId === previousChainId) {
937
997
  return;
938
998
  }
939
- await Promise.all(state.connectedOrigins.map((origin) => this.broadcastProviderEvent("chainChanged", [nextChainId], origin)));
999
+ await Promise.allSettled(state.connectedOrigins.map((origin) => this.broadcastProviderEvent("chainChanged", [nextChainId], origin)));
940
1000
  }
941
1001
  applyActivePreset(state, presetId) {
942
1002
  const normalized = normalizeStoredWalletNetworks(state);
@@ -1050,7 +1110,7 @@ export class WalletController {
1050
1110
  await this.store.saveState({
1051
1111
  ...state,
1052
1112
  trustedDappPolicies: [
1053
- ...currentPolicies.filter((existing) => !sameTrustedDappPolicyScope(existing, policy)),
1113
+ ...currentPolicies.filter((existing) => !xianDappPoliciesHaveSameScope(existing, policy)),
1054
1114
  policy
1055
1115
  ]
1056
1116
  });
@@ -1092,21 +1152,21 @@ export class WalletController {
1092
1152
  value
1093
1153
  };
1094
1154
  }
1095
- async createTrustedDappPolicyForApproval(approval) {
1096
- const state = this.requireStoredWallet(await this.loadWalletState());
1097
- const activeChainId = approval.view.chainId ??
1098
- this.displayChainId(this.activeNetworkPreset(state), await this.safeGetChainId(state));
1099
- if (!activeChainId) {
1155
+ async createTrustedDappPolicyForApproval(approval, argumentScope) {
1156
+ const context = approval.context;
1157
+ if (!context?.network.chainId) {
1100
1158
  return null;
1101
1159
  }
1160
+ const activeChainId = context.network.chainId;
1102
1161
  return createXianDappPolicyForRequest({
1103
1162
  id: this.createId(),
1104
1163
  origin: approval.record.origin,
1105
- account: state.publicKey,
1164
+ account: context.account,
1106
1165
  chainId: activeChainId,
1107
1166
  request: approval.record.request,
1108
1167
  now: this.now(),
1109
- expiresAt: this.now() + TRUSTED_DAPP_POLICY_TTL_MS
1168
+ expiresAt: this.now() + TRUSTED_DAPP_POLICY_TTL_MS,
1169
+ argumentScope
1110
1170
  });
1111
1171
  }
1112
1172
  async updateWatchedAssets(updater) {
@@ -1282,6 +1342,58 @@ export class WalletController {
1282
1342
  chiSupplied: parseIntentNumber(intent.chiSupplied, "chiSupplied")
1283
1343
  });
1284
1344
  }
1345
+ async runAutomaticSendExclusive(scope, action) {
1346
+ const previous = this.automaticSendTails.get(scope) ?? Promise.resolve();
1347
+ let release;
1348
+ const gate = new Promise((resolve) => {
1349
+ release = resolve;
1350
+ });
1351
+ const tail = previous.then(() => gate);
1352
+ this.automaticSendTails.set(scope, tail);
1353
+ await previous;
1354
+ try {
1355
+ return await action();
1356
+ }
1357
+ finally {
1358
+ release();
1359
+ if (this.automaticSendTails.get(scope) === tail) {
1360
+ this.automaticSendTails.delete(scope);
1361
+ }
1362
+ }
1363
+ }
1364
+ async sendCallTransaction(state, intent, options) {
1365
+ const signer = await this.getUnlockedSigner();
1366
+ const client = this.currentClient(state);
1367
+ const activeChainId = await client.getChainId();
1368
+ if (intent.chainId && intent.chainId !== activeChainId) {
1369
+ throw new ProviderChainMismatchError("wallet is connected to a different chain");
1370
+ }
1371
+ const request = {
1372
+ sender: signer.address,
1373
+ contract: intent.contract,
1374
+ function: intent.function,
1375
+ kwargs: intent.kwargs,
1376
+ signer,
1377
+ chainId: activeChainId,
1378
+ chi: parseIntentNumber(intent.chi, "chi"),
1379
+ chiSupplied: parseIntentNumber(intent.chiSupplied, "chiSupplied"),
1380
+ ...options
1381
+ };
1382
+ // The official client owns nonce release/quarantine semantics. Keeping one
1383
+ // client per network makes that reservation manager effective across
1384
+ // concurrent approvals handled by this controller.
1385
+ if (client.sendTx) {
1386
+ return client.sendTx(request);
1387
+ }
1388
+ // Custom clients used by embedders may not yet expose sendTx. Serialize the
1389
+ // full build/sign/broadcast lifecycle so two automatic sends cannot take the
1390
+ // same network nonce concurrently.
1391
+ const scope = `${activeChainId}\u0000${signer.address}`;
1392
+ return this.runAutomaticSendExclusive(scope, async () => {
1393
+ const tx = await this.prepareTransaction(state, intent);
1394
+ return this.sendPreparedTransaction(state, tx, options);
1395
+ });
1396
+ }
1285
1397
  async signPreparedTransaction(state, tx) {
1286
1398
  const signer = await this.getUnlockedSigner();
1287
1399
  const activeChainId = await this.currentClient(state).getChainId();
@@ -1294,11 +1406,25 @@ export class WalletController {
1294
1406
  return this.currentClient(state).signTx(tx, signer);
1295
1407
  }
1296
1408
  async sendPreparedTransaction(state, tx, options) {
1297
- const signedTx = await this.signPreparedTransaction(state, tx);
1298
- return this.currentClient(state).broadcastTx(signedTx, options);
1409
+ const payload = tx.payload;
1410
+ const scope = `${payload.chain_id}\u0000${payload.sender}\u0000${String(payload.nonce)}`;
1411
+ if (this.preparedSendsInFlight.has(scope)) {
1412
+ throw new ProviderUnauthorizedError("another transaction with this sender, chain, and nonce is already being submitted");
1413
+ }
1414
+ this.preparedSendsInFlight.add(scope);
1415
+ try {
1416
+ const signedTx = await this.signPreparedTransaction(state, tx);
1417
+ return await this.currentClient(state).broadcastTx(signedTx, options);
1418
+ }
1419
+ finally {
1420
+ this.preparedSendsInFlight.delete(scope);
1421
+ }
1299
1422
  }
1300
- async executeApprovedRequest(origin, request, dappMetadata) {
1423
+ async executeApprovedRequest(origin, request, dappMetadata, approval) {
1301
1424
  const state = this.requireStoredWallet(await this.loadWalletState());
1425
+ if (approval) {
1426
+ await this.assertApprovalContext(approval, state);
1427
+ }
1302
1428
  switch (request.method) {
1303
1429
  case "xian_requestAccounts": {
1304
1430
  await this.getUnlockedSigner();
@@ -1307,6 +1433,31 @@ export class WalletController {
1307
1433
  await this.emitConnectionLifecycle(origin, chainId ?? "unknown", nextState.publicKey);
1308
1434
  return [nextState.publicKey];
1309
1435
  }
1436
+ case "xian_switchChain": {
1437
+ this.requireConnectedOrigin(state, origin);
1438
+ await this.getUnlockedSigner();
1439
+ const { chainId } = firstParamObject(request.params);
1440
+ const requestedChainId = typeof chainId === "string" ? chainId.trim() : "";
1441
+ if (!requestedChainId) {
1442
+ throw new TypeError("xian_switchChain requires a chainId string");
1443
+ }
1444
+ const previousChainId = this.displayChainId(this.activeNetworkPreset(state), await this.safeGetChainId(state));
1445
+ if (previousChainId === requestedChainId) {
1446
+ return null;
1447
+ }
1448
+ const targetPreset = state.networkPresets.find((preset) => preset.chainId === requestedChainId);
1449
+ if (!targetPreset) {
1450
+ throw new ProviderChainMismatchError("wallet has no configured network preset for the requested chain");
1451
+ }
1452
+ const nextState = this.applyActivePreset(state, targetPreset.id);
1453
+ const resolvedTargetChainId = this.displayChainId(targetPreset, await this.safeGetChainId(nextState));
1454
+ if (resolvedTargetChainId !== requestedChainId) {
1455
+ throw new ProviderChainMismatchError("configured network RPC reports a different chain");
1456
+ }
1457
+ await this.store.saveState(nextState);
1458
+ await this.emitChainChangedForConnectedOrigins(nextState, previousChainId);
1459
+ return null;
1460
+ }
1310
1461
  case "xian_watchAsset": {
1311
1462
  this.requireConnectedOrigin(state, origin);
1312
1463
  await this.getUnlockedSigner();
@@ -1329,7 +1480,12 @@ export class WalletController {
1329
1480
  if (isUnsafeMessageToSign(message)) {
1330
1481
  throw new Error("refusing to sign a transaction-like payload as a plain message");
1331
1482
  }
1332
- return signer.signMessage(message);
1483
+ const chainId = await this.currentClient(state).getChainId();
1484
+ return signer.signMessage(createXianMessageSigningPayload({
1485
+ account: state.publicKey,
1486
+ chainId,
1487
+ message
1488
+ }));
1333
1489
  }
1334
1490
  case "xian_signTransaction": {
1335
1491
  this.requireConnectedOrigin(state, origin);
@@ -1352,8 +1508,7 @@ export class WalletController {
1352
1508
  this.requireConnectedOrigin(state, origin);
1353
1509
  await this.getUnlockedSigner();
1354
1510
  const { intent, mode, waitForTx, timeoutMs, pollIntervalMs } = firstParamObject(request.params);
1355
- const tx = await this.prepareTransaction(state, intent);
1356
- return this.sendPreparedTransaction(state, tx, {
1511
+ return this.sendCallTransaction(state, intent, {
1357
1512
  mode: mode,
1358
1513
  waitForTx: waitForTx,
1359
1514
  timeoutMs: timeoutMs,
@@ -1447,8 +1602,8 @@ export class WalletController {
1447
1602
  return request;
1448
1603
  }
1449
1604
  }
1450
- async createApprovalRequest(requestState, account, chainId) {
1451
- const request = await this.requestWithEstimatedSendCallChi(requestState.request, account);
1605
+ async createApprovalRequest(requestState, context) {
1606
+ const request = await this.requestWithEstimatedSendCallChi(requestState.request, context.account);
1452
1607
  const record = {
1453
1608
  id: this.createId(),
1454
1609
  origin: requestState.origin,
@@ -1461,12 +1616,18 @@ export class WalletController {
1461
1616
  record.kind === "sendCall"
1462
1617
  ? await this.getChiRate()
1463
1618
  : null;
1464
- const view = buildApprovalView(record, { account, chainId, chiRate });
1619
+ const view = buildApprovalView(record, {
1620
+ account: context.account,
1621
+ chainId: context.network.chainId,
1622
+ targetChainId: context.targetNetwork?.chainId,
1623
+ chiRate
1624
+ });
1465
1625
  const approval = {
1466
1626
  id: record.id,
1467
1627
  requestId: requestState.requestId,
1468
1628
  record,
1469
- view
1629
+ view,
1630
+ context
1470
1631
  };
1471
1632
  await this.store.saveApprovalState(approval);
1472
1633
  await this.store.saveRequestState({
@@ -1505,7 +1666,6 @@ export class WalletController {
1505
1666
  case "xian_requestAccounts": {
1506
1667
  const walletState = this.requireStoredWallet(state);
1507
1668
  await this.getUnlockedSigner();
1508
- const approvalChainId = this.displayChainId(this.activeNetworkPreset(walletState), await this.safeGetChainId(walletState));
1509
1669
  if (walletState.connectedOrigins.includes(origin)) {
1510
1670
  const nextState = await this.updateConnectedOrigin(origin, true, dappMetadata);
1511
1671
  return {
@@ -1515,8 +1675,7 @@ export class WalletController {
1515
1675
  }
1516
1676
  return {
1517
1677
  kind: "approval",
1518
- account: walletState.publicKey,
1519
- chainId: approvalChainId
1678
+ context: await this.captureApprovalContext(walletState)
1520
1679
  };
1521
1680
  }
1522
1681
  case "xian_disconnect": {
@@ -1554,27 +1713,31 @@ export class WalletController {
1554
1713
  }
1555
1714
  case "xian_switchChain": {
1556
1715
  const walletState = this.requireStoredWallet(state);
1716
+ this.requireConnectedOrigin(walletState, origin);
1717
+ await this.getUnlockedSigner();
1557
1718
  const { chainId } = firstParamObject(request.params);
1558
- if (typeof chainId !== "string" || chainId.length === 0) {
1719
+ const requestedChainId = typeof chainId === "string" ? chainId.trim() : "";
1720
+ if (!requestedChainId) {
1559
1721
  throw new TypeError("xian_switchChain requires a chainId string");
1560
1722
  }
1561
1723
  const previousChainId = this.displayChainId(this.activeNetworkPreset(walletState), await this.safeGetChainId(walletState));
1562
- if (previousChainId === chainId) {
1724
+ if (previousChainId === requestedChainId) {
1563
1725
  return {
1564
1726
  kind: "result",
1565
1727
  value: null
1566
1728
  };
1567
1729
  }
1568
- const targetPreset = walletState.networkPresets.find((preset) => preset.chainId === chainId);
1730
+ const targetPreset = walletState.networkPresets.find((preset) => preset.chainId === requestedChainId);
1569
1731
  if (!targetPreset) {
1570
1732
  throw new ProviderChainMismatchError("wallet has no configured network preset for the requested chain");
1571
1733
  }
1572
- const nextState = this.applyActivePreset(walletState, targetPreset.id);
1573
- await this.store.saveState(nextState);
1574
- await this.emitChainChangedForConnectedOrigins(nextState, previousChainId);
1734
+ const context = await this.captureApprovalContext(walletState, targetPreset);
1735
+ if (context.targetNetwork?.chainId !== requestedChainId) {
1736
+ throw new ProviderChainMismatchError("configured network RPC reports a different chain");
1737
+ }
1575
1738
  return {
1576
- kind: "result",
1577
- value: null
1739
+ kind: "approval",
1740
+ context
1578
1741
  };
1579
1742
  }
1580
1743
  case "xian_watchAsset": {
@@ -1583,8 +1746,7 @@ export class WalletController {
1583
1746
  await this.getUnlockedSigner();
1584
1747
  return {
1585
1748
  kind: "approval",
1586
- account: walletState.publicKey,
1587
- chainId: this.displayChainId(this.activeNetworkPreset(walletState), await this.safeGetChainId(walletState))
1749
+ context: await this.captureApprovalContext(walletState)
1588
1750
  };
1589
1751
  }
1590
1752
  case "xian_signMessage": {
@@ -1593,8 +1755,7 @@ export class WalletController {
1593
1755
  await this.getUnlockedSigner();
1594
1756
  return {
1595
1757
  kind: "approval",
1596
- account: walletState.publicKey,
1597
- chainId: this.displayChainId(this.activeNetworkPreset(walletState), await this.safeGetChainId(walletState))
1758
+ context: await this.captureApprovalContext(walletState)
1598
1759
  };
1599
1760
  }
1600
1761
  case "xian_prepareTransaction": {
@@ -1620,8 +1781,7 @@ export class WalletController {
1620
1781
  }
1621
1782
  return {
1622
1783
  kind: "approval",
1623
- account: walletState.publicKey,
1624
- chainId: activeChainId
1784
+ context: await this.captureApprovalContext(walletState)
1625
1785
  };
1626
1786
  }
1627
1787
  default:
@@ -1814,13 +1974,12 @@ export class WalletController {
1814
1974
  async sendDirectTransaction(intent) {
1815
1975
  const state = this.requireStoredWallet(await this.loadWalletState());
1816
1976
  await this.getUnlockedSigner();
1817
- const tx = await this.prepareTransaction(state, {
1977
+ return this.sendCallTransaction(state, {
1818
1978
  contract: intent.contract,
1819
1979
  function: intent.function,
1820
1980
  kwargs: intent.kwargs,
1821
1981
  chi: intent.chi
1822
- });
1823
- return this.sendPreparedTransaction(state, tx, { mode: "commit" });
1982
+ }, { mode: "commit" });
1824
1983
  }
1825
1984
  async getDexSnapshot() {
1826
1985
  const state = this.requireStoredWallet(await this.loadWalletState());
@@ -2720,7 +2879,7 @@ export class WalletController {
2720
2879
  }
2721
2880
  return fulfilled;
2722
2881
  }
2723
- return this.createApprovalRequest(requestState, immediate.account, immediate.chainId);
2882
+ return this.createApprovalRequest(requestState, immediate.context);
2724
2883
  }
2725
2884
  catch (error) {
2726
2885
  const rejected = await this.rejectRequest(requestState, error);
@@ -2801,10 +2960,11 @@ export class WalletController {
2801
2960
  return null;
2802
2961
  }
2803
2962
  try {
2804
- const result = await this.executeApprovedRequest(approval.record.origin, approval.record.request, requestState.dappMetadata);
2963
+ const result = await this.executeApprovedRequest(approval.record.origin, approval.record.request, requestState.dappMetadata, approval);
2805
2964
  await this.fulfillRequest(requestState, result);
2806
- if (options?.trust) {
2807
- const policy = await this.createTrustedDappPolicyForApproval(approval);
2965
+ const trustScope = normalizeApprovalTrustScope(options?.trust);
2966
+ if (trustScope) {
2967
+ const policy = await this.createTrustedDappPolicyForApproval(approval, trustScope);
2808
2968
  if (policy) {
2809
2969
  await this.upsertTrustedDappPolicy(policy);
2810
2970
  }