@qntx/wallet-engine 0.12.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.
- package/README.md +1057 -20
- package/dist/apps-fiat24.d.mts +202 -0
- package/dist/apps-fiat24.mjs +1378 -0
- package/dist/apps-fiat24.mjs.map +1 -0
- package/dist/apps-hyperliquid.d.mts +549 -0
- package/dist/apps-hyperliquid.mjs +2742 -0
- package/dist/apps-hyperliquid.mjs.map +1 -0
- package/dist/apps-polymarket.d.mts +729 -0
- package/dist/apps-polymarket.mjs +3786 -0
- package/dist/apps-polymarket.mjs.map +1 -0
- package/dist/apps.d.mts +136 -0
- package/dist/apps.mjs +535 -0
- package/dist/apps.mjs.map +1 -0
- package/dist/connect-BY1C5ZRI.mjs +210 -0
- package/dist/connect-BY1C5ZRI.mjs.map +1 -0
- package/dist/connect.d.mts +17 -9
- package/dist/connect.mjs +3 -185
- package/dist/controller-DpNVHVsj.d.mts +2295 -0
- package/dist/controller-rMnaxKAH.mjs +46 -0
- package/dist/controller-rMnaxKAH.mjs.map +1 -0
- package/dist/decimal-COJ4g8qy.mjs +38 -0
- package/dist/decimal-COJ4g8qy.mjs.map +1 -0
- package/dist/eligibility-BfM9ybYZ.mjs +48 -0
- package/dist/eligibility-BfM9ybYZ.mjs.map +1 -0
- package/dist/engine-Dic_kkEr.d.mts +1829 -0
- package/dist/errors-B8W-hoYW.d.mts +7 -0
- package/dist/errors-horUy5k1.mjs +24 -0
- package/dist/errors-horUy5k1.mjs.map +1 -0
- package/dist/gateway-contract.d.mts +3 -362
- package/dist/gateway-contract.mjs +1531 -81
- package/dist/gateway-contract.mjs.map +1 -1
- package/dist/idb.d.mts +5 -0
- package/dist/idb.mjs +122 -46
- package/dist/idb.mjs.map +1 -1
- package/dist/index-vBgfOFIh.d.mts +2227 -0
- package/dist/index.d.mts +58 -515
- package/dist/index.mjs +22314 -4901
- package/dist/index.mjs.map +1 -1
- package/dist/json-BDwV38cj.mjs +15 -0
- package/dist/json-BDwV38cj.mjs.map +1 -0
- package/dist/link-Ceq8Dggp.mjs +139 -0
- package/dist/link-Ceq8Dggp.mjs.map +1 -0
- package/dist/primitives-DbSHLZKq.mjs +31 -0
- package/dist/primitives-DbSHLZKq.mjs.map +1 -0
- package/dist/push-message-AQuzoNFY.d.mts +84 -0
- package/dist/push-message-kbnH1A5w.mjs +142 -0
- package/dist/push-message-kbnH1A5w.mjs.map +1 -0
- package/dist/push.d.mts +13 -0
- package/dist/push.mjs +70 -0
- package/dist/push.mjs.map +1 -0
- package/dist/qr.d.mts +292 -0
- package/dist/qr.mjs +1725 -0
- package/dist/qr.mjs.map +1 -0
- package/dist/registry-CbtwcxkX.mjs +374 -0
- package/dist/registry-CbtwcxkX.mjs.map +1 -0
- package/dist/risk-DyABgg4W.mjs +757 -0
- package/dist/risk-DyABgg4W.mjs.map +1 -0
- package/dist/session-CNJFLarP.mjs +18 -0
- package/dist/session-CNJFLarP.mjs.map +1 -0
- package/dist/socket-ChG9JRT_.mjs +110 -0
- package/dist/socket-ChG9JRT_.mjs.map +1 -0
- package/dist/spi-BrTw5s98.d.mts +3 -0
- package/dist/timer-Cdk5rGM2.mjs +43 -0
- package/dist/timer-Cdk5rGM2.mjs.map +1 -0
- package/dist/types-BpvioFGo.d.mts +258 -0
- package/dist/types-DbftVZ3I.mjs +90 -0
- package/dist/types-DbftVZ3I.mjs.map +1 -0
- package/dist/walletconnect.d.mts +86 -0
- package/dist/walletconnect.mjs +1507 -0
- package/dist/walletconnect.mjs.map +1 -0
- package/dist/webln-BgrtPXpG.mjs +2593 -0
- package/dist/webln-BgrtPXpG.mjs.map +1 -0
- package/dist/webln-Bllk_xJ2.d.mts +666 -0
- package/package.json +94 -19
- package/dist/connect.mjs.map +0 -1
- package/dist/errors-DpkJneDe.d.mts +0 -1696
- package/dist/registry-Deo5WQe1.d.mts +0 -25
- package/dist/registry-wYrcuFNc.mjs +0 -99
- package/dist/registry-wYrcuFNc.mjs.map +0 -1
- package/dist/webln-DzsI7jVb.mjs +0 -3629
- package/dist/webln-DzsI7jVb.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"risk-DyABgg4W.mjs","names":[],"sources":["../src/requests/simulation.ts","../src/chains/bitcoin.ts","../src/requests/risk.ts"],"sourcesContent":["import { errorMessage } from \"../errors.ts\";\n\n/** Simulation result shapes, in a leaf module so routes and the request controller share them. */\nexport type AssetChange = {\n /** Same ids as `DisplayIntent`: EVM `native` or a token address; Solana `lamports` or a mint. */\n readonly asset: string;\n /** Signed decimal in the smallest unit; negative is an outflow. */\n readonly amount: string;\n readonly decimals?: number;\n readonly symbol?: string;\n /** True only when `decimals` and `symbol` come from the built-in token table. */\n readonly verified: boolean;\n};\n\nexport type SimulationOutcome =\n | { readonly status: \"success\"; readonly changes: ReadonlyArray<AssetChange> }\n | { readonly status: \"reverted\"; readonly error: string }\n | { readonly status: \"unavailable\"; readonly error: string };\n\nexport const SIMULATION_TIMEOUT_MS = 10_000;\n\n/** Asset ids compare by string, case-insensitively for EVM `0x` addresses. */\nexport const sameAsset = (a: string, b: string): boolean =>\n a === b || (a.startsWith(\"0x\") && a.toLowerCase() === b.toLowerCase());\n\n/** An asset amount that moved by more than this share of the old one is a changed simulation. */\nexport const SIMULATION_CHANGE_PERCENT = 5n;\n\nconst covers = (changes: ReadonlyArray<AssetChange>, other: ReadonlyArray<AssetChange>): boolean =>\n changes.every((c) => other.some((o) => sameAsset(o.asset, c.asset)));\n\nconst total = (changes: ReadonlyArray<AssetChange>, asset: string): bigint =>\n changes.filter((c) => sameAsset(c.asset, asset)).reduce((sum, c) => sum + BigInt(c.amount), 0n);\n\n/**\n * Whether a re-simulation differs enough from the first outcome to be shown again: a different\n * status, an asset appearing or disappearing, or an amount that moved by more than\n * {@link SIMULATION_CHANGE_PERCENT} percent of the old one. Two outcomes failing or missing the\n * same way count as unchanged.\n */\nexport function simulationChanged(before: SimulationOutcome, after: SimulationOutcome): boolean {\n if (before.status !== after.status) {\n return true;\n }\n if (before.status !== \"success\" || after.status !== \"success\") {\n return false;\n }\n if (!covers(before.changes, after.changes) || !covers(after.changes, before.changes)) {\n return true;\n }\n return before.changes.some(({ asset }) => {\n const prior = total(before.changes, asset);\n const next = total(after.changes, asset);\n const diff = prior > next ? prior - next : next - prior;\n const base = prior < 0n ? -prior : prior;\n return diff * 100n > base * SIMULATION_CHANGE_PERCENT;\n });\n}\n\nconst noop = (): void => undefined;\n\n/**\n * Runs a simulation under the 10 s bound of the injected timer. A throw from `run` and the timeout\n * are `unavailable`; the timer is always cancelled.\n */\nexport async function boundedSimulation(\n run: () => Promise<SimulationOutcome>,\n setTimer: (ms: number, fn: () => unknown) => () => void,\n): Promise<SimulationOutcome> {\n const stopTimer: { cancel: () => void } = { cancel: noop };\n const timeout = new Promise<SimulationOutcome>((resolve) => {\n stopTimer.cancel = setTimer(SIMULATION_TIMEOUT_MS, () => {\n resolve({ status: \"unavailable\", error: \"timeout\" });\n });\n });\n const bounded = async (): Promise<SimulationOutcome> => {\n try {\n return await run();\n } catch (error) {\n return { status: \"unavailable\", error: errorMessage(error) };\n }\n };\n try {\n return await Promise.race([bounded(), timeout]);\n } finally {\n stopTimer.cancel();\n }\n}\n","import { hex } from \"@scure/base\";\nimport { Address, Transaction } from \"@scure/btc-signer\";\nimport type { NETWORK as BTC_MAINNET } from \"@scure/btc-signer\";\nimport { p2wpkh } from \"@scure/btc-signer/payment.js\";\n/**\n * Bitcoin chain adapter — Esplora client, gap-20 address scanning, PSBT construction with\n *\n * @scure/btc-signer selectUTXO (bip69), fee tiers from /fee-estimates (targets 1/3/6/144),\n * dust floors per output type, ord-postage UTXO protection, and POST /tx broadcasting. Custom\n * endpoints are validated by the genesis block hash via /block-height/0. RBF/CPFP are out\n * of scope for this layer.\n */\nimport type { TransactionInputUpdate } from \"@scure/btc-signer/psbt.js\";\nimport { selectUTXO } from \"@scure/btc-signer/utxo.js\";\n\nimport type { BitcoinAccountTemplate } from \"@qntx/wallet-chains/bitcoin\";\n\nimport { timeoutSignal } from \"../timer.ts\";\nimport type { SetTimer } from \"../timer.ts\";\n\nexport { BITCOIN_GAP_LIMIT as GAP_LIMIT } from \"@qntx/wallet-chains/bitcoin\";\nconst DUST: Record<string, number> = { p2wpkh: 294, p2tr: 330, p2pkh: 546 };\n\nexport type BtcNetworkId = `bip122:${string}`;\n\nexport type BtcUtxo = {\n readonly txid: string;\n readonly vout: number;\n readonly value: number;\n readonly address: string;\n readonly status: \"unconfirmed\" | \"confirmed\" | \"locked\";\n readonly height: number;\n};\n\nexport type BtcAddress = {\n readonly chain: 0 | 1;\n readonly index: number;\n readonly address: string;\n readonly used: boolean;\n};\n\nexport type Esplora = {\n readonly get: (path: string) => Promise<unknown>;\n readonly post: (path: string, body: string) => Promise<unknown>;\n};\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null;\n\nexport type EsploraResponse = {\n readonly ok: boolean;\n readonly status: number;\n readonly headers: { get: (name: string) => string | undefined };\n readonly json: () => Promise<unknown>;\n readonly text: () => Promise<string>;\n};\nexport type EsploraFetch = (\n url: string,\n init?: {\n method: string;\n headers?: Record<string, string>;\n body?: string;\n signal?: AbortSignal;\n },\n) => Promise<EsploraResponse>;\n\nexport class EsploraError extends Error {\n /** True for request timeout/abort, network failure, 429-after-retries and 5xx — safe to retry. */\n readonly transient: boolean;\n constructor(message: string, transient: boolean) {\n super(message);\n this.name = \"EsploraError\";\n this.transient = transient;\n }\n}\n\n/** What the Esplora client needs from its host: timers and randomness are injected. */\nexport type EsploraDeps = {\n readonly setTimer: SetTimer;\n readonly random: (length: number) => Uint8Array;\n};\n\nconst MAX_IN_FLIGHT = 4;\nconst MAX_RETRIES = 3;\nconst MAX_BACKOFF_MS = 2000;\nconst REQUEST_TIMEOUT_MS = 10_000;\n\n/** Bounded-concurrency + 429-aware ordered failover over the endpoint list. */\nexport const esplora = (\n endpoints: ReadonlyArray<string>,\n fetchFn: EsploraFetch,\n deps: EsploraDeps,\n timeoutMs: number = REQUEST_TIMEOUT_MS,\n): Esplora => {\n const { setTimer, random } = deps;\n const sleep = async (ms: number): Promise<void> =>\n new Promise<void>((resolve) => {\n setTimer(ms, resolve);\n });\n let inFlight = 0;\n const waiters: Array<() => void> = [];\n const acquire = async (): Promise<void> => {\n if (inFlight >= MAX_IN_FLIGHT) {\n await new Promise<void>((resolve) => {\n waiters.push(resolve);\n });\n }\n inFlight += 1;\n };\n const release = (): void => {\n inFlight -= 1;\n const next = waiters.shift();\n next?.();\n };\n const backoff = async (headers: EsploraResponse[\"headers\"], retry: number): Promise<void> => {\n const ra = headers.get(\"retry-after\");\n const retryAfterMs =\n ra !== null && ra !== \"\" && !Number.isNaN(Number(ra)) ? Number(ra) * 1000 : undefined;\n const jitter = (random(1)[0] ?? 0) % 100;\n await sleep(retryAfterMs ?? Math.min(100 * 2 ** retry + jitter, MAX_BACKOFF_MS));\n };\n // One request inside a concurrency slot. A 429 releases the slot before anyone backs off:\n // retrying while holding it deadlocks once every slot is throttled at the same time.\n const request = async (\n base: string,\n path: string,\n body: string | undefined,\n ): Promise<{ readonly value: unknown } | { readonly throttled: EsploraResponse[\"headers\"] }> => {\n await acquire();\n const bound = timeoutSignal(timeoutMs, setTimer);\n try {\n let res: EsploraResponse;\n try {\n // An unbounded request can hang the whole scan — bound it so a stalled\n // electrs surfaces as a failure the caller can retry rather than a hang.\n res = await fetchFn(`${base.replace(/\\/$/, \"\")}${path}`, {\n ...(body === undefined\n ? { method: \"GET\" }\n : { method: \"POST\", headers: { \"content-type\": \"text/plain\" }, body }),\n signal: bound.signal,\n });\n } catch (error) {\n throw new EsploraError(\n `esplora ${base}${path}: request failed (${error instanceof Error ? error.name : \"unknown\"})`,\n true,\n );\n }\n if (res.status === 429) {\n return { throttled: res.headers };\n }\n if (!res.ok) {\n throw new EsploraError(`esplora ${base}${path}: ${res.status}`, res.status >= 500);\n }\n const text = await res.text();\n try {\n return { value: JSON.parse(text) as unknown };\n } catch {\n return { value: text };\n }\n } finally {\n bound.cancel();\n release();\n }\n };\n const call = async (\n base: string,\n path: string,\n body: string | undefined,\n retry: number,\n ): Promise<unknown> => {\n const outcome = await request(base, path, body);\n if (\"value\" in outcome) {\n return outcome.value;\n }\n if (retry >= MAX_RETRIES) {\n throw new EsploraError(`esplora ${base}${path}: 429 after ${MAX_RETRIES} retries`, true);\n }\n await backoff(outcome.throttled, retry);\n return call(base, path, body, retry + 1);\n };\n const attempt = async (\n rest: ReadonlyArray<string>,\n path: string,\n body: string | undefined,\n last: unknown,\n ): Promise<unknown> => {\n const [base, ...next] = rest;\n if (base === undefined) {\n throw last instanceof Error ? last : new Error(\"all esplora endpoints failed\");\n }\n try {\n return await call(base, path, body, 0);\n } catch (error) {\n return attempt(next, path, body, error);\n }\n };\n return {\n get: async (path) => attempt(endpoints, path, undefined, undefined),\n post: async (path, body) => attempt(endpoints, path, body, undefined),\n };\n};\n\nexport const validateEndpoint = async (es: Esplora, genesisHash: string): Promise<void> => {\n const got = await es.get(\"/block-height/0\");\n if (got !== genesisHash) {\n throw new Error(`endpoint genesis ${String(got)} ≠ ${genesisHash}`);\n }\n};\n\nexport const feeTiers = async (\n es: Esplora,\n): Promise<ReadonlyArray<{ tier: \"fast\" | \"normal\" | \"slow\" | \"economy\"; satPerByte: number }>> => {\n const res = await es.get(\"/fee-estimates\");\n const estimates = isObject(res) ? res : {};\n const pick = (target: string): number => Math.max(1, Math.ceil(Number(estimates[target] ?? 1)));\n return [\n { tier: \"fast\", satPerByte: pick(\"1\") },\n { tier: \"normal\", satPerByte: pick(\"3\") },\n { tier: \"slow\", satPerByte: pick(\"6\") },\n { tier: \"economy\", satPerByte: pick(\"144\") },\n ];\n};\n\nexport const dustFor = (scriptType: string): number => DUST[scriptType] ?? 546;\n\n/**\n * Ord builds inscription and rune outputs at TARGET_POSTAGE (10_000 sat) and never leaves more than\n * MAX_POSTAGE (20_000 sat) in one (ordinals/ord@1c2c8de: src/lib.rs:156,\n * src/wallet/transaction_builder.rs:17,138).\n */\nexport const ORD_MAX_POSTAGE = 20_000;\n\n/**\n * Whether a UTXO may carry an inscription or rune the wallet cannot see without an indexer, so it\n * is protected by default: every taproot output (the `ordinals` account; ord's own wallet is a\n * bip86 descriptor over /0/* and /1/*, docs/src/guides/wallet.md) and any output within ord's\n * postage.\n */\nexport const mayCarryInscription = (taproot: boolean, value: number): boolean =>\n taproot || value <= ORD_MAX_POSTAGE;\n\n/** Whether `address` decodes to a taproot (P2TR) output on `network`. */\nexport const isTaprootAddress = (address: string, network: typeof BTC_MAINNET): boolean =>\n Address(network).decode(address).type === \"tr\";\n\n/**\n * The spendable subset of `utxos` an automatic selection may pick: every output except the\n * user-frozen ones and those that may carry an inscription (taproot or at most 20 000 sats).\n * Inscription protection is a derived property, separate from freezing — unfreezing never\n * unprotects; a protected output is spendable only by naming it in `PrepareParams.inputs`.\n */\nexport const selectableUtxos = <\n U extends { txid: string; vout: number; value: number; address: string },\n>(\n utxos: ReadonlyArray<U>,\n network: typeof BTC_MAINNET,\n frozen: ReadonlySet<string>,\n): U[] => {\n return utxos.filter(\n (u) =>\n !frozen.has(`${u.txid}:${String(u.vout)}`) &&\n !mayCarryInscription(isTaprootAddress(u.address, network), u.value),\n );\n};\n\nexport type BtcInput = TransactionInputUpdate;\n\n/** Estimated signed size of one input, vbytes — BIP-141 worst case per template. */\nconst INPUT_VBYTES: Record<BitcoinAccountTemplate, number> = {\n \"btc.bip44\": 148,\n \"btc.bip49\": 91,\n \"btc.bip84\": 68,\n \"btc.bip86\": 57.5,\n};\n\n/** Estimated output size, vbytes, by script type — everything else costs at most a p2wsh. */\nconst OUTPUT_VBYTES: Record<string, number> = {\n pkh: 34,\n sh: 32,\n wpkh: 31,\n wsh: 43,\n tr: 43,\n};\n\n/** Version, segwit marker/flag, the two vector lengths and locktime, weighted. */\nconst TX_VBYTES_OVERHEAD = 10.5;\n\n/**\n * The one vsize estimate every build path shares — sends, exact replacements and CPFP children\n * alike — so the fee a transaction reports is the fee its own size demands.\n */\nexport const estimateVsize = (\n inputs: ReadonlyArray<BitcoinAccountTemplate>,\n outputs: ReadonlyArray<string>,\n network: typeof BTC_MAINNET,\n): number =>\n Math.ceil(\n TX_VBYTES_OVERHEAD +\n inputs.reduce((a, t) => a + INPUT_VBYTES[t], 0) +\n outputs.reduce(\n (a, address) => a + (OUTPUT_VBYTES[Address(network).decode(address).type] ?? 43),\n 0,\n ),\n );\n\nexport class BitcoinChainAdapter {\n /** Inputs for selectUTXO — the same TransactionInputUpdate objects added to the PSBT. */\n toInputs(\n utxos: ReadonlyArray<BtcUtxo>,\n fingerprint: number,\n pathOf: (utxo: BtcUtxo) => number[],\n pubkeyOf: (utxo: BtcUtxo) => Uint8Array,\n scriptOf: (utxo: BtcUtxo) => Uint8Array,\n template: string,\n rawTxOf?: (utxo: BtcUtxo) => Uint8Array | undefined,\n ): BtcInput[] {\n // Spendability is the caller's — confirmed outputs, its own unconfirmed change, or a CPFP\n // parent's outputs are all legitimate; inscription protection likewise. Only a locked\n // outpoint can never become an input.\n return utxos\n .filter((u) => u.status !== \"locked\")\n .map((u) => {\n const pub = pubkeyOf(u);\n // Taproot carries only witnessUtxo: the BIP-341 sighash commits to every input amount.\n // Every other template also carries the full previous transaction, from which the signer\n // proves its amounts. bip44 needs it already for selection (its prevout lives nowhere\n // else); for bip49/bip84 the caller attaches it once the selected inputs are known.\n // bip49 additionally carries the P2SH redeemScript.\n const entry: TransactionInputUpdate = {\n txid: u.txid,\n index: u.vout,\n sequence: 0xfffffffd,\n };\n if (template !== \"btc.bip44\") {\n entry.witnessUtxo = { amount: BigInt(u.value), script: scriptOf(u) };\n }\n if (template === \"btc.bip86\") {\n // `pubkeyOf` already returns the x-only internal key for bip86.\n entry.tapInternalKey = pub;\n entry.tapBip32Derivation = [[pub, { hashes: [], der: { fingerprint, path: pathOf(u) } }]];\n return entry;\n }\n const raw = rawTxOf === undefined ? undefined : rawTxOf(u);\n if (raw === undefined && template === \"btc.bip44\") {\n throw new Error(`no raw transaction for bip44 input ${u.txid}`);\n }\n if (raw !== undefined) {\n entry.nonWitnessUtxo = raw;\n }\n entry.bip32Derivation = [[pub, { fingerprint, path: pathOf(u) }]];\n if (template === \"btc.bip49\") {\n entry.redeemScript = p2wpkh(pub).script;\n }\n return entry;\n });\n }\n\n buildPsbt(\n inputs: ReadonlyArray<BtcInput>,\n to: string,\n amount: bigint,\n feePerByte: bigint,\n changeAddress: string,\n network: typeof BTC_MAINNET,\n strategy: \"default\" | \"all\" = \"default\",\n ): { readonly psbt: Uint8Array; readonly inputs: ReadonlyArray<BtcInput> } {\n const selection = selectUTXO([...inputs], [{ address: to, amount }], strategy, {\n feePerByte,\n changeAddress,\n bip69: true,\n dust: BigInt(dustFor(\"p2wpkh\")),\n network,\n createTx: true,\n });\n if (selection === undefined || selection.tx === undefined) {\n throw new Error(\"insufficient confirmed utxo for the amount + fee\");\n }\n const wanted = new Set(\n (selection.inputs ?? []).flatMap((sel) => {\n const raw = sel.txid;\n if (!(raw instanceof Uint8Array)) {\n return [];\n }\n const forward = hex.encode(raw);\n const reverse = hex.encode(Uint8Array.from(raw).reverse());\n return [`${forward}:${String(sel.index ?? -1)}`, `${reverse}:${String(sel.index ?? -1)}`];\n }),\n );\n const chosen = inputs.filter((i) => wanted.has(`${String(i.txid)}:${String(i.index)}`));\n return { psbt: selection.tx.toPSBT(), inputs: chosen };\n }\n\n /** Fixed-input/output PSBT — the RBF/CPFP path, which chooses nothing itself. */\n buildExactPsbt(\n inputs: ReadonlyArray<BtcInput>,\n outputs: ReadonlyArray<{ readonly address: string; readonly amount: bigint }>,\n network: typeof BTC_MAINNET,\n template: BitcoinAccountTemplate,\n ): { readonly psbt: Uint8Array; readonly vsize: number } {\n const tx = new Transaction();\n for (const input of inputs) {\n tx.addInput(input);\n }\n for (const out of outputs) {\n tx.addOutputAddress(out.address, out.amount, network);\n }\n const vsize = estimateVsize(\n inputs.map(() => template),\n outputs.map((o) => o.address),\n network,\n );\n return { psbt: tx.toPSBT(), vsize };\n }\n}\n","import { SiwxError, checkOrigin, createMessage, parseTimestamp } from \"@qntx/siwx\";\nimport type {\n AssetFlow,\n DisplayIntent,\n IntentWarningKind,\n MessageContent,\n SafeTransaction,\n SeaportOrder,\n SignInParse,\n} from \"@qntx/wallet-chains\";\nimport { SAFE_MULTISEND_CALL_ONLY, evmTokenTable } from \"@qntx/wallet-chains/evm\";\nimport { SOLANA_NATIVE_ASSET } from \"@qntx/wallet-chains/solana\";\nimport { tronTokenTable } from \"@qntx/wallet-chains/tron\";\n\nimport { mayCarryInscription } from \"../chains/bitcoin.ts\";\nimport type { PhishingStatus } from \"../phishing/status.ts\";\nimport type { RequestCheckCode } from \"./checks.ts\";\nimport { sameAsset } from \"./simulation.ts\";\nimport type { SimulationOutcome } from \"./simulation.ts\";\nimport type { WalletConnectVerify } from \"./types.ts\";\n\n/**\n * Request risk, pure. A recipient the wallet has never paid or saved is a `warning`; one that looks\n * like a known address (same first and last four characters, different address) is a `danger` — the\n * shape of an address-poisoning lookalike. Both can apply to one recipient. A page the user trusts\n * despite the phishing list is a `danger`; one that could not be checked is a `warning`. A sign-in\n * over QR carries no verifiable domain at all — a `danger` the user must acknowledge, since a dApp\n * claiming a domain it does not own is refused outright.\n */\nexport type RiskFinding = {\n readonly code:\n | \"first-recipient\"\n | \"address-poisoning\"\n | \"phishing-origin\"\n | \"phishing-unchecked\"\n | \"token-impersonation\"\n | \"token-symbol-unicode\"\n | \"simulation-reverted\"\n | \"simulation-mismatch\"\n | \"collection-approval\"\n | \"unlimited-approval\"\n | \"sign-in-malformed\"\n | \"sign-in-domain-mismatch\"\n | \"sign-in-port-mismatch\"\n | \"sign-in-address-mismatch\"\n | \"sign-in-expired\"\n | \"sign-in-not-yet-valid\"\n | \"permit-approval\"\n | \"permit-unlimited\"\n | \"permit-long-lived\"\n | \"order-receives-nothing\"\n | \"order-offerer-mismatch\"\n | \"safe-delegatecall\"\n | \"safe-gas-refund\"\n | \"bitcoin-sighash-single\"\n | \"bitcoin-inscription-input\"\n | \"bitcoin-frozen-input\"\n | \"bitcoin-unusual-output\"\n | \"bitcoin-unconfirmed-output\"\n | \"stake-authority\"\n | \"blind-signing\"\n | \"contract-recipient\"\n | \"token-contract-recipient\"\n | \"token-recipient-empty\"\n | \"fee-limit-below-estimate\"\n | \"verify-mismatch\"\n | \"verify-threat\"\n | \"fiat24-internal-account\"\n | \"fiat24-card-pull\"\n | \"fiat24-unlimited-approval\"\n | \"fiat24-exact-out-unbounded\"\n | \"fiat24-payee-offchain\"\n | \"fiat24-account-move\"\n | \"fiat24-account-burn\"\n | \"qr-sign-in-unverified\";\n readonly level: \"warning\" | \"danger\";\n};\n\nconst byDanger = (findings: ReadonlyArray<RiskFinding>): ReadonlyArray<RiskFinding> =>\n [...findings].sort((a, b) => Number(b.level === \"danger\") - Number(a.level === \"danger\"));\n\n/** The finding for a browser origin's phishing status, if any; `blocked` never reaches a request. */\nexport function originRisk(status: PhishingStatus): ReadonlyArray<RiskFinding> {\n if (status === \"trusted\") {\n return [{ code: \"phishing-origin\", level: \"danger\" }];\n }\n return status === \"unchecked\" ? [{ code: \"phishing-unchecked\", level: \"warning\" }] : [];\n}\n\n/**\n * A WalletConnect peer's Verify verdict: a flagged domain or a domain mismatch is a danger; an\n * unverifiable one is neutral.\n */\nexport function verifyRisk(verify: WalletConnectVerify): ReadonlyArray<RiskFinding> {\n const found: RiskFinding[] = [];\n if (verify.isScam) {\n found.push({ code: \"verify-threat\", level: \"danger\" });\n }\n if (verify.validation === \"INVALID\") {\n found.push({ code: \"verify-mismatch\", level: \"danger\" });\n }\n return found;\n}\n\n/** `findings` plus `extra`, deduplicated by code, `danger` first. */\nexport function mergeRisk(\n findings: ReadonlyArray<RiskFinding>,\n extra: ReadonlyArray<RiskFinding>,\n): ReadonlyArray<RiskFinding> {\n const byCode = new Map<RiskFinding[\"code\"], RiskFinding>();\n for (const finding of [...findings, ...extra]) {\n byCode.set(finding.code, finding);\n }\n return byDanger([...byCode.values()]);\n}\n\n/**\n * The finding a decoder's {@link IntentWarning} maps to — one entry for every `IntentWarningKind`,\n * `undefined` where the prompt rows already carry the fact and no request-level risk exists:\n *\n * - `platform-fee` — the fee is a prompt row.\n * - `stake-lockup` — the lockup window is a prompt row.\n * - `sighash-single-anyonecanpay` — already `bitcoin-sighash-single` via assessBitcoinPsbts.\n * - `permit2-witness` — the bound message is a prompt row.\n * - `delegation-replaced` — the replaced delegation is a prompt row.\n * - `token-2022-transfer-fee` — the withheld fee is a prompt row.\n * - `token-2022-extension` — the extension note is a prompt row.\n * - `fiat24-issuer-rate` — the issuer's applied rate is a prompt row.\n * - `fiat24-swap-quote` — the quoted rate is a prompt row.\n * - `fiat24-account-link` — the account link is a prompt row.\n */\nexport const WARNING_RISK: Readonly<\n Record<\n IntentWarningKind,\n { readonly code: RiskFinding[\"code\"]; readonly level: RiskFinding[\"level\"] } | undefined\n >\n> = {\n \"platform-fee\": undefined,\n \"stake-lockup\": undefined,\n \"sighash-single-anyonecanpay\": undefined,\n \"permit2-witness\": undefined,\n \"delegation-replaced\": undefined,\n \"token-2022-transfer-fee\": undefined,\n \"token-2022-extension\": undefined,\n \"fiat24-internal-account\": { code: \"fiat24-internal-account\", level: \"warning\" },\n \"fiat24-card-pull\": { code: \"fiat24-card-pull\", level: \"warning\" },\n \"fiat24-unlimited-approval\": { code: \"fiat24-unlimited-approval\", level: \"danger\" },\n \"fiat24-issuer-rate\": undefined,\n \"fiat24-exact-out-unbounded\": { code: \"fiat24-exact-out-unbounded\", level: \"warning\" },\n \"fiat24-payee-offchain\": { code: \"fiat24-payee-offchain\", level: \"warning\" },\n \"fiat24-swap-quote\": undefined,\n \"fiat24-account-link\": undefined,\n \"fiat24-account-move\": { code: \"fiat24-account-move\", level: \"danger\" },\n \"fiat24-account-burn\": { code: \"fiat24-account-burn\", level: \"warning\" },\n \"unusual-own-output\": { code: \"bitcoin-unusual-output\", level: \"warning\" },\n \"unconfirmed-signer-output\": { code: \"bitcoin-unconfirmed-output\", level: \"danger\" },\n};\n\n/**\n * Findings for every warning the decoded intents carry, through {@link WARNING_RISK}, deduplicated,\n * `danger` first. A warning stamped `level: \"danger\"` is a `danger` finding whatever the table says\n * — the decoder knows the concrete shape better than the kind default.\n */\nexport function assessWarnings(\n intents: ReadonlyArray<Pick<DisplayIntent, \"warnings\">>,\n): ReadonlyArray<RiskFinding> {\n const found = new Map<RiskFinding[\"code\"], RiskFinding>();\n for (const intent of intents) {\n for (const warning of intent.warnings) {\n const entry = WARNING_RISK[warning.kind];\n if (entry === undefined) {\n continue;\n }\n const level = warning.level ?? entry.level;\n if (found.get(entry.code)?.level !== \"danger\") {\n found.set(entry.code, { code: entry.code, level });\n }\n }\n }\n return byDanger([...found.values()]);\n}\n\n/**\n * Findings for the approvals a transaction grants: an operator approved for a whole collection is a\n * `danger`; a granted unlimited allowance is a `warning`. Revocations and reductions raise\n * nothing.\n */\nexport function assessApprovals(\n intent: Pick<DisplayIntent, \"approvals\">,\n): ReadonlyArray<RiskFinding> {\n const found = new Map<RiskFinding[\"code\"], RiskFinding>();\n for (const change of intent.approvals) {\n if (change.kind === \"operator\") {\n if (change.approved) {\n found.set(\"collection-approval\", { code: \"collection-approval\", level: \"danger\" });\n }\n } else if (change.kind === \"stake-authority\") {\n /* The decoder only emits this for a role handed to a key other than the signer. */\n found.set(\"stake-authority\", { code: \"stake-authority\", level: \"danger\" });\n } else if (change.kind === \"allowance\" && change.change !== \"decrease\" && change.unlimited) {\n found.set(\"unlimited-approval\", { code: \"unlimited-approval\", level: \"warning\" });\n }\n }\n return byDanger([...found.values()]);\n}\n\nconst PERMIT_MAX_LIFETIME_MS = 30 * 24 * 60 * 60 * 1000;\n\n/**\n * Findings for what a signed permit grants: any non-revoking allowance is a `warning`, an unlimited\n * one a `danger`, and a Permit2 allowance that lasts more than 30 days from `now` a `danger`.\n */\nexport function assessPermits(\n intent: Pick<DisplayIntent, \"approvals\">,\n now: number,\n): ReadonlyArray<RiskFinding> {\n const found = new Map<RiskFinding[\"code\"], RiskFinding>();\n for (const change of intent.approvals) {\n if (change.kind !== \"allowance\" || change.amount.amount === \"0\") {\n continue;\n }\n found.set(\"permit-approval\", { code: \"permit-approval\", level: \"warning\" });\n if (change.unlimited) {\n found.set(\"permit-unlimited\", { code: \"permit-unlimited\", level: \"danger\" });\n }\n if (\n change.via === \"permit2\" &&\n change.change === \"set\" &&\n change.expiration !== undefined &&\n change.expiration * 1000 > now + PERMIT_MAX_LIFETIME_MS\n ) {\n found.set(\"permit-long-lived\", { code: \"permit-long-lived\", level: \"danger\" });\n }\n }\n return byDanger([...found.values()]);\n}\n\n/**\n * Findings for a recognized Seaport order: an order whose `offer` gives up items without any\n * consideration paying the offerer is the zero-price-listing phishing shape (`danger`), and an\n * `offerer` other than the signing account is a `warning`.\n */\nexport function assessSeaport(\n order: SeaportOrder | undefined,\n signer: string,\n): ReadonlyArray<RiskFinding> {\n if (order === undefined) {\n return [];\n }\n const found = new Map<RiskFinding[\"code\"], RiskFinding>();\n const paid = order.consideration.some(\n (item) =>\n item.recipient.toLowerCase() === order.offerer.toLowerCase() &&\n (BigInt(item.startAmount.amount) > 0n || BigInt(item.endAmount.amount) > 0n),\n );\n if (order.offer.length > 0 && !paid) {\n found.set(\"order-receives-nothing\", { code: \"order-receives-nothing\", level: \"danger\" });\n }\n if (order.offerer.toLowerCase() !== signer.toLowerCase()) {\n found.set(\"order-offerer-mismatch\", { code: \"order-offerer-mismatch\", level: \"warning\" });\n }\n return byDanger([...found.values()]);\n}\n\n/**\n * Findings for a recognized Safe transaction: a `delegatecall` into a contract that is not a\n * canonical MultiSendCallOnly is the multisig-hijack phishing shape (`danger`), a non-zero gas\n * refund is a `warning`, and every decoded inner call's approvals are assessed too.\n */\nexport function assessSafe(safe: SafeTransaction | undefined): ReadonlyArray<RiskFinding> {\n if (safe === undefined) {\n return [];\n }\n const found = new Map<RiskFinding[\"code\"], RiskFinding>();\n for (const finding of safe.calls.flatMap((call) => assessApprovals(call))) {\n found.set(finding.code, finding);\n }\n if (safe.operation === \"delegatecall\" && !SAFE_MULTISEND_CALL_ONLY.has(safe.to.toLowerCase())) {\n found.set(\"safe-delegatecall\", { code: \"safe-delegatecall\", level: \"danger\" });\n }\n if (safe.refund !== undefined) {\n found.set(\"safe-gas-refund\", { code: \"safe-gas-refund\", level: \"warning\" });\n }\n return byDanger([...found.values()]);\n}\n\n/**\n * Findings for the inputs a dApp PSBT asks the wallet to sign. A `SINGLE|ANYONECANPAY` input binds\n * only its same-index output, so anyone can change the rest of the transaction: `danger`. Until\n * inscription data exists the heuristic is ord's postage rule — every taproot (ordinals-account)\n * input and every input worth at most ord's MAX_POSTAGE of 20_000 sat may carry an inscription:\n * such an input is a `warning` when it is signed as a listing (the sighash that fits selling it)\n * and a `danger` otherwise.\n */\nexport function assessBitcoinPsbts(\n inputs: ReadonlyArray<{\n readonly value: number;\n readonly template: \"btc.bip44\" | \"btc.bip49\" | \"btc.bip84\" | \"btc.bip86\";\n readonly sigHash: \"ALL\" | \"SINGLE|ANYONECANPAY\";\n readonly frozen: boolean;\n }>,\n): ReadonlyArray<RiskFinding> {\n const found = new Map<RiskFinding[\"code\"], RiskFinding>();\n if (inputs.some((i) => i.sigHash === \"SINGLE|ANYONECANPAY\")) {\n found.set(\"bitcoin-sighash-single\", { code: \"bitcoin-sighash-single\", level: \"danger\" });\n }\n if (inputs.some((i) => i.frozen)) {\n // The user froze this outpoint — the dApp is asking to spend it anyway.\n found.set(\"bitcoin-frozen-input\", { code: \"bitcoin-frozen-input\", level: \"danger\" });\n }\n const postage = inputs.filter((i) => mayCarryInscription(i.template === \"btc.bip86\", i.value));\n if (postage.length > 0) {\n found.set(\"bitcoin-inscription-input\", {\n code: \"bitcoin-inscription-input\",\n level: postage.some((i) => i.sigHash !== \"SINGLE|ANYONECANPAY\") ? \"danger\" : \"warning\",\n });\n }\n return byDanger([...found.values()]);\n}\n\nconst LOCAL_HOSTS: ReadonlySet<string> = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\n\n/** `scheme`, `host` (IPv6 keeps its brackets) and `hostPort` of a `scheme://host[:port]` origin. */\nconst originParts = (origin: string): { scheme: string; host: string; hostPort: string } => {\n const sep = origin.indexOf(\"://\");\n const rest = origin.slice(sep + 3);\n const end = rest.startsWith(\"[\") ? rest.indexOf(\"]\") + 1 : rest.lastIndexOf(\":\");\n return {\n scheme: sep === -1 ? \"\" : origin.slice(0, sep).toLowerCase(),\n host: (end > 0 ? rest.slice(0, end) : rest).toLowerCase(),\n hostPort: rest.toLowerCase(),\n };\n};\n\nconst isLocalHost = (host: string): boolean => LOCAL_HOSTS.has(host) || host.endsWith(\".localhost\");\n\n/**\n * What a Sign-In with X message adds to a request from `origin`: a message for another domain is\n * refused (`reject`) in production and a `danger` on a local development page; the signing address\n * must be the signer; an expired or not-yet-valid window and a text that only resembles a sign-in\n * message are warnings. TRON has no sign-in standard — a `tron` parse is only ever `malformed`, the\n * claims-only path.\n */\nexport function assessSignIn(input: {\n readonly signIn: SignInParse;\n /** The page origin, `scheme://host[:port]`. */\n readonly origin: string;\n /** The address that will sign. */\n readonly signer: string;\n readonly family: \"evm\" | \"solana\" | \"tron\";\n /** Milliseconds since the epoch. */\n readonly now: number;\n}): { readonly reject?: string; readonly risk: ReadonlyArray<RiskFinding> } {\n const { signIn, origin, signer, family, now } = input;\n const { scheme, host, hostPort } = originParts(origin);\n const developer = isLocalHost(host);\n if (signIn.status === \"malformed\") {\n /* Lenient verifiers accept such a text as a sign-in for every claimed domain, so each claim is\n * bound to the page like a conforming domain: refuse a foreign one on production, flag it on a\n * local development page. */\n for (const claim of signIn.claims) {\n const matches =\n claim.domain.toLowerCase() === hostPort &&\n (claim.scheme === undefined || claim.scheme.toLowerCase() === scheme);\n if (!matches) {\n return developer\n ? { risk: [{ code: \"sign-in-domain-mismatch\", level: \"danger\" }] }\n : { reject: `the sign-in message is for ${claim.domain}, not this page`, risk: [] };\n }\n }\n return { risk: [{ code: \"sign-in-malformed\", level: \"warning\" }] };\n }\n const { fields } = signIn;\n let findings: ReturnType<typeof checkOrigin>;\n try {\n findings = checkOrigin(\n createMessage(fields),\n origin,\n developer\n ? { allowedSchemes: [\"https\", \"http\"], defaultScheme: scheme, developerMode: true }\n : {},\n );\n } catch (error) {\n if (error instanceof SiwxError && error.code === \"InvalidOrigin\") {\n return { reject: \"the page origin is not a valid web origin\", risk: [] };\n }\n throw error;\n }\n if (findings.some((f) => f.severity === \"reject\")) {\n return { reject: `the sign-in message is for ${fields.domain}, not this page`, risk: [] };\n }\n const found = new Map<RiskFinding[\"code\"], RiskFinding>();\n const add = (code: RiskFinding[\"code\"], level: RiskFinding[\"level\"]): void => {\n found.set(code, { code, level });\n };\n for (const finding of findings) {\n if (finding.code === \"PortMismatch\") {\n add(\"sign-in-port-mismatch\", \"warning\");\n } else {\n add(\"sign-in-domain-mismatch\", \"danger\");\n }\n }\n const same =\n family === \"evm\"\n ? fields.address.toLowerCase() === signer.toLowerCase()\n : fields.address === signer;\n if (!same) {\n add(\"sign-in-address-mismatch\", \"danger\");\n }\n const expires =\n fields.expirationTime === undefined ? undefined : parseTimestamp(fields.expirationTime);\n if (expires !== undefined && expires.epochMs < now) {\n add(\"sign-in-expired\", \"warning\");\n }\n const notBefore = fields.notBefore === undefined ? undefined : parseTimestamp(fields.notBefore);\n if (notBefore !== undefined && notBefore.epochMs > now) {\n add(\"sign-in-not-yet-valid\", \"warning\");\n }\n return { risk: byDanger([...found.values()]) };\n}\n\n/** Characters compared at each end of an address. */\nexport const POISONING_EDGE = 4;\n\n/** EVM addresses compare without the `0x` prefix and case-insensitively. */\nexport const comparable = (family: string, address: string): string =>\n family === \"evm\" ? address.replace(/^0x/i, \"\").toLowerCase() : address;\n\n/**\n * Who a flow pays. A Fiat24 ledger transfer or payout names its recipient in the calldata — `to` is\n * the cash-token contract all of them share — so the account or payee is the recipient compared.\n */\n/**\n * Addresses the wallet already knows for a family: contacts, plus recipients of tracked chain sends\n * (Spark payments are not tracked — for spark the contacts list is the whole answer).\n */\nexport const knownAddresses = (\n entries: ReadonlyArray<{ readonly family: string; readonly address: string }>,\n txs: ReadonlyArray<{\n readonly family: string;\n readonly state: string;\n readonly intent?: DisplayIntent | undefined;\n }>,\n family: string,\n): ReadonlyArray<string> => {\n const contacts = entries.filter((e) => e.family === family).map((e) => e.address);\n if (family === \"spark\") {\n return contacts;\n }\n const paid = txs\n .filter(\n (tx) =>\n tx.family === family &&\n (tx.state === \"submitted\" || tx.state === \"pending\" || tx.state === \"confirmed\"),\n )\n .flatMap((tx) => tx.intent?.outflows.map(recipientOf) ?? []);\n return [...contacts, ...paid];\n};\n\nexport const recipientOf = (flow: Pick<AssetFlow, \"to\" | \"fiat24\">): string =>\n flow.fiat24 === undefined\n ? flow.to\n : \"account\" in flow.fiat24\n ? `fiat24:account:${flow.fiat24.account}`\n : `fiat24:payee:${flow.fiat24.payee}`;\n\nconst looksLike = (a: string, b: string): boolean =>\n a !== b &&\n /* Only address-shaped values look alike: Fiat24 ids are small integers, so two of them sharing\n four digits at both ends says nothing. */\n !a.startsWith(\"fiat24:\") &&\n !b.startsWith(\"fiat24:\") &&\n a.length >= POISONING_EDGE * 2 &&\n b.length >= POISONING_EDGE * 2 &&\n a.slice(0, POISONING_EDGE) === b.slice(0, POISONING_EDGE) &&\n a.slice(-POISONING_EDGE) === b.slice(-POISONING_EDGE);\n\n/**\n * Findings for every recipient of one request, deduplicated, `danger` first. Recipients come from\n * {@link recipientOf}: a Fiat24 flow's recipient is the account or payee it names.\n */\nexport function assessRecipients(\n family: string,\n recipients: ReadonlyArray<string>,\n known: ReadonlyArray<string>,\n): ReadonlyArray<RiskFinding> {\n const knownSet = new Set(known.map((a) => comparable(family, a)));\n const found = new Map<RiskFinding[\"code\"], RiskFinding>();\n for (const recipient of recipients) {\n const candidate = comparable(family, recipient);\n if (knownSet.has(candidate)) {\n continue;\n }\n found.set(\"first-recipient\", { code: \"first-recipient\", level: \"warning\" });\n if ([...knownSet].some((k) => looksLike(candidate, k))) {\n found.set(\"address-poisoning\", { code: \"address-poisoning\", level: \"danger\" });\n }\n }\n return byDanger([...found.values()]);\n}\n\n/**\n * Every party a decoded intent names as receiving value or authority over the signer's value: the\n * outflow recipients (a burned output's script is nobody — a destroyed amount has no recipient),\n * the recipients swap and bridge terms enforce, approval and permission grantees (a revocation\n * names nobody), the inner calls a batch names, and the destinations a recognized typed-data\n * document signs.\n */\nexport const intentRecipients = (intent: DisplayIntent): ReadonlyArray<string> => {\n const recipients: string[] = [];\n const push = (inner: DisplayIntent): void => {\n recipients.push(\n ...inner.outflows.filter((flow) => flow.burn !== true).map(recipientOf),\n ...(inner.minimumReceived?.map((minimum) => minimum.to) ?? []),\n );\n for (const approval of inner.approvals ?? []) {\n /* A grantee takes authority over the signer's value — assessed like a recipient; a\n revocation names nobody: a decrease, a zeroed allowance, a revoked operator or delegate,\n a cleared approval. */\n if (approval.kind === \"allowance\") {\n if (\n approval.change !== \"decrease\" &&\n !(approval.change === \"set\" && approval.amount.amount === \"0\")\n ) {\n recipients.push(approval.spender);\n }\n } else if (approval.kind === \"operator\") {\n if (approval.approved) {\n recipients.push(approval.spender);\n }\n } else if (approval.kind === \"stake-authority\") {\n recipients.push(approval.authority);\n }\n }\n if (inner.bridge !== undefined) {\n recipients.push(inner.bridge.refundTo);\n }\n if (inner.hyperliquidDeposit !== undefined) {\n recipients.push(inner.hyperliquidDeposit.recipient);\n }\n for (const action of inner.staking ?? []) {\n /* A withdraw's destination, the claim NFT's owner and a delegate's receiver take value off\n the signer; a split's `to` is the stake account the same call creates, and an\n undelegate's receiver only gets delegated resources back. */\n if (action.kind === \"withdraw\") {\n recipients.push(action.to);\n } else if (action.kind === \"lido-request\") {\n recipients.push(action.owner);\n } else if (action.kind === \"tron-delegate\") {\n recipients.push(action.receiver);\n }\n }\n const { permissionUpdate } = inner.tron ?? {};\n if (permissionUpdate !== undefined) {\n for (const permission of [\n permissionUpdate.owner,\n ...(permissionUpdate.witness === undefined ? [] : [permissionUpdate.witness]),\n ...permissionUpdate.actives,\n ]) {\n recipients.push(...permission.keys.map((key) => key.address));\n }\n }\n const { message } = inner;\n if (message?.kind === \"typed-data\") {\n recipients.push(...messageRecipients(message));\n }\n for (const call of inner.calls ?? []) {\n push(call);\n }\n };\n push(intent);\n return recipients;\n};\n\n/** The destinations a recognized typed-data document pays, wherever its own shape names them. */\nconst messageRecipients = (\n message: Extract<MessageContent, { kind: \"typed-data\" }>,\n): ReadonlyArray<string> => {\n const recipients: string[] = [\n ...(message.order?.receive.map((entry) => entry.recipient) ?? []),\n ...(message.seaport?.consideration.map((item) => item.recipient) ?? []),\n ];\n const { safe } = message;\n if (safe !== undefined) {\n /* `to` receives value only when the call pays; a zero-value call can still move tokens, which\n its decoded inner calls already name. */\n if (safe.value !== \"0\") {\n recipients.push(safe.to);\n }\n for (const call of safe.calls) {\n recipients.push(...intentRecipients(call));\n }\n if (safe.refund?.receiver !== undefined) {\n recipients.push(safe.refund.receiver);\n }\n }\n const action = message.hyperliquid;\n /* Only the user-signed actions that pay a destination — usd-send, withdraw, spot-send and\n send-asset are exactly the shapes carrying `destination`. */\n if (action !== undefined && \"destination\" in action) {\n recipients.push(action.destination);\n }\n const { polymarket } = message;\n if (polymarket?.kind === \"batch\") {\n for (const call of polymarket.calls) {\n recipients.push(...intentRecipients(call));\n }\n }\n const { authorization } = message;\n if (authorization !== undefined && authorization.kind !== \"cancel\") {\n recipients.push(authorization.to);\n }\n const { authority } = message;\n /* Authority grants hand the signer's account to the grantee — assessed like recipients;\n a revocation (morpho grant=false, a zero aave credit line) names nobody, and a\n snapshot-alias grants no authority over value. */\n if (authority?.kind === \"morpho\") {\n if (authority.grant) {\n recipients.push(authority.authorized);\n }\n } else if (authority?.kind === \"aave-credit\" && authority.amount.amount !== \"0\") {\n recipients.push(authority.delegatee);\n }\n return recipients;\n};\n\n/**\n * Recipient findings for one decoded intent: {@link assessRecipients} over {@link intentRecipients},\n * except the signer itself — swaps, wraps and refunds routinely pay the account back.\n */\nexport function assessIntentRecipients(\n intent: DisplayIntent,\n self: string | undefined,\n known: ReadonlyArray<string>,\n): ReadonlyArray<RiskFinding> {\n const own = self === undefined ? undefined : comparable(intent.family, self);\n return assessRecipients(\n intent.family,\n intentRecipients(intent).filter(\n (recipient) => own === undefined || comparable(intent.family, recipient) !== own,\n ),\n known,\n );\n}\n\ntype DecodedIntent = Pick<DisplayIntent, \"outflows\" | \"verifiability\">;\n\nconst declaredOutflow = (intent: DecodedIntent, asset: string): bigint =>\n intent.outflows\n .filter((flow) => sameAsset(flow.amount.asset, asset))\n .reduce((sum, flow) => sum + BigInt(flow.amount.amount), 0n);\n\n/**\n * What a simulation adds to a request. `unavailable` blocks silent approval; `reverted` is a\n * danger; an outflow above what the decode declares for that asset is a danger too — but only\n * against a decode that is not `opaque`, and never for Solana lamports (fees and rent always exceed\n * the declared amount).\n */\nexport function assessSimulation(\n intent: DecodedIntent,\n outcome: SimulationOutcome | undefined,\n): { readonly checks: ReadonlyArray<RequestCheckCode>; readonly risk: ReadonlyArray<RiskFinding> } {\n if (outcome === undefined) {\n return { checks: [], risk: [] };\n }\n if (outcome.status === \"unavailable\") {\n return { checks: [\"simulation-unavailable\"], risk: [] };\n }\n if (outcome.status === \"reverted\") {\n return { checks: [], risk: [{ code: \"simulation-reverted\", level: \"danger\" }] };\n }\n const mismatch =\n intent.verifiability !== \"opaque\" &&\n outcome.changes.some((change) => {\n const amount = BigInt(change.amount);\n return (\n amount < 0n &&\n change.asset !== SOLANA_NATIVE_ASSET &&\n -amount > declaredOutflow(intent, change.asset)\n );\n });\n return {\n checks: [],\n risk: mismatch ? [{ code: \"simulation-mismatch\", level: \"danger\" }] : [],\n };\n}\n\n/**\n * A token on `chainId` that reports the symbol of a different, built-in token of the same chain —\n * the shape of a lookalike token. Symbols compare case-insensitively.\n */\nexport function impersonatesBuiltIn(chainId: number, address: string, symbol: string): boolean {\n const wanted = symbol.toLowerCase();\n return Object.entries(evmTokenTable[String(chainId)] ?? {}).some(\n ([known, token]) =>\n known.toLowerCase() !== address.toLowerCase() && token.symbol.toLowerCase() === wanted,\n );\n}\n\n/**\n * The TRC-20 counterpart of {@link impersonatesBuiltIn}: a contract reporting the symbol of a\n * different token in the TRON table. Addresses are base58 — case-sensitive, no checksum folding.\n */\nexport function impersonatesTronToken(network: string, address: string, symbol: string): boolean {\n const wanted = symbol.toLowerCase();\n return Object.entries(tronTokenTable[network] ?? {}).some(\n ([known, token]) => known !== address && token.symbol.toLowerCase() === wanted,\n );\n}\n"],"mappings":";;;;;;;;;;;;AAmBA,MAAa,wBAAwB;;AAGrC,MAAa,aAAa,GAAW,MACnC,MAAM,KAAM,EAAE,WAAW,IAAI,KAAK,EAAE,YAAY,MAAM,EAAE,YAAY;;AAGtE,MAAa,4BAA4B;AAEzC,MAAM,UAAU,SAAqC,UACnD,QAAQ,OAAO,MAAM,MAAM,MAAM,MAAM,UAAU,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;AAErE,MAAM,SAAS,SAAqC,UAClD,QAAQ,QAAQ,MAAM,UAAU,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC,QAAQ,KAAK,MAAM,MAAM,OAAO,EAAE,MAAM,GAAG,EAAE;;;;;;;AAQhG,SAAgB,kBAAkB,QAA2B,OAAmC;CAC9F,IAAI,OAAO,WAAW,MAAM,QAC1B,OAAO;CAET,IAAI,OAAO,WAAW,aAAa,MAAM,WAAW,WAClD,OAAO;CAET,IAAI,CAAC,OAAO,OAAO,SAAS,MAAM,OAAO,KAAK,CAAC,OAAO,MAAM,SAAS,OAAO,OAAO,GACjF,OAAO;CAET,OAAO,OAAO,QAAQ,MAAM,EAAE,YAAY;EACxC,MAAM,QAAQ,MAAM,OAAO,SAAS,KAAK;EACzC,MAAM,OAAO,MAAM,MAAM,SAAS,KAAK;EACvC,MAAM,OAAO,QAAQ,OAAO,QAAQ,OAAO,OAAO;EAClD,MAAM,OAAO,QAAQ,KAAK,CAAC,QAAQ;EACnC,OAAO,OAAO,OAAO,OAAO;CAC9B,CAA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W,MAAM,OAAO,YAAY,MAAM,MAC1E;AACF"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// src/gateway/session.ts
|
|
2
|
+
const hex = (bytes) => [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
3
|
+
/** A fresh client id per scope for one engine session — unlinkable across scopes and sessions. */
|
|
4
|
+
function gatewaySession(url, random) {
|
|
5
|
+
return {
|
|
6
|
+
url,
|
|
7
|
+
clientIds: {
|
|
8
|
+
evm: hex(random(16)),
|
|
9
|
+
solana: hex(random(16)),
|
|
10
|
+
bitcoin: hex(random(16)),
|
|
11
|
+
tron: hex(random(16)),
|
|
12
|
+
service: hex(random(16))
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
export { gatewaySession as t };
|
|
17
|
+
|
|
18
|
+
//# sourceMappingURL=session-CNJFLarP.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session-CNJFLarP.mjs","names":[],"sources":["../src/gateway/session.ts"],"sourcesContent":["/**\n * Per-session gateway client ids — a fresh unlinkable id per scope. Lives apart from client.ts so\n * entries that need only session ids (the apps eligibility fetch) don't bundle the contract table\n * that `gatewayScope` requires.\n */\n/** A gateway traffic class with its own client id: one per chain family plus the service routes. */\nexport type GatewayScope = \"evm\" | \"solana\" | \"bitcoin\" | \"tron\" | \"service\";\n\nexport type GatewayConfig = {\n readonly url: string;\n readonly clientIds: Readonly<Record<GatewayScope, string>>;\n};\n\nconst hex = (bytes: Uint8Array): string =>\n [...bytes].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n\n/** A fresh client id per scope for one engine session — unlinkable across scopes and sessions. */\nexport function gatewaySession(url: string, random: (length: number) => Uint8Array): GatewayConfig {\n return {\n url,\n clientIds: {\n evm: hex(random(16)),\n solana: hex(random(16)),\n bitcoin: hex(random(16)),\n tron: hex(random(16)),\n service: hex(random(16)),\n },\n };\n}\n"],"mappings":";AAaA,MAAM,OAAO,UACX,CAAC,GAAG,KAAK,CAAC,CAAC,KAAK,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;;AAGhE,SAAgB,eAAe,KAAa,QAAuD;CACjG,OAAO;EACL;EACA,WAAW;GACT,KAAK,IAAI,OAAO,EAAE,CAAC;GACnB,QAAQ,IAAI,OAAO,EAAE,CAAC;GACtB,SAAS,IAAI,OAAO,EAAE,CAAC;GACvB,MAAM,IAAI,OAAO,EAAE,CAAC;GACpB,SAAS,IAAI,OAAO,EAAE,CAAC;EACzB;CACF;AACF"}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
const BACKOFF_MAX_MS = 3e4;
|
|
2
|
+
const STABLE_MS = 3e4;
|
|
3
|
+
function createAppSocketCore(options) {
|
|
4
|
+
const statusListeners = /* @__PURE__ */ new Set();
|
|
5
|
+
let socket;
|
|
6
|
+
let status = "closed";
|
|
7
|
+
let closedByUser = false;
|
|
8
|
+
let attempts = 0;
|
|
9
|
+
let pingCancel;
|
|
10
|
+
let pongCancel;
|
|
11
|
+
let stableCancel;
|
|
12
|
+
let reconnectCancel;
|
|
13
|
+
const delay = (ms, fn) => options.setTimer(ms, fn);
|
|
14
|
+
const jittered = (ms) => ms + Math.floor((options.random(1)[0] ?? 0) / 256 * ms);
|
|
15
|
+
const setStatus = (next) => {
|
|
16
|
+
if (status !== next) {
|
|
17
|
+
status = next;
|
|
18
|
+
for (const listener of statusListeners) listener(next);
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
const stopHeartbeat = () => {
|
|
22
|
+
pingCancel?.();
|
|
23
|
+
pingCancel = void 0;
|
|
24
|
+
pongCancel?.();
|
|
25
|
+
pongCancel = void 0;
|
|
26
|
+
};
|
|
27
|
+
const scheduleReconnect = () => {
|
|
28
|
+
if (closedByUser || reconnectCancel !== void 0) return;
|
|
29
|
+
const backoff = Math.min(BACKOFF_MAX_MS, 500 * 2 ** attempts);
|
|
30
|
+
attempts += 1;
|
|
31
|
+
reconnectCancel = delay(jittered(backoff), () => {
|
|
32
|
+
reconnectCancel = void 0;
|
|
33
|
+
connect();
|
|
34
|
+
});
|
|
35
|
+
};
|
|
36
|
+
const armPing = () => {
|
|
37
|
+
pingCancel = delay(options.heartbeat.intervalMs, () => {
|
|
38
|
+
socket?.send(options.heartbeat.ping);
|
|
39
|
+
pongCancel = delay(options.heartbeat.pongTimeoutMs, () => socket?.close());
|
|
40
|
+
armPing();
|
|
41
|
+
});
|
|
42
|
+
};
|
|
43
|
+
const startHeartbeat = () => {
|
|
44
|
+
stopHeartbeat();
|
|
45
|
+
armPing();
|
|
46
|
+
};
|
|
47
|
+
const onOpen = () => {
|
|
48
|
+
setStatus("open");
|
|
49
|
+
stableCancel?.();
|
|
50
|
+
stableCancel = delay(STABLE_MS, () => {
|
|
51
|
+
attempts = 0;
|
|
52
|
+
});
|
|
53
|
+
startHeartbeat();
|
|
54
|
+
options.onOpen?.();
|
|
55
|
+
};
|
|
56
|
+
const onClose = () => {
|
|
57
|
+
stopHeartbeat();
|
|
58
|
+
stableCancel?.();
|
|
59
|
+
stableCancel = void 0;
|
|
60
|
+
setStatus("closed");
|
|
61
|
+
socket = void 0;
|
|
62
|
+
if (!closedByUser) scheduleReconnect();
|
|
63
|
+
};
|
|
64
|
+
const onMessage = (event) => {
|
|
65
|
+
const raw = typeof event.data === "string" ? event.data : "";
|
|
66
|
+
if (options.heartbeat.isPong(raw)) {
|
|
67
|
+
pongCancel?.();
|
|
68
|
+
pongCancel = void 0;
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
options.onMessage?.(raw);
|
|
72
|
+
};
|
|
73
|
+
const connect = () => {
|
|
74
|
+
if (closedByUser || socket !== void 0) return;
|
|
75
|
+
setStatus("connecting");
|
|
76
|
+
const next = options.socket(options.url);
|
|
77
|
+
socket = next;
|
|
78
|
+
next.onopen = onOpen;
|
|
79
|
+
next.onmessage = onMessage;
|
|
80
|
+
next.onclose = onClose;
|
|
81
|
+
next.onerror = () => next.close();
|
|
82
|
+
};
|
|
83
|
+
return {
|
|
84
|
+
status: () => status,
|
|
85
|
+
onStatus: (listener) => {
|
|
86
|
+
statusListeners.add(listener);
|
|
87
|
+
return () => {
|
|
88
|
+
statusListeners.delete(listener);
|
|
89
|
+
};
|
|
90
|
+
},
|
|
91
|
+
connect,
|
|
92
|
+
readyState: () => socket?.readyState,
|
|
93
|
+
send: (data) => {
|
|
94
|
+
socket?.send(data);
|
|
95
|
+
},
|
|
96
|
+
closedByUser: () => closedByUser,
|
|
97
|
+
close: () => {
|
|
98
|
+
closedByUser = true;
|
|
99
|
+
reconnectCancel?.();
|
|
100
|
+
reconnectCancel = void 0;
|
|
101
|
+
options.onUserClose?.();
|
|
102
|
+
socket?.close();
|
|
103
|
+
socket = void 0;
|
|
104
|
+
setStatus("closed");
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
export { createAppSocketCore as t };
|
|
109
|
+
|
|
110
|
+
//# sourceMappingURL=socket-ChG9JRT_.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"socket-ChG9JRT_.mjs","names":[],"sources":["../src/apps/socket.ts"],"sourcesContent":["/**\n * The transport-agnostic apps socket: one lazily-opened WebSocket with status transitions,\n * exponential-backoff reconnects with jitter (reset once a connection stays up `STABLE_MS`), a\n * configurable heartbeat (the ping frame text and an `isPong` predicate checked before the message\n * hook), and user close that ends reconnects. All I/O is injected (`socket` factory, `setTimer`,\n * `random`) — no ambient I/O.\n *\n * Protocol layers build on `onOpen` (resubscribe) and `onMessage` (raw frames that are not pongs);\n * the core never interprets payloads.\n */\n\nimport type { SetTimer } from \"../timer.ts\";\n\n/* oxlint-disable typescript/no-restricted-types -- the standard WebSocket handler fields are `| null` */\n/** The WebSocket property-handler subset every runtime provides (browser, RN, Node ≥ 22). */\nexport type AppSocket = {\n readonly readyState: number;\n readonly send: (data: string) => void;\n readonly close: () => void;\n onopen: (() => void) | null;\n onmessage: ((event: { readonly data: unknown }) => void) | null;\n onclose: (() => void) | null;\n onerror: (() => void) | null;\n};\n/* oxlint-enable typescript/no-restricted-types */\n\n/** Connection lifecycle the live layers watch. */\nexport type AppSocketStatus = \"connecting\" | \"open\" | \"closed\";\n\n/** Reconnect backoff bounds and the uptime that resets the attempt count. */\nexport const BACKOFF_MIN_MS = 500;\nexport const BACKOFF_MAX_MS = 30_000;\nexport const STABLE_MS = 30_000;\n\nexport type AppSocketHeartbeat = {\n /** How often the ping frame goes out. */\n readonly intervalMs: number;\n /** How long after a ping a missing pong closes the socket and reconnects. */\n readonly pongTimeoutMs: number;\n /** The frame text sent every interval — `{\"method\":\"ping\"}` or a plain `PING`. */\n readonly ping: string;\n /**\n * Checked against the raw frame text before `onMessage`: a pong clears the pending pong wait and\n * is never delivered to the protocol layer.\n */\n readonly isPong: (raw: string) => boolean;\n};\n\nexport type AppSocketCoreOptions = {\n readonly url: string;\n /** The socket factory, e.g. `(url) => new WebSocket(url)`. */\n readonly socket: (url: string) => AppSocket;\n readonly setTimer: SetTimer;\n /** Jitter source — one byte scaled to [0,1) of the backoff. */\n readonly random: (length: number) => Uint8Array;\n readonly heartbeat: AppSocketHeartbeat;\n /** Runs after `open` and the heartbeat start — the protocol's resubscribe hook. */\n readonly onOpen?: () => void;\n /** Raw text frames that are not pongs — the protocol's dispatcher. */\n readonly onMessage?: (raw: string) => void;\n /**\n * Runs inside `close()` once the user-close flag and reconnect cancellation are in place but\n * before the socket drops — the protocol fails its pendings here so a reentrant call still sees\n * `closedByUser() === true` and the live socket.\n */\n readonly onUserClose?: () => void;\n};\n\n/** The connection handle a protocol layer (subscriptions, frames) builds its protocol on. */\nexport type AppSocketCore = {\n /** Current connection status. */\n readonly status: () => AppSocketStatus;\n /** Subscribe to status transitions; returns an unsubscribe. */\n readonly onStatus: (listener: (status: AppSocketStatus) => void) => () => void;\n /** Lazily open the socket — no-op once user-closed or while a socket exists. */\n readonly connect: () => void;\n /** The live socket's readyState, or undefined when there is no live socket. */\n readonly readyState: () => number | undefined;\n /** `socket?.send(data)` — a no-op while there is no live socket. */\n readonly send: (data: string) => void;\n /** Whether `close()` ran — guards subscribe/connect entry points. */\n readonly closedByUser: () => boolean;\n /** Ends the connection and prevents reconnects. */\n readonly close: () => void;\n};\n\nexport function createAppSocketCore(options: AppSocketCoreOptions): AppSocketCore {\n const statusListeners = new Set<(status: AppSocketStatus) => void>();\n let socket: AppSocket | undefined;\n let status: AppSocketStatus = \"closed\";\n let closedByUser = false;\n let attempts = 0;\n let pingCancel: (() => void) | undefined;\n let pongCancel: (() => void) | undefined;\n let stableCancel: (() => void) | undefined;\n let reconnectCancel: (() => void) | undefined;\n\n const delay = (ms: number, fn: () => void): (() => void) => options.setTimer(ms, fn);\n const jittered = (ms: number): number =>\n ms + Math.floor(((options.random(1)[0] ?? 0) / 256) * ms);\n\n const setStatus = (next: AppSocketStatus): void => {\n if (status !== next) {\n status = next;\n for (const listener of statusListeners) {\n listener(next);\n }\n }\n };\n\n const stopHeartbeat = (): void => {\n pingCancel?.();\n pingCancel = undefined;\n pongCancel?.();\n pongCancel = undefined;\n };\n\n /* Reconnect: every non-user close/error retries — `close()` is the only way out. */\n const scheduleReconnect = (): void => {\n if (closedByUser || reconnectCancel !== undefined) {\n return;\n }\n const backoff = Math.min(BACKOFF_MAX_MS, BACKOFF_MIN_MS * 2 ** attempts);\n attempts += 1;\n reconnectCancel = delay(jittered(backoff), () => {\n reconnectCancel = undefined;\n connect();\n });\n };\n\n const armPing = (): void => {\n pingCancel = delay(options.heartbeat.intervalMs, () => {\n socket?.send(options.heartbeat.ping);\n /* No pong within the window: the connection is dead — drop it and reconnect. */\n pongCancel = delay(options.heartbeat.pongTimeoutMs, () => socket?.close());\n armPing();\n });\n };\n\n const startHeartbeat = (): void => {\n stopHeartbeat();\n armPing();\n };\n\n const onOpen = (): void => {\n setStatus(\"open\");\n stableCancel?.();\n stableCancel = delay(STABLE_MS, () => {\n attempts = 0;\n });\n startHeartbeat();\n options.onOpen?.();\n };\n\n const onClose = (): void => {\n stopHeartbeat();\n stableCancel?.();\n stableCancel = undefined;\n setStatus(\"closed\");\n socket = undefined;\n if (!closedByUser) {\n scheduleReconnect();\n }\n };\n\n const onMessage = (event: { readonly data: unknown }): void => {\n const raw = typeof event.data === \"string\" ? event.data : \"\";\n if (options.heartbeat.isPong(raw)) {\n pongCancel?.();\n pongCancel = undefined;\n return;\n }\n options.onMessage?.(raw);\n };\n\n const connect = (): void => {\n if (closedByUser || socket !== undefined) {\n return;\n }\n setStatus(\"connecting\");\n const next = options.socket(options.url);\n socket = next;\n /* oxlint-disable unicorn/prefer-add-event-listener -- AppSocket is the property-handler subset */\n next.onopen = onOpen;\n next.onmessage = onMessage;\n next.onclose = onClose;\n next.onerror = () => next.close();\n /* oxlint-enable unicorn/prefer-add-event-listener */\n };\n\n return {\n status: () => status,\n onStatus: (listener) => {\n statusListeners.add(listener);\n return () => {\n statusListeners.delete(listener);\n };\n },\n connect,\n readyState: () => socket?.readyState,\n send: (data) => {\n socket?.send(data);\n },\n closedByUser: () => closedByUser,\n close: () => {\n closedByUser = true;\n reconnectCancel?.();\n reconnectCancel = undefined;\n options.onUserClose?.();\n socket?.close();\n socket = undefined;\n setStatus(\"closed\");\n },\n };\n}\n"],"mappings":"AA+BA,MAAa,iBAAiB;AAC9B,MAAa,YAAY;AAsDzB,SAAgB,oBAAoB,SAA8C;CAChF,MAAM,kCAAkB,IAAI,IAAuC;CACnE,IAAI;CACJ,IAAI,SAA0B;CAC9B,IAAI,eAAe;CACnB,IAAI,WAAW;CACf,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CAEJ,MAAM,SAAS,IAAY,OAAiC,QAAQ,SAAS,IAAI,EAAE;CACnF,MAAM,YAAY,OAChB,KAAK,KAAK,OAAQ,QAAQ,OAAO,CAAC,CAAC,CAAC,MAAM,KAAK,MAAO,EAAE;CAE1D,MAAM,aAAa,SAAgC;EACjD,IAAI,W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ACd,KAAK,YAAY;EACjB,KAAK,UAAU;EACf,KAAK,gBAAgB,KAAK,MAAM;CAElC;CAEA,OAAO;EACL,cAAc;EACd,WAAW,aAAa;GACtB,gBAAgB,IAAI,QAAQ;GAC5B,aAAa;IACX,gBAAgB,OAAO,QAAQ;GACjC;EACF;EACA;EACA,kBAAkB,QAAQ;EAC1B,OAAO,SAAS;GACd,QAAQ,KAAK,IAAI;EACnB;EACA,oBAAoB;EACpB,aAAa;GACX,eAAe;GACf,kBAAkB;GAClB,kBAAkB,KAAA;GAClB,QAAQ,cAAc;GACtB,QAAQ,MAAM;GACd,SAAS,KAAA;GACT,UAAU,QAAQ;EACpB;CACF;AACF"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// src/timer.ts
|
|
2
|
+
/**
|
|
3
|
+
* Runs `task` every `ms` on the one-shot `setTimer`. The next run is armed only once the previous
|
|
4
|
+
* one settles, so runs never overlap; a failed run goes to `onError` and the loop goes on. The
|
|
5
|
+
* returned function stops the loop: a run already in flight finishes, but nothing runs after it.
|
|
6
|
+
*/
|
|
7
|
+
function repeat(setTimer, ms, task, onError) {
|
|
8
|
+
let stopped = false;
|
|
9
|
+
const arm = () => setTimer(ms, async () => {
|
|
10
|
+
try {
|
|
11
|
+
await task();
|
|
12
|
+
} catch (error) {
|
|
13
|
+
onError(error);
|
|
14
|
+
}
|
|
15
|
+
if (!stopped) cancel = arm();
|
|
16
|
+
});
|
|
17
|
+
let cancel = arm();
|
|
18
|
+
return () => {
|
|
19
|
+
stopped = true;
|
|
20
|
+
cancel();
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* An `AbortSignal` that fires after `ms` on the injected timer — the platform timeout signal is not
|
|
25
|
+
* available in every runtime this package runs in. Call `cancel` once the work is done, or `abort`
|
|
26
|
+
* to stop it early.
|
|
27
|
+
*/
|
|
28
|
+
function timeoutSignal(ms, setTimer) {
|
|
29
|
+
const controller = new AbortController();
|
|
30
|
+
const cancel = setTimer(ms, () => {
|
|
31
|
+
controller.abort();
|
|
32
|
+
});
|
|
33
|
+
return {
|
|
34
|
+
signal: controller.signal,
|
|
35
|
+
cancel,
|
|
36
|
+
abort: () => {
|
|
37
|
+
controller.abort();
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
export { timeoutSignal as n, repeat as t };
|
|
42
|
+
|
|
43
|
+
//# sourceMappingURL=timer-Cdk5rGM2.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"timer-Cdk5rGM2.mjs","names":[],"sources":["../src/timer.ts"],"sourcesContent":["/**\n * A one-shot timer, `setTimeout` semantics: `fn` runs at most once, `ms` after the call, unless the\n * returned function cancels it first. Every host passes exactly this; loops re-arm through\n * {@link repeat}.\n */\nexport type SetTimer = (ms: number, fn: () => unknown) => () => void;\n\n/**\n * Runs `task` every `ms` on the one-shot `setTimer`. The next run is armed only once the previous\n * one settles, so runs never overlap; a failed run goes to `onError` and the loop goes on. The\n * returned function stops the loop: a run already in flight finishes, but nothing runs after it.\n */\nexport function repeat(\n setTimer: SetTimer,\n ms: number,\n task: () => unknown,\n onError: (error: unknown) => void,\n): () => void {\n let stopped = false;\n const arm = (): (() => void) =>\n setTimer(ms, async () => {\n try {\n await task();\n } catch (error) {\n onError(error);\n }\n if (!stopped) {\n cancel = arm();\n }\n });\n let cancel = arm();\n return () => {\n stopped = true;\n cancel();\n };\n}\n\n/**\n * An `AbortSignal` that fires after `ms` on the injected timer — the platform timeout signal is not\n * available in every runtime this package runs in. Call `cancel` once the work is done, or `abort`\n * to stop it early.\n */\nexport function timeoutSignal(\n ms: number,\n setTimer: SetTimer,\n): { readonly signal: AbortSignal; readonly cancel: () => void; readonly abort: () => void } {\n const controller = new AbortController();\n const cancel = setTimer(ms, () => {\n controller.abort();\n });\n return {\n signal: controller.signal,\n cancel,\n abort: () => {\n controller.abort();\n },\n };\n}\n"],"mappings":";;;;;;AAYA,SAAgB,OACd,UACA,IACA,MACA,SACY;CACZ,IAAI,UAAU;CACd,MAAM,YACJ,SAAS,IAAI,YAAY;EACvB,IAAI;GACF,MAAM,KAAK;EACb,SAAS,OAAO;GACd,QAAQ,KAAK;EACf;EACA,IAAI,CAAC,SACH,SAAS,IAAI;CAEjB,CAAC;CACH,IAAI,SAAS,IAAI;CACjB,aAAa;EACX,UAAU;EACV,OAAO;CACT;AACF;;;;;;AAOA,SAAgB,cACd,IACA,UAC2F;CAC3F,MAAM,aAAa,IAAI,gBAAgB;CACvC,MAAM,SAAS,SAAS,UAAU;EAChC,WAAW,MAAM;CACnB,CAAC;CACD,OAAO;EACL,QAAQ,WAAW;EACnB;EACA,aAAa;GACX,WAAW,MAAM;EACnB;CACF;AACF"}
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { In as SetTimer, Rn as EngineLogger, _ as RequestController, p as PendingRequest, vn as NetworkController, y as RequestInput } from "./controller-DpNVHVsj.mjs";
|
|
2
|
+
import { oa as AppAvailability, sa as EligibilityResponse } from "./index-vBgfOFIh.mjs";
|
|
3
|
+
import { VerifyFactor, Wallet } from "@qntx/wallet";
|
|
4
|
+
import { ChainsApi } from "@qntx/wallet/chains";
|
|
5
|
+
/** The WebSocket property-handler subset every runtime provides (browser, RN, Node ≥ 22). */
|
|
6
|
+
type AppSocket = {
|
|
7
|
+
readonly readyState: number;
|
|
8
|
+
readonly send: (data: string) => void;
|
|
9
|
+
readonly close: () => void;
|
|
10
|
+
onopen: (() => void) | null;
|
|
11
|
+
onmessage: ((event: {
|
|
12
|
+
readonly data: unknown;
|
|
13
|
+
}) => void) | null;
|
|
14
|
+
onclose: (() => void) | null;
|
|
15
|
+
onerror: (() => void) | null;
|
|
16
|
+
};
|
|
17
|
+
/** Connection lifecycle the live layers watch. */
|
|
18
|
+
type AppSocketStatus = "connecting" | "open" | "closed";
|
|
19
|
+
/**
|
|
20
|
+
* The request pipeline stamped to one app's origin: `prepare` opens a request attributed `{ kind:
|
|
21
|
+
* "app", id }` — a provider cannot choose its origin or carry a dApp one.
|
|
22
|
+
*/
|
|
23
|
+
type AppRequests = {
|
|
24
|
+
readonly prepare: (input: RequestInput) => Promise<PendingRequest>;
|
|
25
|
+
readonly outcome: RequestController["outcome"];
|
|
26
|
+
readonly reject: RequestController["reject"];
|
|
27
|
+
};
|
|
28
|
+
/** An app id — `^[a-z][a-z0-9-]{1,31}$`, validated by `createApps` at registration. */
|
|
29
|
+
type AppId = string;
|
|
30
|
+
type AppError = {
|
|
31
|
+
/** The category the app reports for the failed step — its error type's, or a plain reason. */
|
|
32
|
+
readonly category: string;
|
|
33
|
+
readonly message: string;
|
|
34
|
+
};
|
|
35
|
+
type AppStatus = "disabled" | "enabling" | "enabled" | "needs-reauthorization" |
|
|
36
|
+
/**
|
|
37
|
+
* The venue account must be migrated outside the wallet before it can be enabled — read-only
|
|
38
|
+
* until then.
|
|
39
|
+
*/
|
|
40
|
+
"needs-migration" | "unavailable";
|
|
41
|
+
/** The fields the controller owns in every app's group state. */
|
|
42
|
+
type AppGroupBase = {
|
|
43
|
+
/**
|
|
44
|
+
* `unavailable` is the eligibility overlay on `disabled`: the gateway says the app is blocked in
|
|
45
|
+
* the caller's jurisdiction. `enabled`/`enabling` groups keep their status so the user can still
|
|
46
|
+
* disable/cancel — the overlay never hides an existing position.
|
|
47
|
+
*/
|
|
48
|
+
readonly status: AppStatus;
|
|
49
|
+
/** `acknowledgeTerms` persists this across lock/unlock. */
|
|
50
|
+
readonly termsAcknowledged: boolean;
|
|
51
|
+
/** The pending approval request, when a step opened one. */
|
|
52
|
+
readonly requestId?: string;
|
|
53
|
+
/** The last failure — keeps `enabling`/`disabled` resumable. */
|
|
54
|
+
readonly error?: AppError;
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* An app's own group-state fields: any shape that does not redefine a controller field. The index
|
|
58
|
+
* signature is what makes the constraint satisfiable — without it the never-keys alone are a weak
|
|
59
|
+
* type and every legal detail shape ("no properties in common") is refused outright.
|
|
60
|
+
*/
|
|
61
|
+
type AppDetail = { readonly [K in keyof AppGroupBase]?: never; } & Readonly<Record<string, unknown>>;
|
|
62
|
+
/** One wallet group's per-app state — every flow step writes this, so a lock can resume. */
|
|
63
|
+
type AppGroupState<D extends AppDetail = Record<never, never>> = AppGroupBase & Partial<D>;
|
|
64
|
+
/** The gateway's per-app availability for this jurisdiction — `unknown`/`error` refuse enables. */
|
|
65
|
+
type AppsEligibility = {
|
|
66
|
+
readonly status: "unknown" | "ready" | "error";
|
|
67
|
+
readonly apps?: Readonly<Record<string, AppAvailability>>;
|
|
68
|
+
readonly country?: EligibilityResponse["country"];
|
|
69
|
+
readonly region?: EligibilityResponse["region"];
|
|
70
|
+
readonly checkedAt?: number;
|
|
71
|
+
};
|
|
72
|
+
/** `Partial` whose members may be written `undefined` — the clear-a-field form a patch needs. */
|
|
73
|
+
type Clearable<T> = { readonly [K in keyof T]?: T[K] | undefined; };
|
|
74
|
+
/**
|
|
75
|
+
* A state merge for `AppFlow.write` — `undefined` clears a field (exactOptionalPropertyTypes would
|
|
76
|
+
* otherwise refuse it). The terms flag is the controller's alone: `acknowledgeTerms` sets it, a
|
|
77
|
+
* provider patch cannot. Mapped over `keyof AppGroupBase | keyof D` (the same key set
|
|
78
|
+
* `Exclude<keyof AppGroupState<D>, "termsAcknowledged">` yields — computed this way so the detail
|
|
79
|
+
* keys stay literal through the generic).
|
|
80
|
+
*/
|
|
81
|
+
type AppGroupPatch<D extends AppDetail = Record<never, never>> = Omit<Clearable<AppGroupBase>, "termsAcknowledged"> & Clearable<D>;
|
|
82
|
+
/**
|
|
83
|
+
* The handle an enablement flow gets: `write` merges a patch into the group's app state unless the
|
|
84
|
+
* flow went stale (a lock or a newer call bumped the generation), and `stale` tells the flow to
|
|
85
|
+
* stop touching state and abort.
|
|
86
|
+
*/
|
|
87
|
+
type AppFlow<D extends AppDetail = Record<never, never>> = {
|
|
88
|
+
readonly current: () => AppGroupState<D>;
|
|
89
|
+
readonly write: (patch: AppGroupPatch<D>) => void;
|
|
90
|
+
readonly stale: () => boolean;
|
|
91
|
+
};
|
|
92
|
+
/** A wallet group — `walletId` plus `groupIndex`. */
|
|
93
|
+
type AppGroup = {
|
|
94
|
+
readonly walletId: string;
|
|
95
|
+
readonly groupIndex: number;
|
|
96
|
+
};
|
|
97
|
+
/**
|
|
98
|
+
* A standing authority an app's venue holds over the group's funds, outside the kernel's session
|
|
99
|
+
* keys — display-only: nothing that builds or signs reads it.
|
|
100
|
+
*/
|
|
101
|
+
type AppAuthority = {
|
|
102
|
+
readonly kind: "builder-fee" | "token-allowance" | "operator";
|
|
103
|
+
/**
|
|
104
|
+
* Where the authority lives: a CAIP-2 network for an on-chain authority, or, for a venue's own
|
|
105
|
+
* ledger, the venue network name its kernel sessions use as `scope`.
|
|
106
|
+
*/
|
|
107
|
+
readonly network: string;
|
|
108
|
+
/** The account it acts on: the owner, or a venue account (a deposit wallet). */
|
|
109
|
+
readonly account: string;
|
|
110
|
+
/** Who holds it: the builder, the spender, the operator. */
|
|
111
|
+
readonly holder: string;
|
|
112
|
+
/** Token or contract covered (allowance / operator kinds). */
|
|
113
|
+
readonly asset?: string;
|
|
114
|
+
/**
|
|
115
|
+
* Upper bound as a decimal integer string in the asset's (or venue fee's) base unit; absent =
|
|
116
|
+
* unlimited.
|
|
117
|
+
*/
|
|
118
|
+
readonly limit?: string;
|
|
119
|
+
/**
|
|
120
|
+
* How the user removes it: `disable` = the app's `disable({ revoke: true })` removes it;
|
|
121
|
+
* `approvals` = an owner-held on-chain allowance the approvals inventory revokes; `none` = not
|
|
122
|
+
* removable from this wallet.
|
|
123
|
+
*/
|
|
124
|
+
readonly revoke: "disable" | "approvals" | "none";
|
|
125
|
+
};
|
|
126
|
+
/** What the controller asks a per-app provider for. */
|
|
127
|
+
type AppProvider<D extends AppDetail = Record<never, never>> = {
|
|
128
|
+
/**
|
|
129
|
+
* The app's own error type for the controller's generic failures: `busy` and `unlock-required`
|
|
130
|
+
* keep their category; `unavailable` is the jurisdiction gate (the app may report it under its
|
|
131
|
+
* own category); `invalid-input` refuses a flow the group's state does not allow.
|
|
132
|
+
*/
|
|
133
|
+
readonly error: (category: "busy" | "unlock-required" | "unavailable" | "invalid-input", message: string) => Error;
|
|
134
|
+
/** The groups that carry kernel-side app state. */
|
|
135
|
+
readonly groups: () => Promise<ReadonlyArray<AppGroup>>;
|
|
136
|
+
/** Re-derive the group's app state from kernel state and the app's own reads. */
|
|
137
|
+
readonly reconcile: (group: AppGroup, flow: AppFlow<D>) => Promise<void>;
|
|
138
|
+
/**
|
|
139
|
+
* Run or resume the enable flow to `enabled`, or leave a resumable `enabling`/error state.
|
|
140
|
+
* `input` is the app's enable input the host passed to `AppsController.enable` — each app
|
|
141
|
+
* validates it strictly (a session-scheme app takes the session limits and a verify factor).
|
|
142
|
+
*/
|
|
143
|
+
readonly enable: (group: AppGroup, flow: AppFlow<D>, input: unknown) => Promise<void>;
|
|
144
|
+
/** Enable a fresh credential/agent, then drop the old one — the old stays usable until then. */
|
|
145
|
+
readonly renew: (group: AppGroup, flow: AppFlow<D>, input: unknown) => Promise<void>;
|
|
146
|
+
/**
|
|
147
|
+
* Stop trading (the app's credentials deleted first); `revoke` also asks the app to invalidate
|
|
148
|
+
* them server-side. An app whose revoke ceremony creates a kernel credential reads `verify` — the
|
|
149
|
+
* same factor `enable` takes.
|
|
150
|
+
*/
|
|
151
|
+
readonly disable: (group: AppGroup, options: {
|
|
152
|
+
readonly revoke: boolean;
|
|
153
|
+
readonly verify?: VerifyFactor;
|
|
154
|
+
}, flow: AppFlow<D>) => Promise<void>;
|
|
155
|
+
/** Abandon an in-flight flow: reject its request, clean orphans, back to `disabled`. */
|
|
156
|
+
readonly cancel: (group: AppGroup, flow: AppFlow<D>) => Promise<void>;
|
|
157
|
+
/**
|
|
158
|
+
* The venue-held authorities the group has granted, read live from the app — display-only. An app
|
|
159
|
+
* without the member reports none.
|
|
160
|
+
*/
|
|
161
|
+
readonly authorities?: (group: AppGroup) => Promise<ReadonlyArray<AppAuthority>>;
|
|
162
|
+
};
|
|
163
|
+
/** The chain clients an app's deposit path reads allowance/burn limits through. */
|
|
164
|
+
type AppNetworks = Pick<NetworkController, "client" | "independentClient">;
|
|
165
|
+
/**
|
|
166
|
+
* What `createApps` hands every app definition's `create` — the host-injected I/O plus lazy reads
|
|
167
|
+
* of the controller's state. The controller only exists after every `create` ran, so the state
|
|
168
|
+
* accessors are thunks: providers read them per call, never at construction.
|
|
169
|
+
*/
|
|
170
|
+
type AppContext<D extends AppDetail = Record<never, never>> = {
|
|
171
|
+
readonly wallet: Wallet;
|
|
172
|
+
/**
|
|
173
|
+
* The one account seam — the engine's `signers.apis.account`: a vault group derives in the
|
|
174
|
+
* kernel, a card or hardware group reads its pinned material. An app never calls `chains`.
|
|
175
|
+
*/
|
|
176
|
+
readonly account: ChainsApi["account"];
|
|
177
|
+
/** The request pipeline stamped `{ kind: "app", id }` with the definition's own id. */
|
|
178
|
+
readonly requests: AppRequests;
|
|
179
|
+
/** The chain clients an app's deposit path reads allowance/burn limits through. */
|
|
180
|
+
readonly networks: AppNetworks;
|
|
181
|
+
readonly fetch: typeof globalThis.fetch;
|
|
182
|
+
readonly now: () => number;
|
|
183
|
+
readonly setTimer: SetTimer;
|
|
184
|
+
readonly random: (length: number) => Uint8Array;
|
|
185
|
+
readonly logger: EngineLogger;
|
|
186
|
+
readonly socket: (url: string) => AppSocket;
|
|
187
|
+
/**
|
|
188
|
+
* This app's availability under the last ready eligibility answer — `undefined` while unknown,
|
|
189
|
+
* failed, or absent from the answer.
|
|
190
|
+
*/
|
|
191
|
+
readonly availability: () => AppAvailability | undefined;
|
|
192
|
+
/**
|
|
193
|
+
* This app's state for `group` — `undefined` while locked or before any flow or reconcile wrote
|
|
194
|
+
* it.
|
|
195
|
+
*/
|
|
196
|
+
readonly groupState: (group: AppGroup) => AppGroupState<D> | undefined;
|
|
197
|
+
/**
|
|
198
|
+
* Runs `run` as a flow of this app on `group` under the controller's guards: refused with the
|
|
199
|
+
* app's `unlock-required` while locked and `busy` while another flow of this app runs on the
|
|
200
|
+
* group; its writes drop once a lock or a newer flow supersedes it.
|
|
201
|
+
*/
|
|
202
|
+
readonly flow: (group: AppGroup, run: (flow: AppFlow<D>) => Promise<void>) => Promise<void>;
|
|
203
|
+
/** The app's own records in the apps store (collection `apps.<id>`) — unlocked sessions only. */
|
|
204
|
+
readonly storage: AppStorage;
|
|
205
|
+
};
|
|
206
|
+
/**
|
|
207
|
+
* The app's per-group records in the session EngineStore — keys `${walletId}/${groupIndex}/${name}`
|
|
208
|
+
* inside collection `apps.<id>`. Every method throws `EngineStoreError("closed")` while no session
|
|
209
|
+
* store is open (the controller closes it on lock).
|
|
210
|
+
*/
|
|
211
|
+
type AppStorage = {
|
|
212
|
+
readonly get: (group: AppGroup, name: string) => Promise<Uint8Array | undefined>;
|
|
213
|
+
readonly put: (group: AppGroup, name: string, bytes: Uint8Array) => Promise<void>;
|
|
214
|
+
readonly delete: (group: AppGroup, name: string) => Promise<void>;
|
|
215
|
+
/** The group's own record names — the `name` part of every key it owns. */
|
|
216
|
+
readonly list: (group: AppGroup) => Promise<ReadonlyArray<string>>;
|
|
217
|
+
/** The groups with at least one record — deduplicated. */
|
|
218
|
+
readonly groups: () => Promise<ReadonlyArray<AppGroup>>;
|
|
219
|
+
};
|
|
220
|
+
/** What an app definition's `create` hands back: the public api, the provider, lifecycle hooks. */
|
|
221
|
+
type AppInstance<Api, D extends AppDetail = Record<never, never>> = {
|
|
222
|
+
/** The app surface `createApps` returns under the definition's id. */
|
|
223
|
+
readonly api: Api;
|
|
224
|
+
/** The enablement state machine the controller drives. */
|
|
225
|
+
readonly provider: AppProvider<D>;
|
|
226
|
+
/** Runs on every unlock before `controller.init` — a provider refreshes its session state. */
|
|
227
|
+
readonly unlock?: () => Promise<void>;
|
|
228
|
+
/** Runs on every lock before `controller.lock` — a provider resets its session marks. */
|
|
229
|
+
readonly lock?: () => void;
|
|
230
|
+
/** Runs on destroy before `controller.lock` — a provider closes its shared resources. */
|
|
231
|
+
readonly close?: () => void;
|
|
232
|
+
};
|
|
233
|
+
/**
|
|
234
|
+
* One app, declared: `createApps` calls `create` with the shared context and registers the instance
|
|
235
|
+
* under `id` — a duplicate `id` throws.
|
|
236
|
+
*/
|
|
237
|
+
type AppDefinition<Id extends AppId, Api, D extends AppDetail = Record<never, never>> = {
|
|
238
|
+
readonly id: Id;
|
|
239
|
+
/**
|
|
240
|
+
* The eligibility answers under which `enable`/`renew` may start; anything else — `unknown`,
|
|
241
|
+
* `error`, the app absent from a ready answer, or `blocked` — refuses.
|
|
242
|
+
*/
|
|
243
|
+
readonly enableWhen: ReadonlyArray<Exclude<AppAvailability, "blocked">>;
|
|
244
|
+
readonly create: (context: AppContext<D>) => AppInstance<Api, D>;
|
|
245
|
+
};
|
|
246
|
+
/** The per-app api surface `createApps` returns next to the controller — keyed by app id. */
|
|
247
|
+
type AppApis<A extends ReadonlyArray<AppDefinition<AppId, unknown>>> = { readonly [D in A[number] as D["id"]]: D extends AppDefinition<AppId, infer Api> ? Api : never; };
|
|
248
|
+
/** Every registered app's group state keyed by id — the loosest shape a groups map may hold. */
|
|
249
|
+
type AppGroups = Readonly<Record<AppId, AppGroupState>>;
|
|
250
|
+
type AppsState<G extends AppGroups = AppGroups> = {
|
|
251
|
+
readonly locked: boolean;
|
|
252
|
+
readonly groups: Readonly<Record<string, Readonly<Partial<G>>>>;
|
|
253
|
+
readonly eligibility: AppsEligibility;
|
|
254
|
+
};
|
|
255
|
+
/** Each listed definition's group state, keyed by its id. */
|
|
256
|
+
type AppStates<A extends ReadonlyArray<AppDefinition<AppId, unknown>>> = { readonly [D in A[number] as D["id"]]: D extends AppDefinition<AppId, unknown, infer S> ? AppGroupState<S> : never; };
|
|
257
|
+
export { AppSocket as C, AppsState as S, AppRequests as _, AppDetail as a, AppStorage as b, AppGroup as c, AppGroupState as d, AppGroups as f, AppProvider as g, AppNetworks as h, AppDefinition as i, AppGroupBase as l, AppInstance as m, AppAuthority as n, AppError as o, AppId as p, AppContext as r, AppFlow as s, AppApis as t, AppGroupPatch as u, AppStates as v, AppSocketStatus as w, AppsEligibility as x, AppStatus as y };
|
|
258
|
+
//# sourceMappingURL=types-BpvioFGo.d.mts.map
|