@qntx/wallet-engine 0.13.0 → 0.14.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.
Files changed (80) hide show
  1. package/README.md +1057 -20
  2. package/dist/apps-fiat24.d.mts +202 -0
  3. package/dist/apps-fiat24.mjs +1378 -0
  4. package/dist/apps-fiat24.mjs.map +1 -0
  5. package/dist/apps-hyperliquid.d.mts +549 -0
  6. package/dist/apps-hyperliquid.mjs +2742 -0
  7. package/dist/apps-hyperliquid.mjs.map +1 -0
  8. package/dist/apps-polymarket.d.mts +729 -0
  9. package/dist/apps-polymarket.mjs +3786 -0
  10. package/dist/apps-polymarket.mjs.map +1 -0
  11. package/dist/apps.d.mts +136 -0
  12. package/dist/apps.mjs +535 -0
  13. package/dist/apps.mjs.map +1 -0
  14. package/dist/connect-BY1C5ZRI.mjs +210 -0
  15. package/dist/connect-BY1C5ZRI.mjs.map +1 -0
  16. package/dist/connect.d.mts +17 -9
  17. package/dist/connect.mjs +3 -185
  18. package/dist/{errors-CQnlTc1i.d.mts → controller-DpNVHVsj.d.mts} +1093 -758
  19. package/dist/controller-rMnaxKAH.mjs +46 -0
  20. package/dist/controller-rMnaxKAH.mjs.map +1 -0
  21. package/dist/decimal-COJ4g8qy.mjs +38 -0
  22. package/dist/decimal-COJ4g8qy.mjs.map +1 -0
  23. package/dist/eligibility-BfM9ybYZ.mjs +48 -0
  24. package/dist/eligibility-BfM9ybYZ.mjs.map +1 -0
  25. package/dist/engine-Dic_kkEr.d.mts +1829 -0
  26. package/dist/errors-B8W-hoYW.d.mts +7 -0
  27. package/dist/errors-horUy5k1.mjs +24 -0
  28. package/dist/errors-horUy5k1.mjs.map +1 -0
  29. package/dist/gateway-contract.d.mts +3 -608
  30. package/dist/gateway-contract.mjs +1467 -161
  31. package/dist/gateway-contract.mjs.map +1 -1
  32. package/dist/idb.d.mts +5 -0
  33. package/dist/idb.mjs +122 -46
  34. package/dist/idb.mjs.map +1 -1
  35. package/dist/index-vBgfOFIh.d.mts +2227 -0
  36. package/dist/index.d.mts +58 -618
  37. package/dist/index.mjs +21963 -6836
  38. package/dist/index.mjs.map +1 -1
  39. package/dist/json-BDwV38cj.mjs +15 -0
  40. package/dist/json-BDwV38cj.mjs.map +1 -0
  41. package/dist/link-Ceq8Dggp.mjs +139 -0
  42. package/dist/link-Ceq8Dggp.mjs.map +1 -0
  43. package/dist/primitives-DbSHLZKq.mjs +31 -0
  44. package/dist/primitives-DbSHLZKq.mjs.map +1 -0
  45. package/dist/push-message-AQuzoNFY.d.mts +84 -0
  46. package/dist/push-message-kbnH1A5w.mjs +142 -0
  47. package/dist/push-message-kbnH1A5w.mjs.map +1 -0
  48. package/dist/push.d.mts +13 -0
  49. package/dist/push.mjs +70 -0
  50. package/dist/push.mjs.map +1 -0
  51. package/dist/qr.d.mts +292 -0
  52. package/dist/qr.mjs +1725 -0
  53. package/dist/qr.mjs.map +1 -0
  54. package/dist/registry-CbtwcxkX.mjs +374 -0
  55. package/dist/registry-CbtwcxkX.mjs.map +1 -0
  56. package/dist/risk-DyABgg4W.mjs +757 -0
  57. package/dist/risk-DyABgg4W.mjs.map +1 -0
  58. package/dist/session-CNJFLarP.mjs +18 -0
  59. package/dist/session-CNJFLarP.mjs.map +1 -0
  60. package/dist/socket-ChG9JRT_.mjs +110 -0
  61. package/dist/socket-ChG9JRT_.mjs.map +1 -0
  62. package/dist/spi-BrTw5s98.d.mts +3 -0
  63. package/dist/timer-Cdk5rGM2.mjs +43 -0
  64. package/dist/timer-Cdk5rGM2.mjs.map +1 -0
  65. package/dist/types-BpvioFGo.d.mts +258 -0
  66. package/dist/types-DbftVZ3I.mjs +90 -0
  67. package/dist/types-DbftVZ3I.mjs.map +1 -0
  68. package/dist/walletconnect.d.mts +86 -0
  69. package/dist/walletconnect.mjs +1507 -0
  70. package/dist/walletconnect.mjs.map +1 -0
  71. package/dist/webln-BgrtPXpG.mjs +2593 -0
  72. package/dist/webln-BgrtPXpG.mjs.map +1 -0
  73. package/dist/webln-Bllk_xJ2.d.mts +666 -0
  74. package/package.json +92 -19
  75. package/dist/connect.mjs.map +0 -1
  76. package/dist/registry-DwguKWvt.d.mts +0 -27
  77. package/dist/registry-oorLoGtz.mjs +0 -120
  78. package/dist/registry-oorLoGtz.mjs.map +0 -1
  79. package/dist/webln-DKqCnqx1.mjs +0 -3677
  80. package/dist/webln-DKqCnqx1.mjs.map +0 -1
