@qntx/wallet-engine 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,27 +1,29 @@
1
- import { a as Nip07Handler, c as ProviderError, d as unauthorized, f as unrecognizedChain, h as Controller, i as SolanaWalletHandler, l as internalError, m as userRejectedRequest, n as parsePayment, o as ConnectionController, p as unsupportedMethod, r as SOLANA_CHAIN_IDS, s as evmChainId, t as WeblnHandler, u as invalidParams } from "./webln-CHjBMRcv.mjs";
1
+ import { _ as userRejectedRequest, a as Nip07Handler, c as utf8Text, d as ProviderError, f as internalError, g as unsupportedMethod, h as unrecognizedChain, i as SolanaWalletHandler, l as ConnectionController, m as unauthorized, n as parsePayment, o as SessionEvents, p as invalidParams, r as SOLANA_CHAIN_IDS, s as BLIND_SIGNING_MESSAGE, t as WeblnHandler, u as evmChainId, v as PHISHING_BLOCKED_MESSAGE, y as Controller } from "./webln-DHYqdaDU.mjs";
2
2
  import { i as networkById } from "./registry-CHiAn88k.mjs";
3
- import { EVM_RPC_METHODS, INSTALL_ID_HEADER, esploraBasePath, networksPath, parseWith, rpcPath, servedNetworksResponse } from "./gateway-contract.mjs";
3
+ import { EVM_RPC_METHODS, INSTALL_ID_HEADER, applyDiff, contains, decodeHashList, encodeHashList, esploraBasePath, networksPath, parseWith, phishingCandidates, phishingHash, phishingListPath, phishingListResponse, rpcPath, servedNetworksResponse } from "./gateway-contract.mjs";
4
4
  import { bytesToHex, hexToBytes, utf8ToBytes } from "@noble/hashes/utils.js";
5
5
  import { ChainError } from "@qntx/wallet-chains";
6
+ import * as z from "zod/mini";
6
7
  import { WalletError, parseBackupHeader } from "@qntx/wallet";
7
- import { PROGRAM_IDS, decodeSolana, isSolanaAddress, netAfterTransferFee, normalizeSolana, parseMintExtensions } from "@qntx/wallet-chains/solana";
8
+ import { EVM_NATIVE_ASSET, checksumEvmAddress, decodeEvm, evmTokenTable, isEvmAddress, lookupEvmToken, normalizeEvm } from "@qntx/wallet-chains/evm";
9
+ import { PROGRAM_IDS, SOLANA_NATIVE_ASSET, decodeSolana, isSolanaAddress, netAfterTransferFee, normalizeSolana, parseCompiledMessage, parseMintExtensions, solanaTokenTable } from "@qntx/wallet-chains/solana";
8
10
  import { Address, OutScript, Transaction } from "@scure/btc-signer";
9
11
  import { SparkInputError, SparkRequestError, bitcoinAddressScript, createSparkClient, decodeBolt11, decodeSparkAddress, encodeSparkAddress, parseSparkInvoice, uuidv7 } from "@qntx/spark";
10
12
  import { BITCOIN_NETWORKS, bitcoinAddressFromXpub, bitcoinNetwork, bitcoinPubkeyFromXpub, decodeBitcoinPsbt } from "@qntx/wallet-chains/bitcoin";
11
- import { checksumEvmAddress, decodeEvm, isEvmAddress, normalizeEvm } from "@qntx/wallet-chains/evm";
12
13
  import { encodeLnurl, lightningAddressUrl, registerLightningAddress, requestInvoice, resolveLnurl, submitWithdraw, unregisterLightningAddress } from "@qntx/spark/lnurl";
13
14
  import { signedMatchesUnsigned } from "@qntx/nostr";
14
15
  import { makeZapRequest } from "@qntx/nostr/nips/nip57";
16
+ import { sha256 } from "@noble/hashes/sha2.js";
17
+ import { base64, hex } from "@scure/base";
15
18
  import { chains } from "@qntx/wallet/chains";
16
19
  import { nostr } from "@qntx/wallet/nostr";
17
20
  import { spark } from "@qntx/wallet/spark";
18
21
  import { createPublicClient, decodeFunctionResult, encodeFunctionData, fallback, http, isAddress, isHex, numberToHex } from "viem";
19
- import { sha256 } from "@noble/hashes/sha2.js";
20
- import { base64, hex } from "@scure/base";
22
+ import { simulateCalls } from "viem/actions";
21
23
  import { getSetComputeUnitLimitInstruction, getSetComputeUnitPriceInstruction } from "@solana-program/compute-budget";
22
24
  import { getTransferSolInstruction } from "@solana-program/system";
23
25
  import { TOKEN_PROGRAM_ADDRESS, findAssociatedTokenPda, getCreateAssociatedTokenIdempotentInstruction, getTransferCheckedInstruction } from "@solana-program/token";
24
- import { address, appendTransactionMessageInstructions, blockhash, compileTransactionMessage, createNoopSigner, createTransactionMessage, getCompiledTransactionMessageEncoder, setTransactionMessageFeePayer, setTransactionMessageLifetimeUsingBlockhash } from "@solana/kit";
26
+ import { address, appendTransactionMessageInstructions, blockhash, compileTransactionMessage, createNoopSigner, createTransactionMessage, getAddressDecoder, getCompiledTransactionMessageEncoder, getU64Decoder, setTransactionMessageFeePayer, setTransactionMessageLifetimeUsingBlockhash } from "@solana/kit";
25
27
  import { p2wpkh } from "@scure/btc-signer/payment.js";
26
28
  import { selectUTXO } from "@scure/btc-signer/utxo.js";
27
29
  // src/events.ts
@@ -61,6 +63,7 @@ var EngineStoreError = class extends Error {
61
63
  this.code = code;
62
64
  }
63
65
  };
66
+ const errorMessage = (error) => error instanceof Error ? error.message : String(error);
64
67
  // src/store/guard.ts
65
68
  /** NUL is the composite-key/AAD separator — a name or key containing it collides. */
66
69
  function checkName(kind, value) {
@@ -111,6 +114,22 @@ function createMemoryEngineStore(backing) {
111
114
  }
112
115
  };
113
116
  }
117
+ /** In-memory PublicStore: the Node/test implementation — same contract, no durability. */
118
+ function createMemoryPublicStore(backing) {
119
+ const values = backing?.values ?? /* @__PURE__ */ new Map();
120
+ return {
121
+ get: async (key) => {
122
+ checkName("key", key);
123
+ const value = values.get(key);
124
+ return value === void 0 ? void 0 : new Uint8Array(value);
125
+ },
126
+ put: async (key, bytes) => {
127
+ checkName("key", key);
128
+ values.set(key, new Uint8Array(bytes));
129
+ await Promise.resolve();
130
+ }
131
+ };
132
+ }
114
133
  // src/addresses/normalize.ts
115
134
  /**
116
135
  * The canonical form of `address` for its family — EIP-55 for EVM, the re-encoded form for bitcoin
@@ -137,6 +156,39 @@ function normalizeAddress(family, address) {
137
156
  return;
138
157
  }
139
158
  }
159
+ const UNSAFE_RANGES = [
160
+ [0, 31],
161
+ [127, 159],
162
+ [1564, 1564],
163
+ [8203, 8207],
164
+ [8234, 8238],
165
+ [8288, 8288],
166
+ [8294, 8297],
167
+ [65279, 65279]
168
+ ];
169
+ const isUnsafe = (codePoint) => UNSAFE_RANGES.some(([low, high]) => codePoint >= low && codePoint <= high);
170
+ /**
171
+ * Untrusted contract text (a token symbol) as safe-to-show text: trimmed, non-empty, at most `max`
172
+ * code points, with no control, bidi-control or zero-width characters. `undefined` otherwise.
173
+ */
174
+ function safeDisplayText(raw, max) {
175
+ const text = raw.trim();
176
+ let count = 0;
177
+ for (const char of text) {
178
+ count += 1;
179
+ if (count > max || isUnsafe(char.codePointAt(0) ?? 0)) return;
180
+ }
181
+ return count === 0 ? void 0 : text;
182
+ }
183
+ function isAscii(text) {
184
+ for (const char of text) {
185
+ const code = char.codePointAt(0) ?? 0;
186
+ if (code < 32 || code > 126) return false;
187
+ }
188
+ return true;
189
+ }
190
+ /** A token's `decimals` as an integer within `0..TOKEN_DECIMALS_MAX`, else `undefined`. */
191
+ const safeDecimals = (value) => Number.isInteger(value) && value >= 0 && value <= 36 ? value : void 0;
140
192
  // src/spark/errors.ts