@@ -0,0 +1,757 @@
1
+ import { r as errorMessage } from "./errors-horUy5k1.mjs";
2
+ import { n as timeoutSignal } from "./timer-Cdk5rGM2.mjs";
3
+ import { SAFE_MULTISEND_CALL_ONLY, evmTokenTable } from "@qntx/wallet-chains/evm";
4
+ import { SOLANA_NATIVE_ASSET } from "@qntx/wallet-chains/solana";
5
+ import { tronTokenTable } from "@qntx/wallet-chains/tron";
6
+ import { Address, Transaction } from "@scure/btc-signer";
7
+ import "@qntx/wallet-chains/bitcoin";
8
+ import { hex } from "@scure/base";
9
+ import { p2wpkh } from "@scure/btc-signer/payment.js";
10
+ import { selectUTXO } from "@scure/btc-signer/utxo.js";
11
+ import { SiwxError, checkOrigin, createMessage, parseTimestamp } from "@qntx/siwx";
12
+ // src/requests/simulation.ts
13
+ const SIMULATION_TIMEOUT_MS = 1e4;
14
+ /** Asset ids compare by string, case-insensitively for EVM `0x` addresses. */
15
+ const sameAsset = (a, b) => a === b || a.startsWith("0x") && a.toLowerCase() === b.toLowerCase();
16
+ /** An asset amount that moved by more than this share of the old one is a changed simulation. */
17
+ const SIMULATION_CHANGE_PERCENT = 5n;
18
+ const covers = (changes, other) => changes.every((c) => other.some((o) => sameAsset(o.asset, c.asset)));
19
+ const total = (changes, asset) => changes.filter((c) => sameAsset(c.asset, asset)).reduce((sum, c) => sum + BigInt(c.amount), 0n);
20
+ /**
21
+ * Whether a re-simulation differs enough from the first outcome to be shown again: a different
22
+ * status, an asset appearing or disappearing, or an amount that moved by more than
23
+ * {@link SIMULATION_CHANGE_PERCENT} percent of the old one. Two outcomes failing or missing the
24
+ * same way count as unchanged.
25
+ */
26
+ function simulationChanged(before, after) {
27
+ if (before.status !== after.status) return true;
28
+ if (before.status !== "success" || after.status !== "success") return false;
29
+ if (!covers(before.changes, after.changes) || !covers(after.changes, before.changes)) return true;
30
+ return before.changes.some(({ asset }) => {
31
+ const prior = total(before.changes, asset);
32
+ const next = total(after.changes, asset);
33
+ const diff = prior > next ? prior - next : next - prior;
34
+ const base = prior < 0n ? -prior : prior;
35
+ return diff * 100n > base * SIMULATION_CHANGE_PERCENT;
36
+ });
37
+ }
38
+ const noop = () => void 0;
39
+ /**
40
+ * Runs a simulation under the 10 s bound of the injected timer. A throw from `run` and the timeout
41
+ * are `unavailable`; the timer is always cancelled.
42
+ */
43
+ async function boundedSimulation(run, setTimer) {
44
+ const stopTimer = { cancel: noop };
45
+ const timeout = new Promise((resolve) => {
46
+ stopTimer.cancel = setTimer(SIMULATION_TIMEOUT_MS, () => {
47
+ resolve({
48
+ status: "unavailable",
49
+ error: "timeout"
50
+ });
51
+ });
52
+ });
53
+ const bounded = async () => {
54
+ try {
55
+ return await run();
56
+ } catch (error) {
57
+ return {
58
+ status: "unavailable",
59
+ error: errorMessage(error)
60
+ };
61
+ }
62
+ };
63
+ try {
64
+ return await Promise.race([bounded(), timeout]);
65
+ } finally {
66
+ stopTimer.cancel();
67
+ }
68
+ }
69
+ // src/chains/bitcoin.ts
70
+ const DUST = {
71
+ p2wpkh: 294,
72
+ p2tr: 330,
73
+ p2pkh: 546
74
+ };
75
+ const isObject = (v) => typeof v === "object" && v !== null;
76
+ var EsploraError = class extends Error {
77
+ /** True for request timeout/abort, network failure, 429-after-retries and 5xx — safe to retry. */
78
+ transient;
79
+ constructor(message, transient) {
80
+ super(message);
81
+ this.name = "EsploraError";
82
+ this.transient = transient;
83
+ }
84
+ };
85
+ const MAX_IN_FLIGHT = 4;
86
+ const MAX_RETRIES = 3;
87
+ const MAX_BACKOFF_MS = 2e3;
88
+ const REQUEST_TIMEOUT_MS = 1e4;
89
+ /** Bounded-concurrency + 429-aware ordered failover over the endpoint list. */
90
+ const esplora = (endpoints, fetchFn, deps, timeoutMs = REQUEST_TIMEOUT_MS) => {
91
+ const { setTimer, random } = deps;
92
+ const sleep = async (ms) => new Promise((resolve) => {
93
+ setTimer(ms, resolve);
94
+ });
95
+ let inFlight = 0;
96
+ const waiters = [];
97
+ const acquire = async () => {
98
+ if (inFlight >= MAX_IN_FLIGHT) await new Promise((resolve) => {
99
+ waiters.push(resolve);
100
+ });
101
+ inFlight += 1;
102
+ };
103
+ const release = () => {
104
+ inFlight -= 1;
105
+ waiters.shift()?.();
106
+ };
107
+ const backoff = async (headers, retry) => {
108
+ const ra = headers.get("retry-after");
109
+ const retryAfterMs = ra !== null && ra !== "" && !Number.isNaN(Number(ra)) ? Number(ra) * 1e3 : void 0;
110
+ const jitter = (random(1)[0] ?? 0) % 100;
111
+ await sleep(retryAfterMs ?? Math.min(100 * 2 ** retry + jitter, MAX_BACKOFF_MS));
112
+ };
113
+ const request = async (base, path, body) => {
114
+ await acquire();
115
+ const bound = timeoutSignal(timeoutMs, setTimer);
116
+ try {
117
+ let res;
118
+ try {
119
+ res = await fetchFn(`${base.replace(/\/$/, "")}${path}`, {
120
+ ...body === void 0 ? { method: "GET" } : {
121
+ method: "POST",
122
+ headers: { "content-type": "text/plain" },
123
+ body
124
+ },
125
+ signal: bound.signal
126
+ });
127
+ } catch (error) {
128
+ throw new EsploraError(`esplora ${base}${path}: request failed (${error instanceof Error ? error.name : "unknown"})`, true);
129
+ }
130
+ if (res.status === 429) return { throttled: res.headers };
131
+ if (!res.ok) throw new EsploraError(`esplora ${base}${path}: ${res.status}`, res.status >= 500);
132
+ const text = await res.text();
133
+ try {
134
+ return { value: JSON.parse(text) };
135
+ } catch {
136
+ return { value: text };
137
+ }
138
+ } finally {
139
+ bound.cancel();
140
+ release();
141
+ }
142
+ };
143
+ const call = async (base, path, body, retry) => {
144
+ const outcome = await request(base, path, body);
145
+ if ("value" in outcome) return outcome.value;
146
+ if (retry >= MAX_RETRIES) throw new EsploraError(`esplora ${base}${path}: 429 after ${MAX_RETRIES} retries`, true);
147
+ await backoff(outcome.throttled, retry);
148
+ return call(base, path, body, retry + 1);
149
+ };
150
+ const attempt = async (rest, path, body, last) => {
151
+ const [base, ...next] = rest;
152
+ if (base === void 0) throw last instanceof Error ? last : /* @__PURE__ */ new Error("all esplora endpoints failed");
153
+ try {
154
+ return await call(base, path, body, 0);
155
+ } catch (error) {
156
+ return attempt(next, path, body, error);
157
+ }
158
+ };
159
+ return {
160
+ get: async (path) => attempt(endpoints, path, void 0, void 0),
161
+ post: async (path, body) => attempt(endpoints, path, body, void 0)
162
+ };
163
+ };
164
+ const feeTiers = async (es) => {
165
+ const res = await es.get("/fee-estimates");
166
+ const estimates = isObject(res) ? res : {};
167
+ const pick = (target) => Math.max(1, Math.ceil(Number(estimates[target] ?? 1)));
168
+ return [
169
+ {
170
+ tier: "fast",
171
+ satPerByte: pick("1")
172
+ },
173
+ {
174
+ tier: "normal",
175
+ satPerByte: pick("3")
176
+ },
177
+ {
178
+ tier: "slow",
179
+ satPerByte: pick("6")
180
+ },
181
+ {
182
+ tier: "economy",
183
+ satPerByte: pick("144")
184
+ }
185
+ ];
186
+ };
187
+ const dustFor = (scriptType) => DUST[scriptType] ?? 546;
188
+ /**
189
+ * Whether a UTXO may carry an inscription or rune the wallet cannot see without an indexer, so it
190
+ * is protected by default: every taproot output (the `ordinals` account; ord's own wallet is a
191
+ * bip86 descriptor over /0/* and /1/*, docs/src/guides/wallet.md) and any output within ord's
192
+ * postage.
193
+ */
194
+ const mayCarryInscription = (taproot, value) => taproot || value <= 2e4;
195
+ /** Whether `address` decodes to a taproot (P2TR) output on `network`. */
196
+ const isTaprootAddress = (address, network) => Address(network).decode(address).type === "tr";
197
+ /**
198
+ * The spendable subset of `utxos` an automatic selection may pick: every output except the
199
+ * user-frozen ones and those that may carry an inscription (taproot or at most 20 000 sats).
200
+ * Inscription protection is a derived property, separate from freezing — unfreezing never
201
+ * unprotects; a protected output is spendable only by naming it in `PrepareParams.inputs`.
202
+ */
203
+ const selectableUtxos = (utxos, network, frozen) => {
204
+ return utxos.filter((u) => !frozen.has(`${u.txid}:${String(u.vout)}`) && !mayCarryInscription(isTaprootAddress(u.address, network), u.value));
205
+ };
206
+ /** Estimated signed size of one input, vbytes — BIP-141 worst case per template. */
207
+ const INPUT_VBYTES = {
208
+ "btc.bip44": 148,
209
+ "btc.bip49": 91,
210
+ "btc.bip84": 68,
211
+ "btc.bip86": 57.5
212
+ };
213
+ /** Estimated output size, vbytes, by script type — everything else costs at most a p2wsh. */
214
+ const OUTPUT_VBYTES = {
215
+ pkh: 34,
216
+ sh: 32,
217
+ wpkh: 31,
218
+ wsh: 43,
219
+ tr: 43
220
+ };
221
+ /** Version, segwit marker/flag, the two vector lengths and locktime, weighted. */
222
+ const TX_VBYTES_OVERHEAD = 10.5;
223
+ /**
224
+ * The one vsize estimate every build path shares — sends, exact replacements and CPFP children
225
+ * alike — so the fee a transaction reports is the fee its own size demands.
226
+ */
227
+ const estimateVsize = (inputs, outputs, network) => Math.ceil(TX_VBYTES_OVERHEAD + inputs.reduce((a, t) => a + INPUT_VBYTES[t], 0) + outputs.reduce((a, address) => a + (OUTPUT_VBYTES[Address(network).decode(address).type] ?? 43), 0));
228
+ var BitcoinChainAdapter = class {
229
+ /** Inputs for selectUTXO — the same TransactionInputUpdate objects added to the PSBT. */
230
+ toInputs(utxos, fingerprint, pathOf, pubkeyOf, scriptOf, template, rawTxOf) {
231
+ return utxos.filter((u) => u.status !== "locked").map((u) => {
232
+ const pub = pubkeyOf(u);
233
+ const entry = {
234
+ txid: u.txid,
235
+ index: u.vout,
236
+ sequence: 4294967293
237
+ };
238
+ if (template !== "btc.bip44") entry.witnessUtxo = {
239
+ amount: BigInt(u.value),
240
+ script: scriptOf(u)
241
+ };
242
+ if (template === "btc.bip86") {
243
+ entry.tapInternalKey = pub;
244
+ entry.tapBip32Derivation = [[pub, {
245
+ hashes: [],
246
+ der: {
247
+ fingerprint,
248
+ path: pathOf(u)
249
+ }
250
+ }]];
251
+ return entry;
252
+ }
253
+ const raw = rawTxOf === void 0 ? void 0 : rawTxOf(u);
254
+ if (raw === void 0 && template === "btc.bip44") throw new Error(`no raw transaction for bip44 input ${u.txid}`);
255
+ if (raw !== void 0) entry.nonWitnessUtxo = raw;
256
+ entry.bip32Derivation = [[pub, {
257
+ fingerprint,
258
+ path: pathOf(u)
259
+ }]];
260
+ if (template === "btc.bip49") entry.redeemScript = p2wpkh(pub).script;
261
+ return entry;
262
+ });
263
+ }
264
+ buildPsbt(inputs, to, amount, feePerByte, changeAddress, network, strategy = "default") {
265
+ const selection = selectUTXO([...inputs], [{
266
+ address: to,
267
+ amount
268
+ }], strategy, {
269
+ feePerByte,
270
+ changeAddress,
271
+ bip69: true,
272
+ dust: BigInt(dustFor("p2wpkh")),
273
+ network,
274
+ createTx: true
275
+ });
276
+ if (selection === void 0 || selection.tx === void 0) throw new Error("insufficient confirmed utxo for the amount + fee");
277
+ const wanted = new Set((selection.inputs ?? []).flatMap((sel) => {
278
+ const raw = sel.txid;
279
+ if (!(raw instanceof Uint8Array)) return [];
280
+ const forward = hex.encode(raw);
281
+ const reverse = hex.encode(Uint8Array.from(raw).reverse());
282
+ return [`${forward}:${String(sel.index ?? -1)}`, `${reverse}:${String(sel.index ?? -1)}`];
283
+ }));
284
+ const chosen = inputs.filter((i) => wanted.has(`${String(i.txid)}:${String(i.index)}`));
285
+ return {
286
+ psbt: selection.tx.toPSBT(),
287
+ inputs: chosen
288
+ };
289
+ }
290
+ /** Fixed-input/output PSBT — the RBF/CPFP path, which chooses nothing itself. */
291
+ buildExactPsbt(inputs, outputs, network, template) {
292
+ const tx = new Transaction();
293
+ for (const input of inputs) tx.addInput(input);
294
+ for (const out of outputs) tx.addOutputAddress(out.address, out.amount, network);
295
+ const vsize = estimateVsize(inputs.map(() => template), outputs.map((o) => o.address), network);
296
+ return {
297
+ psbt: tx.toPSBT(),
298
+ vsize
299
+ };
300
+ }
301
+ };
302
+ // src/requests/risk.ts
303
+ const byDanger = (findings) => [...findings].sort((a, b) => Number(b.level === "danger") - Number(a.level === "danger"));
304
+ /** The finding for a browser origin's phishing status, if any; `blocked` never reaches a request. */
305
+ function originRisk(status) {
306
+ if (status === "trusted") return [{
307
+ code: "phishing-origin",
308
+ level: "danger"
309
+ }];
310
+ return status === "unchecked" ? [{
311
+ code: "phishing-unchecked",
312
+ level: "warning"
313
+ }] : [];
314
+ }
315
+ /**
316
+ * A WalletConnect peer's Verify verdict: a flagged domain or a domain mismatch is a danger; an
317
+ * unverifiable one is neutral.
318
+ */
319
+ function verifyRisk(verify) {
320
+ const found = [];
321
+ if (verify.isScam) found.push({
322
+ code: "verify-threat",
323
+ level: "danger"
324
+ });
325
+ if (verify.validation === "INVALID") found.push({
326
+ code: "verify-mismatch",
327
+ level: "danger"
328
+ });
329
+ return found;
330
+ }
331
+ /** `findings` plus `extra`, deduplicated by code, `danger` first. */
332
+ function mergeRisk(findings, extra) {
333
+ const byCode = /* @__PURE__ */ new Map();
334
+ for (const finding of [...findings, ...extra]) byCode.set(finding.code, finding);
335
+ return byDanger([...byCode.values()]);
336
+ }
337
+ /**
338
+ * The finding a decoder's {@link IntentWarning} maps to — one entry for every `IntentWarningKind`,
339
+ * `undefined` where the prompt rows already carry the fact and no request-level risk exists:
340
+ *
341
+ * - `platform-fee` — the fee is a prompt row.
342
+ * - `stake-lockup` — the lockup window is a prompt row.
343
+ * - `sighash-single-anyonecanpay` — already `bitcoin-sighash-single` via assessBitcoinPsbts.
344
+ * - `permit2-witness` — the bound message is a prompt row.
345
+ * - `delegation-replaced` — the replaced delegation is a prompt row.
346
+ * - `token-2022-transfer-fee` — the withheld fee is a prompt row.
347
+ * - `token-2022-extension` — the extension note is a prompt row.
348
+ * - `fiat24-issuer-rate` — the issuer's applied rate is a prompt row.
349
+ * - `fiat24-swap-quote` — the quoted rate is a prompt row.
350
+ * - `fiat24-account-link` — the account link is a prompt row.
351
+ */
352
+ const WARNING_RISK = {
353
+ "platform-fee": void 0,
354
+ "stake-lockup": void 0,
355
+ "sighash-single-anyonecanpay": void 0,
356
+ "permit2-witness": void 0,
357
+ "delegation-replaced": void 0,
358
+ "token-2022-transfer-fee": void 0,
359
+ "token-2022-extension": void 0,
360
+ "fiat24-internal-account": {
361
+ code: "fiat24-internal-account",
362
+ level: "warning"
363
+ },
364
+ "fiat24-card-pull": {
365
+ code: "fiat24-card-pull",
366
+ level: "warning"
367
+ },
368
+ "fiat24-unlimited-approval": {
369
+ code: "fiat24-unlimited-approval",
370
+ level: "danger"
371
+ },
372
+ "fiat24-issuer-rate": void 0,
373
+ "fiat24-exact-out-unbounded": {
374
+ code: "fiat24-exact-out-unbounded",
375
+ level: "warning"
376
+ },
377
+ "fiat24-payee-offchain": {
378
+ code: "fiat24-payee-offchain",
379
+ level: "warning"
380
+ },
381
+ "fiat24-swap-quote": void 0,
382
+ "fiat24-account-link": void 0,
383
+ "fiat24-account-move": {
384
+ code: "fiat24-account-move",
385
+ level: "danger"
386
+ },
387
+ "fiat24-account-burn": {
388
+ code: "fiat24-account-burn",
389
+ level: "warning"
390
+ },
391
+ "unusual-own-output": {
392
+ code: "bitcoin-unusual-output",
393
+ level: "warning"
394
+ },
395
+ "unconfirmed-signer-output": {
396
+ code: "bitcoin-unconfirmed-output",
397
+ level: "danger"
398
+ }
399
+ };
400
+ /**
401
+ * Findings for every warning the decoded intents carry, through {@link WARNING_RISK}, deduplicated,
402
+ * `danger` first. A warning stamped `level: "danger"` is a `danger` finding whatever the table says
403
+ * — the decoder knows the concrete shape better than the kind default.
404
+ */
405
+ function assessWarnings(intents) {
406
+ const found = /* @__PURE__ */ new Map();
407
+ for (const intent of intents) for (const warning of intent.warnings) {
408
+ const entry = WARNING_RISK[warning.kind];
409
+ if (entry === void 0) continue;
410
+ const level = warning.level ?? entry.level;
411
+ if (found.get(entry.code)?.level !== "danger") found.set(entry.code, {
412
+ code: entry.code,
413
+ level
414
+ });
415
+ }
416
+ return byDanger([...found.values()]);
417
+ }
418
+ /**
419
+ * Findings for the approvals a transaction grants: an operator approved for a whole collection is a
420
+ * `danger`; a granted unlimited allowance is a `warning`. Revocations and reductions raise
421
+ * nothing.
422
+ */
423
+ function assessApprovals(intent) {
424
+ const found = /* @__PURE__ */ new Map();
425
+ for (const change of intent.approvals) if (change.kind === "operator") {
426
+ if (change.approved) found.set("collection-approval", {
427
+ code: "collection-approval",
428
+ level: "danger"
429
+ });
430
+ } else if (change.kind === "stake-authority") found.set("stake-authority", {
431
+ code: "stake-authority",
432
+ level: "danger"
433
+ });
434
+ else if (change.kind === "allowance" && change.change !== "decrease" && change.unlimited) found.set("unlimited-approval", {
435
+ code: "unlimited-approval",
436
+ level: "warning"
437
+ });
438
+ return byDanger([...found.values()]);
439
+ }
440
+ const PERMIT_MAX_LIFETIME_MS = 2592e6;
441
+ /**
442
+ * Findings for what a signed permit grants: any non-revoking allowance is a `warning`, an unlimited
443
+ * one a `danger`, and a Permit2 allowance that lasts more than 30 days from `now` a `danger`.
444
+ */
445
+ function assessPermits(intent, now) {
446
+ const found = /* @__PURE__ */ new Map();
447
+ for (const change of intent.approvals) {
448
+ if (change.kind !== "allowance" || change.amount.amount === "0") continue;
449
+ found.set("permit-approval", {
450
+ code: "permit-approval",
451
+ level: "warning"
452
+ });
453
+ if (change.unlimited) found.set("permit-unlimited", {
454
+ code: "permit-unlimited",
455
+ level: "danger"
456
+ });
457
+ if (change.via === "permit2" && change.change === "set" && change.expiration !== void 0 && change.expiration * 1e3 > now + PERMIT_MAX_LIFETIME_MS) found.set("permit-long-lived", {
458
+ code: "permit-long-lived",
459
+ level: "danger"
460
+ });
461
+ }
462
+ return byDanger([...found.values()]);
463
+ }
464
+ /**
465
+ * Findings for a recognized Seaport order: an order whose `offer` gives up items without any
466
+ * consideration paying the offerer is the zero-price-listing phishing shape (`danger`), and an
467
+ * `offerer` other than the signing account is a `warning`.
468
+ */
469
+ function assessSeaport(order, signer) {
470
+ if (order === void 0) return [];
471
+ const found = /* @__PURE__ */ new Map();
472
+ const paid = order.consideration.some((item) => item.recipient.toLowerCase() === order.offerer.toLowerCase() && (BigInt(item.startAmount.amount) > 0n || BigInt(item.endAmount.amount) > 0n));
473
+ if (order.offer.length > 0 && !paid) found.set("order-receives-nothing", {
474
+ code: "order-receives-nothing",
475
+ level: "danger"
476
+ });
477
+ if (order.offerer.toLowerCase() !== signer.toLowerCase()) found.set("order-offerer-mismatch", {
478
+ code: "order-offerer-mismatch",
479
+ level: "warning"
480
+ });
481
+ return byDanger([...found.values()]);
482
+ }
483
+ /**
484
+ * Findings for a recognized Safe transaction: a `delegatecall` into a contract that is not a
485
+ * canonical MultiSendCallOnly is the multisig-hijack phishing shape (`danger`), a non-zero gas
486
+ * refund is a `warning`, and every decoded inner call's approvals are assessed too.
487
+ */
488
+ function assessSafe(safe) {
489
+ if (safe === void 0) return [];
490
+ const found = /* @__PURE__ */ new Map();
491
+ for (const finding of safe.calls.flatMap((call) => assessApprovals(call))) found.set(finding.code, finding);
492
+ if (safe.operation === "delegatecall" && !SAFE_MULTISEND_CALL_ONLY.has(safe.to.toLowerCase())) found.set("safe-delegatecall", {
493
+ code: "safe-delegatecall",
494
+ level: "danger"
495
+ });
496
+ if (safe.refund !== void 0) found.set("safe-gas-refund", {
497
+ code: "safe-gas-refund",
498
+ level: "warning"
499
+ });
500
+ return byDanger([...found.values()]);
501
+ }
502
+ /**
503
+ * Findings for the inputs a dApp PSBT asks the wallet to sign. A `SINGLE|ANYONECANPAY` input binds
504
+ * only its same-index output, so anyone can change the rest of the transaction: `danger`. Until
505
+ * inscription data exists the heuristic is ord's postage rule — every taproot (ordinals-account)
506
+ * input and every input worth at most ord's MAX_POSTAGE of 20_000 sat may carry an inscription:
507
+ * such an input is a `warning` when it is signed as a listing (the sighash that fits selling it)
508
+ * and a `danger` otherwise.
509
+ */
510
+ function assessBitcoinPsbts(inputs) {
511
+ const found = /* @__PURE__ */ new Map();
512
+ if (inputs.some((i) => i.sigHash === "SINGLE|ANYONECANPAY")) found.set("bitcoin-sighash-single", {
513
+ code: "bitcoin-sighash-single",
514
+ level: "danger"
515
+ });
516
+ if (inputs.some((i) => i.frozen)) found.set("bitcoin-frozen-input", {
517
+ code: "bitcoin-frozen-input",
518
+ level: "danger"
519
+ });
520
+ const postage = inputs.filter((i) => mayCarryInscription(i.template === "btc.bip86", i.value));
521
+ if (postage.length > 0) found.set("bitcoin-inscription-input", {
522
+ code: "bitcoin-inscription-input",
523
+ level: postage.some((i) => i.sigHash !== "SINGLE|ANYONECANPAY") ? "danger" : "warning"
524
+ });
525
+ return byDanger([...found.values()]);
526
+ }
527
+ const LOCAL_HOSTS = /* @__PURE__ */ new Set([
528
+ "localhost",
529
+ "127.0.0.1",
530
+ "[::1]"
531
+ ]);
532
+ /** `scheme`, `host` (IPv6 keeps its brackets) and `hostPort` of a `scheme://host[:port]` origin. */
533
+ const originParts = (origin) => {
534
+ const sep = origin.indexOf("://");
535
+ const rest = origin.slice(sep + 3);
536
+ const end = rest.startsWith("[") ? rest.indexOf("]") + 1 : rest.lastIndexOf(":");
537
+ return {
538
+ scheme: sep === -1 ? "" : origin.slice(0, sep).toLowerCase(),
539
+ host: (end > 0 ? rest.slice(0, end) : rest).toLowerCase(),
540
+ hostPort: rest.toLowerCase()
541
+ };
542
+ };
543
+ const isLocalHost = (host) => LOCAL_HOSTS.has(host) || host.endsWith(".localhost");
544
+ /**
545
+ * What a Sign-In with X message adds to a request from `origin`: a message for another domain is
546
+ * refused (`reject`) in production and a `danger` on a local development page; the signing address
547
+ * must be the signer; an expired or not-yet-valid window and a text that only resembles a sign-in
548
+ * message are warnings. TRON has no sign-in standard — a `tron` parse is only ever `malformed`, the
549
+ * claims-only path.
550
+ */
551
+ function assessSignIn(input) {
552
+ const { signIn, origin, signer, family, now } = input;
553
+ const { scheme, host, hostPort } = originParts(origin);
554
+ const developer = isLocalHost(host);
555
+ if (signIn.status === "malformed") {
556
+ for (const claim of signIn.claims) if (!(claim.domain.toLowerCase() === hostPort && (claim.scheme === void 0 || claim.scheme.toLowerCase() === scheme))) return developer ? { risk: [{
557
+ code: "sign-in-domain-mismatch",
558
+ level: "danger"
559
+ }] } : {
560
+ reject: `the sign-in message is for ${claim.domain}, not this page`,
561
+ risk: []
562
+ };
563
+ return { risk: [{
564
+ code: "sign-in-malformed",
565
+ level: "warning"
566
+ }] };
567
+ }
568
+ const { fields } = signIn;
569
+ let findings;
570
+ try {
571
+ findings = checkOrigin(createMessage(fields), origin, developer ? {
572
+ allowedSchemes: ["https", "http"],
573
+ defaultScheme: scheme,
574
+ developerMode: true
575
+ } : {});
576
+ } catch (error) {
577
+ if (error instanceof SiwxError && error.code === "InvalidOrigin") return {
578
+ reject: "the page origin is not a valid web origin",
579
+ risk: []
580
+ };
581
+ throw error;
582
+ }
583
+ if (findings.some((f) => f.severity === "reject")) return {
584
+ reject: `the sign-in message is for ${fields.domain}, not this page`,
585
+ risk: []
586
+ };
587
+ const found = /* @__PURE__ */ new Map();
588
+ const add = (code, level) => {
589
+ found.set(code, {
590
+ code,
591
+ level
592
+ });
593
+ };
594
+ for (const finding of findings) if (finding.code === "PortMismatch") add("sign-in-port-mismatch", "warning");
595
+ else add("sign-in-domain-mismatch", "danger");
596
+ if (!(family === "evm" ? fields.address.toLowerCase() === signer.toLowerCase() : fields.address === signer)) add("sign-in-address-mismatch", "danger");
597
+ const expires = fields.expirationTime === void 0 ? void 0 : parseTimestamp(fields.expirationTime);
598
+ if (expires !== void 0 && expires.epochMs < now) add("sign-in-expired", "warning");
599
+ const notBefore = fields.notBefore === void 0 ? void 0 : parseTimestamp(fields.notBefore);
600
+ if (notBefore !== void 0 && notBefore.epochMs > now) add("sign-in-not-yet-valid", "warning");
601
+ return { risk: byDanger([...found.values()]) };
602
+ }
603
+ /** EVM addresses compare without the `0x` prefix and case-insensitively. */
604
+ const comparable = (family, address) => family === "evm" ? address.replace(/^0x/i, "").toLowerCase() : address;
605
+ /**
606
+ * Who a flow pays. A Fiat24 ledger transfer or payout names its recipient in the calldata — `to` is
607
+ * the cash-token contract all of them share — so the account or payee is the recipient compared.
608
+ */
609
+ /**
610
+ * Addresses the wallet already knows for a family: contacts, plus recipients of tracked chain sends
611
+ * (Spark payments are not tracked — for spark the contacts list is the whole answer).
612
+ */
613
+ const knownAddresses = (entries, txs, family) => {
614
+ const contacts = entries.filter((e) => e.family === family).map((e) => e.address);
615
+ if (family === "spark") return contacts;
616
+ const paid = txs.filter((tx) => tx.family === family && (tx.state === "submitted" || tx.state === "pending" || tx.state === "confirmed")).flatMap((tx) => tx.intent?.outflows.map(recipientOf) ?? []);
617
+ return [...contacts, ...paid];
618
+ };
619
+ const recipientOf = (flow) => flow.fiat24 === void 0 ? flow.to : "account" in flow.fiat24 ? `fiat24:account:${flow.fiat24.account}` : `fiat24:payee:${flow.fiat24.payee}`;
620
+ const looksLike = (a, b) => a !== b && !a.startsWith("fiat24:") && !b.startsWith("fiat24:") && a.length >= 8 && b.length >= 8 && a.slice(0, 4) === b.slice(0, 4) && a.slice(-4) === b.slice(-4);
621
+ /**
622
+ * Findings for every recipient of one request, deduplicated, `danger` first. Recipients come from
623
+ * {@link recipientOf}: a Fiat24 flow's recipient is the account or payee it names.
624
+ */
625
+ function assessRecipients(family, recipients, known) {
626
+ const knownSet = new Set(known.map((a) => comparable(family, a)));
627
+ const found = /* @__PURE__ */ new Map();
628
+ for (const recipient of recipients) {
629
+ const candidate = comparable(family, recipient);
630
+ if (knownSet.has(candidate)) continue;
631
+ found.set("first-recipient", {
632
+ code: "first-recipient",
633
+ level: "warning"
634
+ });
635
+ if ([...knownSet].some((k) => looksLike(candidate, k))) found.set("address-poisoning", {
636
+ code: "address-poisoning",
637
+ level: "danger"
638
+ });
639
+ }
640
+ return byDanger([...found.values()]);
641
+ }
642
+ /**
643
+ * Every party a decoded intent names as receiving value or authority over the signer's value: the
644
+ * outflow recipients (a burned output's script is nobody — a destroyed amount has no recipient),
645
+ * the recipients swap and bridge terms enforce, approval and permission grantees (a revocation
646
+ * names nobody), the inner calls a batch names, and the destinations a recognized typed-data
647
+ * document signs.
648
+ */
649
+ const intentRecipients = (intent) => {
650
+ const recipients = [];
651
+ const push = (inner) => {
652
+ recipients.push(...inner.outflows.filter((flow) => flow.burn !== true).map(recipientOf), ...inner.minimumReceived?.map((minimum) => minimum.to) ?? []);
653
+ for (const approval of inner.approvals ?? []) if (approval.kind === "allowance") {
654
+ if (approval.change !== "decrease" && !(approval.change === "set" && approval.amount.amount === "0")) recipients.push(approval.spender);
655
+ } else if (approval.kind === "operator") {
656
+ if (approval.approved) recipients.push(approval.spender);
657
+ } else if (approval.kind === "stake-authority") recipients.push(approval.authority);
658
+ if (inner.bridge !== void 0) recipients.push(inner.bridge.refundTo);
659
+ if (inner.hyperliquidDeposit !== void 0) recipients.push(inner.hyperliquidDeposit.recipient);
660
+ for (const action of inner.staking ?? []) if (action.kind === "withdraw") recipients.push(action.to);
661
+ else if (action.kind === "lido-request") recipients.push(action.owner);
662
+ else if (action.kind === "tron-delegate") recipients.push(action.receiver);
663
+ const { permissionUpdate } = inner.tron ?? {};
664
+ if (permissionUpdate !== void 0) for (const permission of [
665
+ permissionUpdate.owner,
666
+ ...permissionUpdate.witness === void 0 ? [] : [permissionUpdate.witness],
667
+ ...permissionUpdate.actives
668
+ ]) recipients.push(...permission.keys.map((key) => key.address));
669
+ const { message } = inner;
670
+ if (message?.kind === "typed-data") recipients.push(...messageRecipients(message));
671
+ for (const call of inner.calls ?? []) push(call);
672
+ };
673
+ push(intent);
674
+ return recipients;
675
+ };
676
+ /** The destinations a recognized typed-data document pays, wherever its own shape names them. */
677
+ const messageRecipients = (message) => {
678
+ const recipients = [...message.order?.receive.map((entry) => entry.recipient) ?? [], ...message.seaport?.consideration.map((item) => item.recipient) ?? []];
679
+ const { safe } = message;
680
+ if (safe !== void 0) {
681
+ if (safe.value !== "0") recipients.push(safe.to);
682
+ for (const call of safe.calls) recipients.push(...intentRecipients(call));
683
+ if (safe.refund?.receiver !== void 0) recipients.push(safe.refund.receiver);
684
+ }
685
+ const action = message.hyperliquid;
686
+ if (action !== void 0 && "destination" in action) recipients.push(action.destination);
687
+ const { polymarket } = message;
688
+ if (polymarket?.kind === "batch") for (const call of polymarket.calls) recipients.push(...intentRecipients(call));
689
+ const { authorization } = message;
690
+ if (authorization !== void 0 && authorization.kind !== "cancel") recipients.push(authorization.to);
691
+ const { authority } = message;
692
+ if (authority?.kind === "morpho") {
693
+ if (authority.grant) recipients.push(authority.authorized);
694
+ } else if (authority?.kind === "aave-credit" && authority.amount.amount !== "0") recipients.push(authority.delegatee);
695
+ return recipients;
696
+ };
697
+ /**
698
+ * Recipient findings for one decoded intent: {@link assessRecipients} over {@link intentRecipients},
699
+ * except the signer itself — swaps, wraps and refunds routinely pay the account back.
700
+ */
701
+ function assessIntentRecipients(intent, self, known) {
702
+ const own = self === void 0 ? void 0 : comparable(intent.family, self);
703
+ return assessRecipients(intent.family, intentRecipients(intent).filter((recipient) => own === void 0 || comparable(intent.family, recipient) !== own), known);
704
+ }
705
+ const declaredOutflow = (intent, asset) => intent.outflows.filter((flow) => sameAsset(flow.amount.asset, asset)).reduce((sum, flow) => sum + BigInt(flow.amount.amount), 0n);
706
+ /**
707
+ * What a simulation adds to a request. `unavailable` blocks silent approval; `reverted` is a
708
+ * danger; an outflow above what the decode declares for that asset is a danger too — but only
709
+ * against a decode that is not `opaque`, and never for Solana lamports (fees and rent always exceed
710
+ * the declared amount).
711
+ */
712
+ function assessSimulation(intent, outcome) {
713
+ if (outcome === void 0) return {
714
+ checks: [],
715
+ risk: []
716
+ };
717
+ if (outcome.status === "unavailable") return {
718
+ checks: ["simulation-unavailable"],
719
+ risk: []
720
+ };
721
+ if (outcome.status === "reverted") return {
722
+ checks: [],
723
+ risk: [{
724
+ code: "simulation-reverted",
725
+ level: "danger"
726
+ }]
727
+ };
728
+ return {
729
+ checks: [],
730
+ risk: intent.verifiability !== "opaque" && outcome.changes.some((change) => {
731
+ const amount = BigInt(change.amount);
732
+ return amount < 0n && change.asset !== SOLANA_NATIVE_ASSET && -amount > declaredOutflow(intent, change.asset);
733
+ }) ? [{
734
+ code: "simulation-mismatch",
735
+ level: "danger"
736
+ }] : []
737
+ };
738
+ }
739
+ /**
740
+ * A token on `chainId` that reports the symbol of a different, built-in token of the same chain —
741
+ * the shape of a lookalike token. Symbols compare case-insensitively.
742
+ */
743
+ function impersonatesBuiltIn(chainId, address, symbol) {
744
+ const wanted = symbol.toLowerCase();
745
+ return Object.entries(evmTokenTable[String(chainId)] ?? {}).some(([known, token]) => known.toLowerCase() !== address.toLowerCase() && token.symbol.toLowerCase() === wanted);
746
+ }
747
+ /**
748
+ * The TRC-20 counterpart of {@link impersonatesBuiltIn}: a contract reporting the symbol of a
749
+ * different token in the TRON table. Addresses are base58 — case-sensitive, no checksum folding.
750
+ */
751
+ function impersonatesTronToken(network, address, symbol) {
752
+ const wanted = symbol.toLowerCase();
753
+ return Object.entries(tronTokenTable[network] ?? {}).some(([known, token]) => known !== address && token.symbol.toLowerCase() === wanted);
754
+ }
755
+ export { isTaprootAddress as C, simulationChanged as D, boundedSimulation as E, feeTiers as S, selectableUtxos as T, verifyRisk as _, assessRecipients as a, esplora as b, assessSignIn as c, comparable as d, impersonatesBuiltIn as f, originRisk as g, mergeRisk as h, assessPermits as i, assessSimulation as l, knownAddresses as m, assessBitcoinPsbts as n, assessSafe as o, impersonatesTronToken as p, assessIntentRecipients as r, assessSeaport as s, assessApprovals as t, assessWarnings as u, BitcoinChainAdapter as v, mayCarryInscription as w, estimateVsize as x, EsploraError as y };
756
+
757
+ //# sourceMappingURL=risk-DyABgg4W.mjs.map