141
193
  var SparkControllerError = class extends Error {
142
194
  category;
@@ -495,7 +547,6 @@ const SPARK_L1_NETWORK = {
495
547
  const hexId = (prefix, random) => `${prefix}-${[...random(8)].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
496
548
  const newId = (random) => hexId("tx", random);
497
549
  const newRequestId = (random) => hexId("req", random);
498
- const errorMessage$1 = (error) => error instanceof Error ? error.message : String(error);
499
550
  const LIVE_REPLACEMENT_STATES = /* @__PURE__ */ new Set([
500
551
  "draft",
501
552
  "signed",
@@ -525,7 +576,7 @@ const failTx = async (ctx, tx, error) => {
525
576
  const failed = tx.state === "signed" ? "failed" : "rejected";
526
577
  await ctx.transition(tx, {
527
578
  state: failed,
528
- error: errorMessage$1(error)
579
+ error: errorMessage(error)
529
580
  });
530
581
  };
531
582
  // src/requests/checks.ts
@@ -604,6 +655,25 @@ const mergeSatPerByte = (primary, independent) => ({
604
655
  });
605
656
  /** The checks a prepared build carries, in a stable order and without duplicates. */
606
657
  const collectChecks = (flags) => [...new Set(flags.filter((f) => f !== void 0))];
658
+ // src/requests/risk.ts
659
+ const byDanger = (findings) => [...findings].sort((a, b) => Number(b.level === "danger") - Number(a.level === "danger"));
660
+ /** The finding for a browser origin's phishing status, if any; `blocked` never reaches a request. */
661
+ function originRisk(status) {
662
+ if (status === "trusted") return [{
663
+ code: "phishing-origin",
664
+ level: "danger"
665
+ }];
666
+ return status === "unchecked" ? [{
667
+ code: "phishing-unchecked",
668
+ level: "warning"
669
+ }] : [];
670
+ }
671
+ /** `findings` plus `extra`, deduplicated by code, `danger` first. */
672
+ function mergeRisk(findings, extra) {
673
+ const byCode = /* @__PURE__ */ new Map();
674
+ for (const finding of [...findings, ...extra]) byCode.set(finding.code, finding);
675
+ return byDanger([...byCode.values()]);
676
+ }
607
677
  /** EVM addresses compare without the `0x` prefix and case-insensitively. */
608
678
  const comparable = (family, address) => family === "evm" ? address.replace(/^0x/i, "").toLowerCase() : address;
609
679
  const looksLike = (a, b) => a !== b && a.length >= 8 && b.length >= 8 && a.slice(0, 4) === b.slice(0, 4) && a.slice(-4) === b.slice(-4);
@@ -623,7 +693,50 @@ function assessRecipients(family, recipients, known) {
623
693
  level: "danger"
624
694
  });
625
695
  }
626
- return [...found.values()].sort((a, b) => Number(b.level === "danger") - Number(a.level === "danger"));
696
+ return byDanger([...found.values()]);
697
+ }
698
+ const sameAsset = (a, b) => a === b || a.startsWith("0x") && a.toLowerCase() === b.toLowerCase();
699
+ const declaredOutflow = (intent, asset) => intent.outflows.filter((flow) => sameAsset(flow.amount.asset, asset)).reduce((sum, flow) => sum + BigInt(flow.amount.amount), 0n);
700
+ /**
701
+ * What a simulation adds to a request. `unavailable` blocks silent approval; `reverted` is a
702
+ * danger; an outflow above what the decode declares for that asset is a danger too — but only
703
+ * against a decode that is not `opaque`, and never for Solana lamports (fees and rent always exceed
704
+ * the declared amount).
705
+ */
706
+ function assessSimulation(intent, outcome) {
707
+ if (outcome === void 0) return {
708
+ checks: [],
709
+ risk: []
710
+ };
711
+ if (outcome.status === "unavailable") return {
712
+ checks: ["simulation-unavailable"],
713
+ risk: []
714
+ };
715
+ if (outcome.status === "reverted") return {
716
+ checks: [],
717
+ risk: [{
718
+ code: "simulation-reverted",
719
+ level: "danger"
720
+ }]
721
+ };
722
+ return {
723
+ checks: [],
724
+ risk: intent.verifiability !== "opaque" && outcome.changes.some((change) => {
725
+ const amount = BigInt(change.amount);
726
+ return amount < 0n && change.asset !== SOLANA_NATIVE_ASSET && -amount > declaredOutflow(intent, change.asset);
727
+ }) ? [{
728
+ code: "simulation-mismatch",
729
+ level: "danger"
730
+ }] : []
731
+ };
732
+ }
733
+ /**
734
+ * A token on `chainId` that reports the symbol of a different, built-in token of the same chain —
735
+ * the shape of a lookalike token. Symbols compare case-insensitively.
736
+ */
737
+ function impersonatesBuiltIn(chainId, address, symbol) {
738
+ const wanted = symbol.toLowerCase();
739
+ return Object.entries(evmTokenTable[String(chainId)] ?? {}).some(([known, token]) => known.toLowerCase() !== address.toLowerCase() && token.symbol.toLowerCase() === wanted);
627
740
  }
628
741
  // src/requests/sign-log.ts
629
742
  const SIGN_LOG_LIMIT = 1e3;
@@ -639,6 +752,7 @@ const METHODS = /* @__PURE__ */ new Set([
639
752
  "evm-sign",
640
753
  "nostr-sign",
641
754
  "webln-invoice",
755
+ "watch-asset",
642
756
  "spark-deposit",
643
757
  "spark-exit"
644
758
  ]);
@@ -662,8 +776,8 @@ const isAccount = (value) => {
662
776
  if (value["kind"] === void 0 && typeof value["walletId"] === "string" && typeof value["groupIndex"] === "number" && typeof value["address"] === "string") return true;
663
777
  return value["kind"] === void 0 && typeof value["walletId"] === "string" && typeof value["groupIndex"] === "number" && typeof value["network"] === "string";
664
778
  };
665
- const isOrigin = (value) => isObject$13(value) && (value["kind"] === "internal" || value["kind"] === "browser" && typeof value["origin"] === "string");
666
- const isEntry = (value) => isObject$13(value) && typeof value["id"] === "string" && typeof value["at"] === "number" && isOrigin(value["origin"]) && METHODS.has(value["method"]) && OUTCOMES.has(value["outcome"]) && isAccount(value["account"]);
779
+ const isOrigin$1 = (value) => isObject$13(value) && (value["kind"] === "internal" || value["kind"] === "browser" && typeof value["origin"] === "string");
780
+ const isEntry = (value) => isObject$13(value) && typeof value["id"] === "string" && typeof value["at"] === "number" && isOrigin$1(value["origin"]) && METHODS.has(value["method"]) && OUTCOMES.has(value["outcome"]) && isAccount(value["account"]);
667
781
  /** Sortable key: time first, request id as the tiebreak. */
668
782
  const keyOf = (entry) => `${String(entry.at).padStart(16, "0")}-${entry.id}`;
669
783
  function createSignLog(logger) {
@@ -708,6 +822,13 @@ function createSignLog(logger) {
708
822
  };
709
823
  }
710
824
  // src/requests/controller.ts
825
+ /** A token the page asked to watch whose on-chain metadata cannot be shown; the dApp's bad input. */
826
+ var InvalidTokenError = class extends Error {
827
+ constructor(message) {
828
+ super(message);
829
+ this.name = "InvalidTokenError";
830
+ }
831
+ };
711
832
  /** A request that ended without a result: `stage` says how, `message` is the failure if any. */
712
833
  var RequestEndedError = class extends Error {
713
834
  stage;
@@ -727,8 +848,12 @@ var OriginBusyError = class extends Error {
727
848
  /** Requests expire this long after creation. */
728
849
  const REQUEST_TTL_MS = 6e5;
729
850
  const originKey = (origin) => `origin:${origin.origin}`;
730
- /** The input's browser origin, when it carries one (`evm-sign`/`nostr-sign`/`webln-invoice`/`pay`). */
731
- const solanaDecode = (account, network, message) => {
851
+ const messageText = (message) => {
852
+ const text = utf8Text(message);
853
+ if (text === void 0) throw new Error("a solana message request must be UTF-8 text");
854
+ return text;
855
+ };
856
+ const solanaIntent = (account, network, message) => {
732
857
  try {
733
858
  const request = normalizeSolana({
734
859
  kind: "solana.transaction",
@@ -741,15 +866,29 @@ const solanaDecode = (account, network, message) => {
741
866
  },
742
867
  message
743
868
  }, account.address);
744
- if (request.kind === "solana.transaction") return decodeSolana(request, account.address, void 0);
745
- return;
869
+ return request.kind === "solana.transaction" ? decodeSolana(request, account.address, void 0) : { error: "not a transaction" };
746
870
  } catch (error) {
747
871
  return { error: errorMessage(error) };
748
872
  }
749
873
  };
874
+ /** Nothing declared and nothing checkable: what a transaction that did not decode counts as. */
875
+ const OPAQUE_INTENT = {
876
+ outflows: [],
877
+ verifiability: "opaque"
878
+ };
879
+ const withSimulation = (built, intent, simulation) => {
880
+ if (simulation === void 0) return built;
881
+ const assessed = assessSimulation(intent, simulation);
882
+ return {
883
+ ...built,
884
+ checks: collectChecks([...built.checks, ...assessed.checks]),
885
+ risk: mergeRisk(built.risk, assessed.risk),
886
+ simulation
887
+ };
888
+ };
889
+ /** The input's browser origin, when it carries one (`evm-sign`/`nostr-sign`/`webln-invoice`/`pay`). */
750
890
  const browserOriginOf = (input) => "origin" in input ? input.origin : void 0;
751
891
  const LIVE = /* @__PURE__ */ new Set(["awaiting-approval", "signing"]);
752
- const errorMessage = (error) => error instanceof Error ? error.message : String(error);
753
892
  var RequestController = class extends Controller {
754
893
  options;
755
894
  entries = /* @__PURE__ */ new Map();
@@ -805,6 +944,8 @@ var RequestController = class extends Controller {
805
944
  const id = newRequestId(this.options.random);
806
945
  const target = "txId" in input ? input.txId : void 0;
807
946
  const browserOrigin = browserOriginOf(input);
947
+ const originStatus = browserOrigin === void 0 ? "clear" : this.options.phishing.check(browserOrigin.origin);
948
+ if (originStatus === "blocked") throw new Error(PHISHING_BLOCKED_MESSAGE);
808
949
  if (browserOrigin !== void 0) {
809
950
  const key = originKey(browserOrigin);
810
951
  if (this.targets.has(key)) throw new OriginBusyError(browserOrigin.origin);
@@ -839,7 +980,8 @@ var RequestController = class extends Controller {
839
980
  display: built.display,
840
981
  verification: checks.length > 0 ? "unverifiable" : "verified",
841
982
  checks,
842
- risk: built.risk,
983
+ risk: mergeRisk(built.risk, originRisk(originStatus)),
984
+ ...built.simulation === void 0 ? {} : { simulation: built.simulation },
843
985
  createdAt,
844
986
  expiresAt: createdAt + REQUEST_TTL_MS
845
987
  };
@@ -903,6 +1045,16 @@ var RequestController = class extends Controller {
903
1045
  }
904
1046
  };
905
1047
  }
1048
+ async simulateOne(account, network, message) {
1049
+ try {
1050
+ return await this.options.simulateSolana(account, network, message);
1051
+ } catch (error) {
1052
+ return {
1053
+ status: "unavailable",
1054
+ error: errorMessage(error)
1055
+ };
1056
+ }
1057
+ }
906
1058
  async build(input, id) {
907
1059
  if (input.method === "pay" || input.method === "zap") {
908
1060
  const action = input.method === "pay" ? await preparePay({
@@ -962,7 +1114,7 @@ var RequestController = class extends Controller {
962
1114
  if (input.method === "evm-sign") {
963
1115
  const prepared = await this.options.transactions.prepareDapp(input.account, input.request);
964
1116
  const isTransaction = input.request.kind === "evm.transaction";
965
- return {
1117
+ const built = {
966
1118
  account: prepared.account,
967
1119
  network: prepared.network,
968
1120
  display: prepared.intent,
@@ -973,17 +1125,25 @@ var RequestController = class extends Controller {
973
1125
  factor: "required"
974
1126
  }
975
1127
  };
1128
+ return isTransaction ? withSimulation(built, prepared.intent, prepared.simulation) : built;
976
1129
  }
977
1130
  if (input.method === "solana-sign") {
978
1131
  const txs = input.request.kind === "transactions" ? input.request.transactions : [];
979
- return {
1132
+ const [only] = txs;
1133
+ const intents = txs.map((tx) => solanaIntent(input.account, input.network, tx));
1134
+ const [decoded] = intents;
1135
+ const built = {
980
1136
  account: input.account,
981
1137
  network: input.network,
982
1138
  display: {
983
1139
  kind: "solana.sign",
984
1140
  send: input.request.kind === "transactions" ? input.request.send : false,
985
1141
  count: txs.length === 0 ? 1 : txs.length,
986
- transactions: txs.map((tx) => solanaDecode(input.account, input.network, tx))
1142
+ transactions: intents,
1143
+ ...input.request.kind === "message" ? {
1144
+ message: { text: messageText(input.request.message) },
1145
+ ...input.request.signIn === void 0 ? {} : { signIn: input.request.signIn }
1146
+ } : {}
987
1147
  },
988
1148
  checks: [],
989
1149
  risk: [],
@@ -994,6 +1154,12 @@ var RequestController = class extends Controller {
994
1154
  release: () => void 0
995
1155
  }
996
1156
  };
1157
+ if (only === void 0) return built;
1158
+ const simulation = txs.length > 1 ? {
1159
+ status: "unavailable",
1160
+ error: "batch"
1161
+ } : await this.simulateOne(input.account, input.network, only);
1162
+ return withSimulation(built, decoded !== void 0 && "verifiability" in decoded ? decoded : OPAQUE_INTENT, simulation);
997
1163
  }
998
1164
  if (input.method === "webln-invoice") return {
999
1165
  account: input.ref,
@@ -1020,6 +1186,44 @@ var RequestController = class extends Controller {
1020
1186
  release: () => void 0
1021
1187
  }
1022
1188
  };
1189
+ if (input.method === "watch-asset") {
1190
+ const address = checksumEvmAddress(input.address);
1191
+ const metadata = await this.options.tokens.metadata(input.network, address);
1192
+ const symbol = safeDisplayText(metadata.symbol, 32);
1193
+ const decimals = safeDecimals(metadata.decimals);
1194
+ if (symbol === void 0) throw new InvalidTokenError("the token symbol cannot be displayed safely");
1195
+ if (decimals === void 0) throw new InvalidTokenError("the token decimals are out of range");
1196
+ const chainId = Number(input.network.slice(7));
1197
+ return {
1198
+ account: input.account,
1199
+ network: input.network,
1200
+ display: {
1201
+ kind: "token.watch",
1202
+ network: input.network,
1203
+ address,
1204
+ symbol,
1205
+ decimals,
1206
+ verified: lookupEvmToken(evmTokenTable, chainId, address) !== void 0
1207
+ },
1208
+ checks: [],
1209
+ risk: [...impersonatesBuiltIn(chainId, address, symbol) ? [{
1210
+ code: "token-impersonation",
1211
+ level: "danger"
1212
+ }] : [], ...isAscii(symbol) ? [] : [{
1213
+ code: "token-symbol-unicode",
1214
+ level: "warning"
1215
+ }]],
1216
+ run: {
1217
+ factor: "none",
1218
+ staleReason: () => void 0,
1219
+ submit: async () => {
1220
+ await this.options.tokens.add(input.network, address);
1221
+ return { kind: "token.watch" };
1222
+ },
1223
+ release: () => void 0
1224
+ }
1225
+ };
1226
+ }
1023
1227
  if (input.method === "nostr-sign") return {
1024
1228
  account: input.ref,
1025
1229
  network: "",
@@ -1042,7 +1246,7 @@ var RequestController = class extends Controller {
1042
1246
  }
1043
1247
  };
1044
1248
  const prepared = input.method === "send" ? await this.options.transactions.prepareSend(input, id) : await this.options.transactions.prepareReplacement(input, id);
1045
- return {
1249
+ const built = {
1046
1250
  account: prepared.account,
1047
1251
  network: prepared.network,
1048
1252
  display: prepared.intent,
@@ -1053,6 +1257,7 @@ var RequestController = class extends Controller {
1053
1257
  factor: "required"
1054
1258
  }
1055
1259
  };
1260
+ return input.method === "send" ? withSimulation(built, prepared.intent, prepared.simulation) : built;
1056
1261
  }
1057
1262
  async approve(id, method, verify) {
1058
1263
  const request = this.getState().requests[id];
@@ -1064,6 +1269,10 @@ var RequestController = class extends Controller {
1064
1269
  this.finish(id, "expired");
1065
1270
  throw new Error(`request ${id} expired`);
1066
1271
  }
1272
+ if (request.origin.kind === "browser" && this.options.phishing.check(request.origin.origin) === "blocked") {
1273
+ this.finish(id, "failed", PHISHING_BLOCKED_MESSAGE);
1274
+ throw new Error(PHISHING_BLOCKED_MESSAGE);
1275
+ }
1067
1276
  const { session } = this;
1068
1277
  this.put({
1069
1278
  ...request,
@@ -1168,7 +1377,7 @@ var RequestController = class extends Controller {
1168
1377
  record(request, outcome, error, result) {
1169
1378
  const { display } = request;
1170
1379
  const eventId = result !== void 0 && "kind" in result && result.kind === "nostr.event" ? result.event.id : void 0;
1171
- const summary = "kind" in display && display.kind === "nostr.event" ? `nostr kind ${display.eventKind}${eventId === void 0 ? "" : ` ${eventId}`}` : "kind" in display && display.kind === "lightning.invoice" ? `lightning invoice ${display.amountSats} sats` : "kind" in display && display.kind === "solana.sign" ? display.transactions.length === 0 ? "solana message" : `solana ${display.send ? "send" : "sign"} ${String(display.count)} tx` : "summary" in display ? display.summary : `${display.kind} ${display.amountSats}`;
1380
+ const summary = "kind" in display && display.kind === "nostr.event" ? `nostr kind ${display.eventKind}${eventId === void 0 ? "" : ` ${eventId}`}` : "kind" in display && display.kind === "token.watch" ? `watch token ${display.symbol}` : "kind" in display && display.kind === "lightning.invoice" ? `lightning invoice ${display.amountSats} sats` : "kind" in display && display.kind === "solana.sign" ? display.signIn === void 0 ? display.transactions.length === 0 ? "solana message" : `solana ${display.send ? "send" : "sign"} ${String(display.count)} tx` : `solana sign-in ${display.signIn.domain}` : "summary" in display ? display.summary : `${display.kind} ${display.amountSats}`;
1172
1381
  const entry = {
1173
1382
  id: request.id,
1174
1383
  at: this.options.now(),
@@ -1227,8 +1436,6 @@ const REFUSED = /* @__PURE__ */ new Set([
1227
1436
  ]);
1228
1437
  /** Planned for later layers; answered `4200` until then. */
1229
1438
  const DEFERRED = /* @__PURE__ */ new Set([
1230
- "wallet_addEthereumChain",
1231
- "wallet_watchAsset",
1232
1439
  "wallet_sendCalls",
1233
1440
  "wallet_getCallsStatus",
1234
1441
  "wallet_getCapabilities",
@@ -1246,11 +1453,7 @@ const textBytes = (value) => {
1246
1453
  if (typeof value !== "string") throw invalidParams("message must be a string");
1247
1454
  if (/^0x(?:[0-9a-fA-F]{2})*$/.test(value)) {
1248
1455
  const bytes = hexToBytes(value.slice(2));
1249
- try {
1250
- new TextDecoder("utf-8", { fatal: true }).decode(bytes);
1251
- } catch {
1252
- throw new ProviderError(4200, "blind signing is not enabled: the message is not UTF-8 text");
1253
- }
1456
+ if (utf8Text(bytes) === void 0) throw new ProviderError(4200, BLIND_SIGNING_MESSAGE);
1254
1457
  return bytes;
1255
1458
  }
1256
1459
  return new TextEncoder().encode(value);
@@ -1262,33 +1465,20 @@ const quantityOf = (value, field, fallback) => {
1262
1465
  };
1263
1466
  var Eip1193Handler = class {
1264
1467
  options;
1265
- listeners = /* @__PURE__ */ new Set();
1266
- unsubscribe;
1468
+ events;
1267
1469
  constructor(options) {
1268
1470
  this.options = options;
1471
+ this.events = new SessionEvents(options.connections, diffSessions);
1269
1472
  }
1270
1473
  /** Events for the host to forward to pages; derived from changes to the sessions. */
1271
1474
  subscribe(listener) {
1272
- this.listeners.add(listener);
1273
- if (this.unsubscribe === void 0) {
1274
- let previous = this.options.connections.getState().sessions;
1275
- this.unsubscribe = this.options.connections.store.subscribe((state) => {
1276
- for (const event of diffSessions(previous, state.sessions)) for (const l of this.listeners) l(event);
1277
- previous = state.sessions;
1278
- });
1279
- }
1280
- return () => {
1281
- this.listeners.delete(listener);
1282
- if (this.listeners.size === 0) {
1283
- this.unsubscribe?.();
1284
- this.unsubscribe = void 0;
1285
- }
1286
- };
1475
+ return this.events.subscribe(listener);
1287
1476
  }
1288
1477
  async handle(origin, request) {
1289
1478
  const { connections } = this.options;
1290
1479
  connections.checkOrigin(origin);
1291
1480
  const { method } = request;
1481
+ if (method === "wallet_watchAsset") return this.watchAsset(origin, request.params);
1292
1482
  const params = paramList(request.params);
1293
1483
  if (REFUSED.has(method) || DEFERRED.has(method)) throw unsupportedMethod(method);
1294
1484
  switch (method) {
@@ -1303,6 +1493,7 @@ var Eip1193Handler = class {
1303
1493
  await connections.revoke(origin);
1304
1494
  return null;
1305
1495
  case "wallet_switchEthereumChain": return this.switchChain(origin, params[0]);
1496
+ case "wallet_addEthereumChain": return this.addChain(origin, params[0]);
1306
1497
  case "personal_sign": return this.personalSign(origin, params);
1307
1498
  case "eth_signTypedData_v4": return this.typedData(origin, params);
1308
1499
  case "eth_sendTransaction": return this.sendTransaction(origin, params[0]);
@@ -1312,7 +1503,7 @@ var Eip1193Handler = class {
1312
1503
  }
1313
1504
  async requestAccounts(origin) {
1314
1505
  const { connections } = this.options;
1315
- if (connections.accounts(origin).length === 0) await connections.request(origin, "connect");
1506
+ if (connections.accounts(origin).length === 0) await connections.request(origin, { kind: "connect" });
1316
1507
  await connections.touch(origin);
1317
1508
  return connections.accounts(origin);
1318
1509
  }
@@ -1336,10 +1527,70 @@ var Eip1193Handler = class {
1336
1527
  if (!connections.isEnabled(network)) throw unrecognizedChain(`chain ${chainId} is not enabled`);
1337
1528
  const session = connections.session(origin);
1338
1529
  if (session === void 0) throw unauthorized();
1339
- if (session.scopes[network] === void 0) await connections.request(origin, "network", network);
1530
+ if (session.scopes[network] === void 0) await connections.request(origin, {
1531
+ kind: "network",
1532
+ network
1533
+ });
1340
1534
  else if (session.currentNetwork !== network) await connections.setCurrentNetwork(origin, network);
1341
1535
  return null;
1342
1536
  }
1537
+ /**
1538
+ * EIP-3085. The chain must already be a network the wallet enables; the page's `rpcUrls` are
1539
+ * validated for shape and never read or used — custom endpoints are the user's setting.
1540
+ */
1541
+ async addChain(origin, arg) {
1542
+ const { connections } = this.options;
1543
+ if (!isObject$12(arg)) throw invalidParams("the chain parameter must be an object");
1544
+ const { chainId, chainName, nativeCurrency, rpcUrls } = arg;
1545
+ if (typeof chainId !== "string" || !/^0x[1-9a-f][0-9a-f]*$/i.test(chainId)) throw invalidParams("chainId must be a 0x quantity without leading zeros");
1546
+ if (typeof chainName !== "string" || chainName === "") throw invalidParams("chainName must be a non-empty string");
1547
+ if (!isObject$12(nativeCurrency) || typeof nativeCurrency["name"] !== "string" || nativeCurrency["name"] === "" || typeof nativeCurrency["symbol"] !== "string" || nativeCurrency["symbol"].length < 2 || nativeCurrency["symbol"].length > 6 || nativeCurrency["decimals"] !== 18) throw invalidParams("nativeCurrency must be { name, symbol (2-6 characters), decimals: 18 }");
1548
+ if (!Array.isArray(rpcUrls) || rpcUrls.length === 0 || !rpcUrls.every((url) => typeof url === "string")) throw invalidParams("rpcUrls must be a non-empty array of strings");
1549
+ const network = `eip155:${Number.parseInt(chainId, 16)}`;
1550
+ if (!connections.isEnabled(network)) throw unrecognizedChain(`chain ${chainId} is not enabled`);
1551
+ const session = connections.session(origin);
1552
+ if (session !== void 0 && session.scopes[network] === void 0) await connections.request(origin, {
1553
+ kind: "network",
1554
+ network,
1555
+ activate: false
1556
+ });
1557
+ return null;
1558
+ }
1559
+ /** EIP-747 (ERC-20 only): `symbol`, `decimals` and `image` from the page are never used. */
1560
+ async watchAsset(origin, arg) {
1561
+ const { connections, requests } = this.options;
1562
+ const session = this.signingSession(origin, "wallet_watchAsset");
1563
+ if (!isObject$12(arg) || arg["type"] !== "ERC20" || !isObject$12(arg["options"])) throw invalidParams("params must be { type: 'ERC20', options: { address } }");
1564
+ const { options } = arg;
1565
+ const { address, chainId } = options;
1566
+ if (typeof address !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(address)) throw invalidParams("options.address must be an EVM address");
1567
+ const { currentNetwork: network } = session;
1568
+ if (chainId !== void 0 && Number(chainId) !== evmChainId(network)) throw invalidParams("options.chainId does not match the session network");
1569
+ if (this.options.isTracked(network, address)) return true;
1570
+ const group = connections.activeGroup();
1571
+ if (group === void 0) throw internalError("no account group is selected");
1572
+ try {
1573
+ const pending = await requests.prepare({
1574
+ method: "watch-asset",
1575
+ origin: {
1576
+ kind: "browser",
1577
+ origin
1578
+ },
1579
+ account: {
1580
+ kind: "hd",
1581
+ ...group,
1582
+ template: "evm.bip44"
1583
+ },
1584
+ network,
1585
+ address
1586
+ });
1587
+ await requests.outcome(pending.id);
1588
+ await connections.touch(origin);
1589
+ return true;
1590
+ } catch (error) {
1591
+ throw toProviderError(error);
1592
+ }
1593
+ }
1343
1594
  authorizedAccount(session, address) {
1344
1595
  const accounts = this.options.connections.accounts(session.origin.origin);
1345
1596
  const wanted = typeof address === "string" ? address.toLowerCase() : accounts[0];
@@ -1448,6 +1699,7 @@ var Eip1193Handler = class {
1448
1699
  };
1449
1700
  function toProviderError(error) {
1450
1701
  if (error instanceof ProviderError) return error;
1702
+ if (error instanceof InvalidTokenError) return invalidParams(error.message);
1451
1703
  if (error instanceof OriginBusyError) return userRejectedRequest(error.message);
1452
1704
  if (error instanceof RequestEndedError) return error.stage === "failed" ? internalError(error.message) : userRejectedRequest(error.message);
1453
1705
  if (error instanceof ChainError) return invalidParams(error.message);
@@ -1776,6 +2028,271 @@ var AddressBookController = class extends Controller {
1776
2028
  return this.engineStore;
1777
2029
  }
1778
2030
  };
2031
+ // src/gateway/client.ts
2032
+ /** `fetch` that adds the install id to requests bound for the gateway's origin only. */
2033
+ function gatewayFetch(fetch, gateway) {
2034
+ const origin = gateway === void 0 ? void 0 : new URL(gateway.url).origin;
2035
+ return async (input, init) => {
2036
+ const target = input instanceof Request ? input.url : String(input);
2037
+ if (gateway === void 0 || new URL(target).origin !== origin) return fetch(input, init);
2038
+ const headers = new Headers(init?.headers);
2039
+ headers.set(INSTALL_ID_HEADER, gateway.installId);
2040
+ return fetch(input, {
2041
+ ...init,
2042
+ headers
2043
+ });
2044
+ };
2045
+ }
2046
+ // src/timer.ts
2047
+ /**
2048
+ * An `AbortSignal` that fires after `ms` on the injected timer — the platform timeout signal is not
2049
+ * available in every runtime this package runs in. Call `cancel` once the work is done, or `abort`
2050
+ * to stop it early.
2051
+ */
2052
+ function timeoutSignal(ms, setTimer) {
2053
+ const controller = new AbortController();
2054
+ const cancel = setTimer(ms, () => {
2055
+ controller.abort();
2056
+ });
2057
+ return {
2058
+ signal: controller.signal,
2059
+ cancel,
2060
+ abort: () => {
2061
+ controller.abort();
2062
+ }
2063
+ };
2064
+ }
2065
+ // src/phishing/controller.ts
2066
+ const PHISHING_REFRESH_MS = 36e5;
2067
+ const SYNC_TIMEOUT_MS = 3e4;
2068
+ const LIST_KEY = "phishing-list";
2069
+ const TRUSTED_KEY = "phishing-trusted";
2070
+ const storedList = z.object({
2071
+ version: z.number().check(z.int(), z.nonnegative()),
2072
+ updatedAt: z.number(),
2073
+ deny: z.string(),
2074
+ allow: z.string()
2075
+ });
2076
+ const storedTrusted = z.array(z.string());
2077
+ const isOrigin = (value) => {
2078
+ try {
2079
+ const url = new URL(value);
2080
+ return (url.protocol === "http:" || url.protocol === "https:") && url.origin === value;
2081
+ } catch {
2082
+ return false;
2083
+ }
2084
+ };
2085
+ const encoder = new TextEncoder();
2086
+ const decoder = new TextDecoder();
2087
+ var PhishingController = class extends Controller {
2088
+ options;
2089
+ fetchGateway;
2090
+ deny;
2091
+ allow;
2092
+ inflight;
2093
+ abort;
2094
+ cancelTimer;
2095
+ epoch = 0;
2096
+ destroyed = false;
2097
+ constructor(options) {
2098
+ super({
2099
+ name: "phishing",
2100
+ defaultState: () => ({
2101
+ version: null,
2102
+ updatedAt: null,
2103
+ trusted: []
2104
+ })
2105
+ });
2106
+ this.options = options;
2107
+ this.fetchGateway = gatewayFetch(options.fetch, options.gateway);
2108
+ }
2109
+ async init() {
2110
+ await this.load();
2111
+ await this.sync();
2112
+ this.arm();
2113
+ }
2114
+ async destroy() {
2115
+ this.destroyed = true;
2116
+ this.epoch += 1;
2117
+ this.cancelTimer?.();
2118
+ this.cancelTimer = void 0;
2119
+ this.abort?.abort();
2120
+ await Promise.resolve();
2121
+ }
2122
+ check(url) {
2123
+ const candidates = phishingCandidates(url);
2124
+ if (candidates.length === 0) return "clear";
2125
+ const { deny, allow } = this;
2126
+ if (deny === void 0 || allow === void 0) return "unchecked";
2127
+ for (const candidate of candidates) {
2128
+ const hash = phishingHash(candidate);
2129
+ if (contains(allow, hash)) return "clear";
2130
+ if (contains(deny, hash)) return this.getState().trusted.includes(new URL(url).origin) ? "trusted" : "blocked";
2131
+ }
2132
+ return "clear";
2133
+ }
2134
+ /** Fetches a snapshot or diff from the gateway; one request at a time, never throws. */
2135
+ async sync() {
2136
+ const { gateway } = this.options;
2137
+ if (gateway === void 0) return;
2138
+ if (this.inflight !== void 0) return this.inflight;
2139
+ const run = async () => {
2140
+ try {
2141
+ await this.fetchAndApply(gateway);
2142
+ } finally {
2143
+ this.inflight = void 0;
2144
+ }
2145
+ };
2146
+ this.inflight = run();
2147
+ return this.inflight;
2148
+ }
2149
+ async trust(origin) {
2150
+ this.assertOrigin(origin);
2151
+ const { trusted } = this.getState();
2152
+ if (!trusted.includes(origin)) await this.saveTrusted([...trusted, origin]);
2153
+ }
2154
+ async untrust(origin) {
2155
+ this.assertOrigin(origin);
2156
+ const { trusted } = this.getState();
2157
+ if (trusted.includes(origin)) await this.saveTrusted(trusted.filter((entry) => entry !== origin));
2158
+ }
2159
+ assertOrigin(origin) {
2160
+ if (!isOrigin(origin)) throw new Error("a trusted origin must be http(s)://host[:port]");
2161
+ }
2162
+ async saveTrusted(trusted) {
2163
+ this.update((state) => ({
2164
+ ...state,
2165
+ trusted
2166
+ }));
2167
+ await this.options.publicStore.put(TRUSTED_KEY, encoder.encode(JSON.stringify(trusted)));
2168
+ }
2169
+ arm() {
2170
+ if (this.destroyed) return;
2171
+ this.cancelTimer = this.options.setTimer(PHISHING_REFRESH_MS, () => {
2172
+ this.refresh();
2173
+ });
2174
+ }
2175
+ async refresh() {
2176
+ await this.sync();
2177
+ this.arm();
2178
+ }
2179
+ async load() {
2180
+ const { publicStore, logger } = this.options;
2181
+ try {
2182
+ const rawList = await publicStore.get(LIST_KEY);
2183
+ if (rawList !== void 0 && !this.restoreList(rawList)) logger.warn("ignoring a malformed stored phishing list");
2184
+ const rawTrusted = await publicStore.get(TRUSTED_KEY);
2185
+ if (rawTrusted !== void 0) {
2186
+ const trusted = parseWith(storedTrusted, JSON.parse(decoder.decode(rawTrusted)));
2187
+ if (trusted === void 0 || !trusted.every(isOrigin)) logger.warn("ignoring a malformed stored trusted-origin list");
2188
+ else this.update((state) => ({
2189
+ ...state,
2190
+ trusted
2191
+ }));
2192
+ }
2193
+ } catch (error) {
2194
+ logger.warn("phishing list could not be loaded", error);
2195
+ }
2196
+ }
2197
+ restoreList(raw) {
2198
+ let json;
2199
+ try {
2200
+ json = JSON.parse(decoder.decode(raw));
2201
+ } catch {
2202
+ return false;
2203
+ }
2204
+ const stored = parseWith(storedList, json);
2205
+ const deny = stored === void 0 ? void 0 : decodeHashList(stored.deny);
2206
+ const allow = stored === void 0 ? void 0 : decodeHashList(stored.allow);
2207
+ if (stored === void 0 || deny === void 0 || allow === void 0) return false;
2208
+ this.deny = deny;
2209
+ this.allow = allow;
2210
+ this.update((state) => ({
2211
+ ...state,
2212
+ version: stored.version,
2213
+ updatedAt: stored.updatedAt
2214
+ }));
2215
+ return true;
2216
+ }
2217
+ async fetchAndApply(gateway) {
2218
+ const { version } = this.getState();
2219
+ const url = `${gateway.url.replace(/\/+$/, "")}${phishingListPath}${version === null ? "" : `?since=${String(version)}`}`;
2220
+ const { epoch } = this;
2221
+ const bound = timeoutSignal(SYNC_TIMEOUT_MS, this.options.setTimer);
2222
+ const { cancel } = bound;
2223
+ this.abort = bound;
2224
+ try {
2225
+ const response = await this.fetchGateway(url, { signal: bound.signal });
2226
+ if (!response.ok) throw new Error(`status ${String(response.status)}`);
2227
+ const body = await response.json();
2228
+ if (epoch !== this.epoch) return;
2229
+ await this.apply(body);
2230
+ } catch (error) {
2231
+ this.options.logger.warn("phishing list sync failed", error);
2232
+ } finally {
2233
+ cancel();
2234
+ this.abort = void 0;
2235
+ }
2236
+ }
2237
+ async apply(body) {
2238
+ const response = parseWith(phishingListResponse, body);
2239
+ if (response === void 0) throw new Error("malformed phishing list response");
2240
+ const { version } = this.getState();
2241
+ if (response.kind === "current") {
2242
+ if (this.deny === void 0 || response.version !== version) {
2243
+ this.update((state) => ({
2244
+ ...state,
2245
+ version: null
2246
+ }));
2247
+ return;
2248
+ }
2249
+ const updatedAt = this.options.now();
2250
+ this.update((state) => ({
2251
+ ...state,
2252
+ updatedAt
2253
+ }));
2254
+ return;
2255
+ }
2256
+ if (response.kind === "diff") {
2257
+ if (response.from !== version || this.deny === void 0 || this.allow === void 0) {
2258
+ this.update((state) => ({
2259
+ ...state,
2260
+ version: null
2261
+ }));
2262
+ return;
2263
+ }
2264
+ const [denyAdd, denyRemove, allowAdd, allowRemove] = [
2265
+ decodeHashList(response.deny.add),
2266
+ decodeHashList(response.deny.remove),
2267
+ decodeHashList(response.allow.add),
2268
+ decodeHashList(response.allow.remove)
2269
+ ];
2270
+ if (denyAdd === void 0 || denyRemove === void 0 || allowAdd === void 0 || allowRemove === void 0) throw new Error("malformed phishing list diff");
2271
+ await this.persist(response.version, applyDiff(this.deny, denyAdd, denyRemove), applyDiff(this.allow, allowAdd, allowRemove));
2272
+ return;
2273
+ }
2274
+ const deny = decodeHashList(response.deny);
2275
+ const allow = decodeHashList(response.allow);
2276
+ if (deny === void 0 || allow === void 0) throw new Error("malformed phishing list snapshot");
2277
+ await this.persist(response.version, deny, allow);
2278
+ }
2279
+ async persist(version, deny, allow) {
2280
+ const updatedAt = this.options.now();
2281
+ this.deny = deny;
2282
+ this.allow = allow;
2283
+ this.update((state) => ({
2284
+ ...state,
2285
+ version,
2286
+ updatedAt
2287
+ }));
2288
+ await this.options.publicStore.put(LIST_KEY, encoder.encode(JSON.stringify({
2289
+ version,
2290
+ updatedAt,
2291
+ deny: encodeHashList(deny),
2292
+ allow: encodeHashList(allow)
2293
+ })));
2294
+ }
2295
+ };
1779
2296
  // src/chains/bitcoin-scan.ts
1780
2297
  /**
1781
2298
  * Gap-20 BIP-44/86 account scanning over Esplora — derives /0/* and /1/* from the account xpub,
@@ -2140,7 +2657,7 @@ const check = async (family, run) => {
2140
2657
  } catch (error) {
2141
2658
  return [family, {
2142
2659
  used: false,
2143
- error: errorMessage$1(error)
2660
+ error: errorMessage(error)
2144
2661
  }];
2145
2662
  }
2146
2663
  };
@@ -2816,6 +3333,39 @@ function persistedToState(tree) {
2816
3333
  totals: tree.totals
2817
3334
  };
2818
3335
  }
3336
+ // src/requests/simulation.ts
3337
+ const SIMULATION_TIMEOUT_MS = 1e4;
3338
+ const noop = () => void 0;
3339
+ /**
3340
+ * Runs a simulation under the 10 s bound of the injected timer. A throw from `run` and the timeout
3341
+ * are `unavailable`; the timer is always cancelled.
3342
+ */
3343
+ async function boundedSimulation(run, setTimer) {
3344
+ const stopTimer = { cancel: noop };
3345
+ const timeout = new Promise((resolve) => {
3346
+ stopTimer.cancel = setTimer(SIMULATION_TIMEOUT_MS, () => {
3347
+ resolve({
3348
+ status: "unavailable",
3349
+ error: "timeout"
3350
+ });
3351
+ });
3352
+ });
3353
+ const bounded = async () => {
3354
+ try {
3355
+ return await run();
3356
+ } catch (error) {
3357
+ return {
3358
+ status: "unavailable",
3359
+ error: errorMessage(error)
3360
+ };
3361
+ }
3362
+ };
3363
+ try {
3364
+ return await Promise.race([bounded(), timeout]);
3365
+ } finally {
3366
+ stopTimer.cancel();
3367
+ }
3368
+ }
2819
3369
  // src/chains/evm.ts
2820
3370
  /**
2821
3371
  * EVM chain adapter: native transfers through a viem PublicClient injected by NetworkController.
@@ -2880,6 +3430,19 @@ const checkedAddress = (v) => {
2880
3430
  if (!isAddress(v)) throw new TypeError(`malformed evm address: ${v}`);
2881
3431
  return v;
2882
3432
  };
3433
+ /** A contract's own `symbol` and `decimals`, kept only when they are safe to show. */
3434
+ const unverifiedMetadata = (token) => {
3435
+ const symbol = token.symbol === void 0 ? void 0 : safeDisplayText(token.symbol, 32);
3436
+ const decimals = token.decimals === void 0 ? void 0 : safeDecimals(token.decimals);
3437
+ return {
3438
+ ...decimals === void 0 ? {} : { decimals },
3439
+ ...symbol === void 0 ? {} : { symbol }
3440
+ };
3441
+ };
3442
+ const checkedHex = (v) => {
3443
+ if (!isHex(v, { strict: true }) || v.length % 2 !== 0) throw new TypeError("malformed hex data");
3444
+ return v;
3445
+ };
2883
3446
  const hex$1 = (v) => numberToHex(v);
2884
3447
  const evmRpc = async (client, method, params) => client.transport.request({
2885
3448
  method,
@@ -2890,6 +3453,8 @@ const evmRpcHex = async (client, method, params) => {
2890
3453
  if (typeof result !== "string") throw new TypeError(`${method} returned a malformed result`);
2891
3454
  return result;
2892
3455
  };
3456
+ /** Viem's marker for the chain's native asset in traced asset changes. */
3457
+ const NATIVE_MARKER = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
2893
3458
  var EvmChainAdapter = class {
2894
3459
  family = "evm";
2895
3460
  nonces = /* @__PURE__ */ new Map();
@@ -3050,6 +3615,60 @@ var EvmChainAdapter = class {
3050
3615
  if (signed.kind !== "evm.transaction" || bytes === void 0) throw new Error(`unexpected sign result ${signed.kind}`);
3051
3616
  return `0x${[...bytes].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
3052
3617
  }
3618
+ /**
3619
+ * Simulates one call from `from` with traced asset changes. A revert is `reverted`; an
3620
+ * unsupported method, any thrown error or the timeout is `unavailable`. The result is for display
3621
+ * only.
3622
+ */
3623
+ async simulate(client, chainId, from, call, setTimer) {
3624
+ return boundedSimulation(async () => {
3625
+ const result = await simulateCalls(client, {
3626
+ account: checkedAddress(from),
3627
+ calls: [{
3628
+ to: checkedAddress(call.to),
3629
+ value: call.value,
3630
+ data: checkedHex(call.data)
3631
+ }],
3632
+ traceAssetChanges: true
3633
+ });
3634
+ const [first] = result.results;
3635
+ if (first?.status === "failure") return {
3636
+ status: "reverted",
3637
+ error: errorMessage(first.error)
3638
+ };
3639
+ const changes = [];
3640
+ for (const change of result.assetChanges) {
3641
+ if (change.value.diff === 0n) continue;
3642
+ const address = change.token.address.toLowerCase();
3643
+ if (address === NATIVE_MARKER) {
3644
+ changes.push({
3645
+ asset: EVM_NATIVE_ASSET,
3646
+ amount: change.value.diff.toString(10),
3647
+ verified: true
3648
+ });
3649
+ continue;
3650
+ }
3651
+ const asset = checksumEvmAddress(address);
3652
+ const known = lookupEvmToken(evmTokenTable, chainId, asset);
3653
+ changes.push({
3654
+ asset,
3655
+ amount: change.value.diff.toString(10),
3656
+ ...known === void 0 ? {
3657
+ ...unverifiedMetadata(change.token),
3658
+ verified: false
3659
+ } : {
3660
+ decimals: known.decimals,
3661
+ symbol: known.symbol,
3662
+ verified: true
3663
+ }
3664
+ });
3665
+ }
3666
+ return {
3667
+ status: "success",
3668
+ changes
3669
+ };
3670
+ }, setTimer);
3671
+ }
3053
3672
  async broadcast(client, raw) {
3054
3673
  return evmRpcHex(client, "eth_sendRawTransaction", [raw]);
3055
3674
  }
@@ -3320,6 +3939,22 @@ var AssetsController = class extends Controller {
3320
3939
  return;
3321
3940
  }
3322
3941
  }
3942
+ /** Whether `address` is in the built-in token table of `network` or among the custom tokens. */
3943
+ isTracked(network, address) {
3944
+ const wanted = address.toLowerCase();
3945
+ return Object.keys(evmTokenTable[String(this.options.networks.info(network).chainId)] ?? {}).some((known) => known.toLowerCase() === wanted) || (this.customTokens.get(network) ?? []).some((t) => t.address.toLowerCase() === wanted);
3946
+ }
3947
+ /** The token's own `symbol` and `decimals` (EVM only); throws when either read fails. */
3948
+ async tokenMetadata(network, address) {
3949
+ const client = this.options.networks.client(network);
3950
+ const symbol = await this.callToken(client, address, "symbol");
3951
+ const decimals = await this.callToken(client, address, "decimals");
3952
+ if (symbol === void 0 || decimals === void 0) throw new TypeError(`${address} is not a readable ERC-20 token on ${network}`);
3953
+ return {
3954
+ symbol,
3955
+ decimals
3956
+ };
3957
+ }
3323
3958
  /** Reads symbol/decimals on-chain, marks unverified, persists; throws when the calls fail. */
3324
3959
  async addToken(network, address) {
3325
3960
  if (this.options.networks.info(network).family === "solana") {
@@ -3723,6 +4358,37 @@ function idFromName(name) {
3723
4358
  }
3724
4359
  PROGRAM_IDS.token2022;
3725
4360
  const MAX_MESSAGE_BYTES = 1232;
4361
+ const LOOKUP_TABLE_HEADER_BYTES = 56;
4362
+ const ADDRESS_BYTES = 32;
4363
+ const TOKEN_ACCOUNT_MIN_BYTES = 72;
4364
+ const TOKEN_ACCOUNT_OWNER_OFFSET = 32;
4365
+ const TOKEN_ACCOUNT_AMOUNT_OFFSET = 64;
4366
+ const addressDecoder = getAddressDecoder();
4367
+ const parseAccount = (value) => {
4368
+ const record = obj$1(value);
4369
+ const data = record?.["data"];
4370
+ if (record === void 0 || !Array.isArray(data) || typeof data[0] !== "string" || typeof record["owner"] !== "string") return;
4371
+ return {
4372
+ lamports: BigInt(str(record["lamports"])),
4373
+ owner: record["owner"],
4374
+ data: base64.decode(data[0])
4375
+ };
4376
+ };
4377
+ const accountList = (value) => {
4378
+ return (Array.isArray(value) ? value : []).map(parseAccount);
4379
+ };
4380
+ const u64Decoder = getU64Decoder();
4381
+ const readU64 = (data, offset) => u64Decoder.decode(data, offset);
4382
+ /** Token and Token-2022 accounts owned by `owner`: balance per mint. */
4383
+ const tokenBalances = (watch, accounts, owner) => {
4384
+ const balances = /* @__PURE__ */ new Map();
4385
+ for (const [index, account] of accounts.entries()) {
4386
+ if (watch[index] === void 0 || account === void 0 || account.owner !== PROGRAM_IDS.token && account.owner !== PROGRAM_IDS.token2022 || account.data.length < TOKEN_ACCOUNT_MIN_BYTES || addressDecoder.decode(account.data.slice(TOKEN_ACCOUNT_OWNER_OFFSET, 64)) !== owner) continue;
4387
+ const mint = addressDecoder.decode(account.data.slice(0, ADDRESS_BYTES));
4388
+ balances.set(mint, (balances.get(mint) ?? 0n) + readU64(account.data, TOKEN_ACCOUNT_AMOUNT_OFFSET));
4389
+ }
4390
+ return balances;
4391
+ };
3726
4392
  const CU_SIMULATE_LIMIT = 14e5;
3727
4393
  const b64 = (bytes) => base64.encode(bytes);
3728
4394
  const isObject$7 = (v) => typeof v === "object" && v !== null;
@@ -3782,7 +4448,7 @@ var SolanaChainAdapter = class {
3782
4448
  const blockhashValue = typeof value?.["blockhash"] === "string" ? value["blockhash"] : "";
3783
4449
  const lastValidBlockHeight = BigInt(str(value?.["lastValidBlockHeight"], "0"));
3784
4450
  const compiled = this.compile(from, instructions, blockhashValue, lastValidBlockHeight);
3785
- const units = await this.simulate(rpc, compiled.messageBytes);
4451
+ const units = await this.simulateUnits(rpc, compiled.messageBytes);
3786
4452
  return {
3787
4453
  family: "solana",
3788
4454
  network,
@@ -3807,14 +4473,12 @@ var SolanaChainAdapter = class {
3807
4473
  }
3808
4474
  return [...out];
3809
4475
  }
3810
- /** Unsigned wire bytes: shortvec(1) sig count + 64-byte zero sig + message (for simulate). */
4476
+ /** Unsigned wire bytes: one zeroed signature per required signer, then the message. */
3811
4477
  wireBytes(messageBytes) {
3812
- const out = new Uint8Array(65 + messageBytes.length);
3813
- out[0] = 1;
3814
- out.set(messageBytes, 65);
3815
- return out;
4478
+ const { numRequiredSignatures } = parseCompiledMessage(messageBytes);
4479
+ return this.finalize(messageBytes, Array.from({ length: numRequiredSignatures }, () => /* @__PURE__ */ new Uint8Array(64)));
3816
4480
  }
3817
- async simulate(rpc, messageBytes) {
4481
+ async simulateUnits(rpc, messageBytes) {
3818
4482
  const result = obj$1(await this.rpc(rpc, "simulateTransaction", [b64(this.wireBytes(messageBytes)), {
3819
4483
  encoding: "base64",
3820
4484
  sigVerify: false,
@@ -3872,6 +4536,91 @@ var SolanaChainAdapter = class {
3872
4536
  ...tx.instructions
3873
4537
  ], tx.blockhash, tx.lastValidBlockHeight).messageBytes;
3874
4538
  }
4539
+ /**
4540
+ * Simulates `message` for `owner`: lamports and Token/Token-2022 balance changes of the owner's
4541
+ * accounts from account state read before and returned after `simulateTransaction`. The two reads
4542
+ * are not atomic. A node error or the 10 s timeout is `unavailable`.
4543
+ */
4544
+ async simulate(rpc, network, owner, message, setTimer) {
4545
+ return boundedSimulation(async () => this.simulateAccounts(rpc, network, owner, message), setTimer);
4546
+ }
4547
+ async lookupWritable(rpc, lookups) {
4548
+ if (lookups.length === 0) return [];
4549
+ const result = obj$1(await this.rpc(rpc, "getMultipleAccounts", [lookups.map((lookup) => lookup.address), {
4550
+ encoding: "base64",
4551
+ commitment: "confirmed"
4552
+ }]));
4553
+ const tables = accountList(result?.["value"]);
4554
+ const writable = [];
4555
+ for (const [index, lookup] of lookups.entries()) {
4556
+ const data = tables[index]?.data;
4557
+ if (data === void 0) throw new Error(`lookup table ${lookup.address} not found`);
4558
+ for (const entry of lookup.writableIndexes) {
4559
+ const start = LOOKUP_TABLE_HEADER_BYTES + entry * ADDRESS_BYTES;
4560
+ if (start + ADDRESS_BYTES > data.length) throw new Error("lookup table index out of range");
4561
+ writable.push(addressDecoder.decode(data.slice(start, start + ADDRESS_BYTES)));
4562
+ }
4563
+ }
4564
+ return writable;
4565
+ }
4566
+ async simulateAccounts(rpc, network, owner, message) {
4567
+ const parsed = parseCompiledMessage(message);
4568
+ const watch = [.../* @__PURE__ */ new Set([...parsed.staticAccounts, ...await this.lookupWritable(rpc, parsed.lookups)])];
4569
+ const before = obj$1(await this.rpc(rpc, "getMultipleAccounts", [watch, {
4570
+ encoding: "base64",
4571
+ commitment: "confirmed"
4572
+ }]));
4573
+ const result = obj$1(await this.rpc(rpc, "simulateTransaction", [b64(this.wireBytes(message)), {
4574
+ encoding: "base64",
4575
+ sigVerify: false,
4576
+ replaceRecentBlockhash: true,
4577
+ commitment: "confirmed",
4578
+ accounts: {
4579
+ addresses: watch,
4580
+ encoding: "base64"
4581
+ }
4582
+ }]));
4583
+ const value = obj$1(result?.["value"]);
4584
+ if (value?.["err"] !== null && value?.["err"] !== void 0) {
4585
+ const last = (Array.isArray(value["logs"]) ? value["logs"] : []).at(-1);
4586
+ return {
4587
+ status: "reverted",
4588
+ error: `${JSON.stringify(value["err"])}${typeof last === "string" ? ` (${last})` : ""}`
4589
+ };
4590
+ }
4591
+ const pre = accountList(before?.["value"]);
4592
+ const post = accountList(value?.["accounts"]);
4593
+ const changes = [];
4594
+ const ownerIndex = watch.indexOf(owner);
4595
+ if (ownerIndex !== -1) {
4596
+ const delta = (post[ownerIndex]?.lamports ?? 0n) - (pre[ownerIndex]?.lamports ?? 0n);
4597
+ if (delta !== 0n) changes.push({
4598
+ asset: SOLANA_NATIVE_ASSET,
4599
+ amount: delta.toString(10),
4600
+ verified: true
4601
+ });
4602
+ }
4603
+ const was = tokenBalances(watch, pre, owner);
4604
+ const now = tokenBalances(watch, post, owner);
4605
+ for (const mint of /* @__PURE__ */ new Set([...was.keys(), ...now.keys()])) {
4606
+ const delta = (now.get(mint) ?? 0n) - (was.get(mint) ?? 0n);
4607
+ if (delta === 0n) continue;
4608
+ const known = solanaTokenTable[network]?.[mint];
4609
+ changes.push({
4610
+ asset: mint,
4611
+ amount: delta.toString(10),
4612
+ ...known === void 0 ? { verified: false } : {
4613
+ decimals: known.decimals,
4614
+ symbol: known.symbol,
4615
+ verified: true
4616
+ }
4617
+ });
4618
+ }
4619
+ return {
4620
+ status: "success",
4621
+ changes
4622
+ };
4623
+ }
3875
4624
  /** Wire transaction bytes — sigCount shortvec + each 64-byte sig + message. */
3876
4625
  finalize(messageBytes, signatures) {
3877
4626
  for (const sig of signatures) if (sig.length !== 64) throw new Error(`solana signature must be 64 bytes, got ${sig.length}`);
@@ -4263,7 +5012,11 @@ const MAX_RETRIES = 3;
4263
5012
  const MAX_BACKOFF_MS = 2e3;
4264
5013
  const REQUEST_TIMEOUT_MS = 1e4;
4265
5014
  /** Bounded-concurrency + 429-aware ordered failover over the endpoint list. */
4266
- const esplora = (endpoints, fetchFn, sleep, timeoutMs = REQUEST_TIMEOUT_MS) => {
5015
+ const esplora = (endpoints, fetchFn, deps, timeoutMs = REQUEST_TIMEOUT_MS) => {
5016
+ const { setTimer, random } = deps;
5017
+ const sleep = async (ms) => new Promise((resolve) => {
5018
+ setTimer(ms, resolve);
5019
+ });
4267
5020
  let inFlight = 0;
4268
5021
  const waiters = [];
4269
5022
  const acquire = async () => {
@@ -4279,11 +5032,12 @@ const esplora = (endpoints, fetchFn, sleep, timeoutMs = REQUEST_TIMEOUT_MS) => {
4279
5032
  const backoff = async (headers, retry) => {
4280
5033
  const ra = headers.get("retry-after");
4281
5034
  const retryAfterMs = ra !== null && ra !== "" && !Number.isNaN(Number(ra)) ? Number(ra) * 1e3 : void 0;
4282
- const jitter = Math.floor(Math.random() * 100);
5035
+ const jitter = (random(1)[0] ?? 0) % 100;
4283
5036
  await sleep(retryAfterMs ?? Math.min(100 * 2 ** retry + jitter, MAX_BACKOFF_MS));
4284
5037
  };
4285
5038
  const request = async (base, path, body) => {
4286
5039
  await acquire();
5040
+ const bound = timeoutSignal(timeoutMs, setTimer);
4287
5041
  try {
4288
5042
  let res;
4289
5043
  try {
@@ -4293,7 +5047,7 @@ const esplora = (endpoints, fetchFn, sleep, timeoutMs = REQUEST_TIMEOUT_MS) => {
4293
5047
  headers: { "content-type": "text/plain" },
4294
5048
  body
4295
5049
  },
4296
- signal: AbortSignal.timeout(timeoutMs)
5050
+ signal: bound.signal
4297
5051
  });
4298
5052
  } catch (error) {
4299
5053
  throw new EsploraError(`esplora ${base}${path}: request failed (${error instanceof Error ? error.name : "unknown"})`, true);
@@ -4307,6 +5061,7 @@ const esplora = (endpoints, fetchFn, sleep, timeoutMs = REQUEST_TIMEOUT_MS) => {
4307
5061
  return { value: text };
4308
5062
  }
4309
5063
  } finally {
5064
+ bound.cancel();
4310
5065
  release();
4311
5066
  }
4312
5067
  };
@@ -4441,9 +5196,6 @@ var BitcoinChainAdapter = class {
4441
5196
  * without code here. Custom RPC URLs are validated against the registry chain id with `eth_chainId`
4442
5197
  * and persisted in the EngineStore.
4443
5198
  */
4444
- const esploraSleep = async (ms) => new Promise((resolve) => {
4445
- setTimeout(resolve, ms);
4446
- });
4447
5199
  /** Bound on the unlock-time `/v1/networks` read so a dead gateway cannot stall unlocking. */
4448
5200
  const GATEWAY_PROBE_TIMEOUT_MS = 5e3;
4449
5201
  const isObject$4 = (v) => typeof v === "object" && v !== null;
@@ -4461,7 +5213,7 @@ const makeClient = (info, urls, fetchFn) => createPublicClient({
4461
5213
  transport: fallback(urls.map((url) => http(url, { fetchFn }))),
4462
5214
  batch: { multicall: true }
4463
5215
  });
4464
- const esploraClient = (urls, fetchFn) => esplora(urls, async (url, init) => {
5216
+ const esploraClient = (urls, fetchFn, deps) => esplora(urls, async (url, init) => {
4465
5217
  const r = await fetchFn(url, init);
4466
5218
  return {
4467
5219
  ok: r.ok,
@@ -4470,7 +5222,7 @@ const esploraClient = (urls, fetchFn) => esplora(urls, async (url, init) => {
4470
5222
  json: async () => r.json(),
4471
5223
  text: async () => r.text()
4472
5224
  };
4473
- }, esploraSleep);
5225
+ }, deps);
4474
5226
  const solanaCaller = (urls, fetchFn) => ({ call: async (method, params) => {
4475
5227
  const attempt = async (rest, last) => {
4476
5228
  const [url, ...next] = rest;
@@ -4503,7 +5255,7 @@ var NetworkController = class extends Controller {
4503
5255
  engineStore;
4504
5256
  clients = /* @__PURE__ */ new Map();
4505
5257
  gatewayBase;
4506
- gatewayOrigin;
5258
+ gatewayFetch;
4507
5259
  /** Networks the gateway reported at unlock; empty while locked or when the read failed. */
4508
5260
  gatewayServed = /* @__PURE__ */ new Set();
4509
5261
  constructor(options) {
@@ -4512,10 +5264,8 @@ var NetworkController = class extends Controller {
4512
5264
  defaultState: () => ({ customRpc: {} })
4513
5265
  });
4514
5266
  this.options = options;
4515
- if (options.gateway !== void 0) {
4516
- this.gatewayBase = options.gateway.url.replace(/\/+$/, "");
4517
- this.gatewayOrigin = new URL(options.gateway.url).origin;
4518
- }
5267
+ if (options.gateway !== void 0) this.gatewayBase = options.gateway.url.replace(/\/+$/, "");
5268
+ this.gatewayFetch = gatewayFetch(options.fetch, options.gateway);
4519
5269
  }
4520
5270
  async init() {
4521
5271
  this.engineStore = await this.options.openStore();
@@ -4539,8 +5289,9 @@ var NetworkController = class extends Controller {
4539
5289
  async loadGatewayNetworks() {
4540
5290
  if (this.gatewayBase === void 0) return;
4541
5291
  const url = `${this.gatewayBase}${networksPath}`;
5292
+ const probe = timeoutSignal(GATEWAY_PROBE_TIMEOUT_MS, this.options.setTimer);
4542
5293
  try {
4543
- const res = await this.gatewayFetch(url, { signal: AbortSignal.timeout(GATEWAY_PROBE_TIMEOUT_MS) });
5294
+ const res = await this.gatewayFetch(url, { signal: probe.signal });
4544
5295
  if (!res.ok) throw new Error(`status ${res.status}`);
4545
5296
  const body = await res.json();
4546
5297
  const served = parseWith(servedNetworksResponse, body);
@@ -4549,20 +5300,10 @@ var NetworkController = class extends Controller {
4549
5300
  } catch {
4550
5301
  this.gatewayServed = /* @__PURE__ */ new Set();
4551
5302
  this.options.logger.warn(`gateway unavailable, not used for this session: ${url}`);
5303
+ } finally {
5304
+ probe.cancel();
4552
5305
  }
4553
5306
  }
4554
- /** `fetch` that adds the install id to requests bound for the gateway's origin only. */
4555
- gatewayFetch = async (input, init) => {
4556
- const { gateway } = this.options;
4557
- const target = input instanceof Request ? input.url : String(input);
4558
- if (gateway === void 0 || new URL(target).origin !== this.gatewayOrigin) return this.options.fetch(input, init);
4559
- const headers = new Headers(init?.headers);
4560
- headers.set(INSTALL_ID_HEADER, gateway.installId);
4561
- return this.options.fetch(input, {
4562
- ...init,
4563
- headers
4564
- });
4565
- };
4566
5307
  async destroy() {
4567
5308
  this.lock();
4568
5309
  await Promise.resolve();
@@ -4621,7 +5362,10 @@ var NetworkController = class extends Controller {
4621
5362
  return this.independent(network, (hosts) => solanaCaller(hosts, this.options.fetch));
4622
5363
  }
4623
5364
  independentEsplora(network) {
4624
- return this.independent(network, (hosts) => esploraClient(hosts, this.options.fetch));
5365
+ return this.independent(network, (hosts) => esploraClient(hosts, this.options.fetch, {
5366
+ setTimer: this.options.setTimer,
5367
+ random: this.options.random
5368
+ }));
4625
5369
  }
4626
5370
  /** Networks with at least one configured endpoint or served by the gateway, by family. */
4627
5371
  enabled(family) {
@@ -4644,7 +5388,10 @@ var NetworkController = class extends Controller {
4644
5388
  esplora(network) {
4645
5389
  const urls = this.endpoints(network);
4646
5390
  if (urls.length === 0) throw new Error(`no esplora endpoint for ${network}`);
4647
- return esploraClient(urls, this.gatewayFetch);
5391
+ return esploraClient(urls, this.gatewayFetch, {
5392
+ setTimer: this.options.setTimer,
5393
+ random: this.options.random
5394
+ });
4648
5395
  }
4649
5396
  /** Validate a custom endpoint's reported chain id, then persist it first in the list. */
4650
5397
  async addRpc(network, url) {
@@ -5939,7 +6686,7 @@ const signSubmit = async (ctx, tx, apis, request, verify, broadcast) => {
5939
6686
  } catch (error) {
5940
6687
  await ctx.transition(tracked, {
5941
6688
  state: "rejected",
5942
- error: errorMessage$1(error)
6689
+ error: errorMessage(error)
5943
6690
  });
5944
6691
  throw error;
5945
6692
  }
@@ -5955,7 +6702,7 @@ const signSubmit = async (ctx, tx, apis, request, verify, broadcast) => {
5955
6702
  } catch (error) {
5956
6703
  await ctx.transition(tracked, {
5957
6704
  state: "failed",
5958
- error: errorMessage$1(error)
6705
+ error: errorMessage(error)
5959
6706
  });
5960
6707
  throw error;
5961
6708
  }
@@ -6010,6 +6757,11 @@ const createEvmRoute = () => {
6010
6757
  const intent = decodeEvm(request);
6011
6758
  const txId = newId(ctx.options.random);
6012
6759
  const chosen = quote;
6760
+ const simulation = await evm.simulate(client, info.chainId, from, {
6761
+ to: feed.to,
6762
+ value: feed.value,
6763
+ data: feed.data
6764
+ }, ctx.options.setTimer);
6013
6765
  const submit = async (verify) => {
6014
6766
  pending.set(txId, {
6015
6767
  unsigned: feed,
@@ -6043,6 +6795,7 @@ const createEvmRoute = () => {
6043
6795
  network,
6044
6796
  intent,
6045
6797
  checks: collectChecks(flags),
6798
+ simulation,
6046
6799
  staleReason: () => evm.nonceConsumed(network, from, unsigned.nonce) ? "nonce already used by a newer transaction — start over" : void 0,
6047
6800
  submit,
6048
6801
  release: () => void 0
@@ -6275,6 +7028,7 @@ const prepareSolana = async (ctx, params) => {
6275
7028
  };
6276
7029
  const intent = ext === void 0 || params.token === void 0 ? decodeSolana(request, from) : token2022Intent(decodeSolana(request, from), ext, params.token, amount);
6277
7030
  const id = newId(ctx.options.random);
7031
+ const simulation = await solana.simulate(rpc, network, from, messageBytes, ctx.options.setTimer);
6278
7032
  const submit = async (verify) => {
6279
7033
  let tx = {
6280
7034
  id,
@@ -6312,6 +7066,7 @@ const prepareSolana = async (ctx, params) => {
6312
7066
  network,
6313
7067
  intent,
6314
7068
  checks: collectChecks(flags),
7069
+ simulation,
6315
7070
  staleReason: async () => await solana.blockHeight(rpc) > unsigned.lastValidBlockHeight ? "blockhash expired — start over" : void 0,
6316
7071
  submit,
6317
7072
  release: () => void 0
@@ -6625,13 +7380,30 @@ var TransactionController = class extends Controller {
6625
7380
  }
6626
7381
  };
6627
7382
  // src/engine.ts
6628
- /**
6629
- * Composition root: wires the Wallet's lock state to the SparkController's lifecycle. Unlocked →
6630
- * open the EngineStore and start every declared account; locked → abort event loops, close every
6631
- * client, close the store and reset account state. Transitions are serialized on one promise chain,
6632
- * so an unlock→lock flip can never overlap a still-opening store.
6633
- */
7383
+ const defaultSetTimer = (ms, fn) => {
7384
+ const id = setTimeout(fn, ms);
7385
+ return () => {
7386
+ clearTimeout(id);
7387
+ };
7388
+ };
6634
7389
  function createWalletEngine(options) {
7390
+ const setTimer = options.setTimer ?? defaultSetTimer;
7391
+ const phishing = new PhishingController({
7392
+ publicStore: options.publicStore,
7393
+ gateway: options.gateway,
7394
+ fetch: options.fetch,
7395
+ now: options.now,
7396
+ setTimer,
7397
+ logger: options.logger
7398
+ });
7399
+ const startPhishing = async () => {
7400
+ try {
7401
+ await phishing.init();
7402
+ } catch (error) {
7403
+ options.logger.warn("phishing list failed to start", error);
7404
+ }
7405
+ };
7406
+ startPhishing();
6635
7407
  const backup = new BackupController({
6636
7408
  wallet: options.wallet,
6637
7409
  cloud: options.cloud,
@@ -6656,17 +7428,14 @@ function createWalletEngine(options) {
6656
7428
  rpc: options.rpc ?? {},
6657
7429
  openStore: options.openStore,
6658
7430
  logger: options.logger,
6659
- gateway: options.gateway
7431
+ gateway: options.gateway,
7432
+ setTimer,
7433
+ random: options.random
6660
7434
  });
6661
7435
  const assets = new AssetsController({
6662
7436
  networks,
6663
7437
  openStore: options.openStore,
6664
- setTimer: options.setTimer ?? ((ms, fn) => {
6665
- const id = setTimeout(() => {
6666
- fn();
6667
- }, ms);
6668
- return () => clearTimeout(id);
6669
- }),
7438
+ setTimer,
6670
7439
  logger: options.logger
6671
7440
  });
6672
7441
  const transactions = new TransactionController({
@@ -6674,12 +7443,7 @@ function createWalletEngine(options) {
6674
7443
  networks,
6675
7444
  openStore: options.openStore,
6676
7445
  random: options.random,
6677
- setTimer: options.setTimer ?? ((ms, fn) => {
6678
- const id = setTimeout(() => {
6679
- fn();
6680
- }, ms);
6681
- return () => clearTimeout(id);
6682
- }),
7446
+ setTimer,
6683
7447
  now: options.now,
6684
7448
  logger: options.logger
6685
7449
  });
@@ -6690,6 +7454,12 @@ function createWalletEngine(options) {
6690
7454
  logger: options.logger
6691
7455
  });
6692
7456
  const requests = new RequestController({
7457
+ phishing,
7458
+ tokens: {
7459
+ metadata: async (network, address) => assets.tokenMetadata(network, address),
7460
+ add: async (network, address) => assets.addToken(network, address)
7461
+ },
7462
+ simulateSolana: async (account, network, message) => new SolanaChainAdapter().simulate(networks.solanaRpc(network), network, account.address, message, setTimer),
6693
7463
  transactions,
6694
7464
  addressBook,
6695
7465
  openStore: options.openStore,
@@ -6764,12 +7534,7 @@ function createWalletEngine(options) {
6764
7534
  fetch: options.fetch,
6765
7535
  random: options.random,
6766
7536
  now: options.now,
6767
- setTimer: options.setTimer ?? ((ms, fn) => {
6768
- const id = setTimeout(() => {
6769
- fn();
6770
- }, ms);
6771
- return () => clearTimeout(id);
6772
- }),
7537
+ setTimer,
6773
7538
  logger: options.logger
6774
7539
  });
6775
7540
  const accounts = new AccountTreeController({
@@ -6797,6 +7562,8 @@ function createWalletEngine(options) {
6797
7562
  logger: options.logger
6798
7563
  });
6799
7564
  const connections = new ConnectionController({
7565
+ phishing,
7566
+ setTimer,
6800
7567
  openStore: options.openStore,
6801
7568
  random: options.random,
6802
7569
  now: options.now,
@@ -6831,7 +7598,8 @@ function createWalletEngine(options) {
6831
7598
  connections,
6832
7599
  requests,
6833
7600
  networks,
6834
- defaultNetwork: () => networks.enabled("evm")[0] ?? "eip155:1"
7601
+ defaultNetwork: () => networks.enabled("evm")[0] ?? "eip155:1",
7602
+ isTracked: (network, address) => assets.isTracked(network, address)
6835
7603
  });
6836
7604
  const nip07 = new Nip07Handler({
6837
7605
  connections,
@@ -6850,15 +7618,10 @@ function createWalletEngine(options) {
6850
7618
  network: options.sparkNetwork
6851
7619
  };
6852
7620
  },
7621
+ now: options.now,
6853
7622
  alias: options.weblnAlias,
6854
7623
  lightningMaxFee: options.lightningMaxFee,
6855
7624
  sleep: async (ms) => {
6856
- const setTimer = options.setTimer ?? ((ms_, fn) => {
6857
- const timer = setTimeout(fn, ms_);
6858
- return () => {
6859
- clearTimeout(timer);
6860
- };
6861
- });
6862
7625
  await new Promise((resolve) => {
6863
7626
  setTimer(ms, resolve);
6864
7627
  });
@@ -6988,7 +7751,11 @@ function createWalletEngine(options) {
6988
7751
  now: options.now
6989
7752
  }, params)
6990
7753
  },
6991
- unsubscribe
7754
+ phishing,
7755
+ unsubscribe: () => {
7756
+ unsubscribe();
7757
+ phishing.destroy();
7758
+ }
6992
7759
  };
6993
7760
  }
6994
7761
  // src/backup/memory.ts
@@ -7023,6 +7790,6 @@ function createMemoryCloudStore(backing) {
7023
7790
  }
7024
7791
  };
7025
7792
  }
7026
- export { AccountTreeController, AccountTreeError, AddressBookController, AddressBookError, BackupController, BackupControllerError, ConnectionController, Controller, Eip1193Handler, EngineStoreError, MetaSyncController, MetaSyncError, PaymentError, ProviderError, REQUEST_TTL_MS, RequestController, SparkController, SparkControllerError, createEventBus, createMemoryCloudStore, createMemoryEngineStore, createWalletEngine, decodeExitChain, encodeExitChain, parsePayment, prepareZap, resolvePayment, sparkStore };
7793
+ export { AccountTreeController, AccountTreeError, AddressBookController, AddressBookError, BackupController, BackupControllerError, ConnectionController, Controller, Eip1193Handler, EngineStoreError, MetaSyncController, MetaSyncError, PHISHING_REFRESH_MS, PaymentError, PhishingController, ProviderError, REQUEST_TTL_MS, RequestController, SparkController, SparkControllerError, createEventBus, createMemoryCloudStore, createMemoryEngineStore, createMemoryPublicStore, createWalletEngine, decodeExitChain, encodeExitChain, parsePayment, prepareZap, resolvePayment, sparkStore };
7027
7794
 
7028
7795
  //# sourceMappingURL=index.mjs.map