@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,1378 @@
1
+ import { t as EngineStoreError } from "./errors-horUy5k1.mjs";
2
+ import { i as RequestEndedError, n as NonceConflictError } from "./types-DbftVZ3I.mjs";
3
+ import { bytesToHex, createClient, custom, isAddressEqual, isHash } from "viem";
4
+ import { fiat24SessionMessage } from "@qntx/wallet-chains/evm";
5
+ import { WalletError } from "@qntx/wallet";
6
+ import { createFiat24Api, sessionLabel, sessionMessage } from "@qntx/fiat24/api";
7
+ import { advanceCard, advanceExchange, advanceOnboarding, advancePayout, advanceTopUp, advanceTransfer, decodeFlowState, encodeFlowState, kycUrl, loadAccount, loadPayoutSettlement, startCardOperation, startCardSetup, startExchange, startOnboarding, startPayout, startTopUp, startTransfer } from "@qntx/fiat24/flows";
8
+ import { CURRENCIES, Fiat24Error, isFiat24Error } from "@qntx/fiat24/core";
9
+ import { getAllowances } from "@qntx/fiat24/chain";
10
+ import { arbitrum } from "@qntx/fiat24/deployments";
11
+ import { arbitrum as arbitrum$1 } from "viem/chains";
12
+ // src/apps/fiat24/errors.ts
13
+ /**
14
+ * The Fiat24 provider error. `category` is the closed union the host branches on; `code` is the
15
+ * SDK's own closed `Fiat24ErrorCode`, set only when the failure came out of `@qntx/fiat24`
16
+ * (`category: "protocol"`) — the SDK's messages are fixed English templates, so they pass through
17
+ * verbatim. No `cause` is ever attached: nothing an SDK error was built from — requests, results,
18
+ * grants or signatures — may ride along.
19
+ */
20
+ var Fiat24AppError = class extends Error {
21
+ category;
22
+ /** The SDK's closed error code — set on `protocol` only. */
23
+ code;
24
+ constructor(category, message, options) {
25
+ super(message);
26
+ this.name = "Fiat24AppError";
27
+ this.category = category;
28
+ if (options?.code !== void 0) this.code = options.code;
29
+ }
30
+ };
31
+ /**
32
+ * One funnel for every failure out of the provider: `Fiat24AppError` passes through, an SDK
33
+ * `Fiat24Error` becomes `protocol` with its code and fixed message, and anything else — a viem or
34
+ * transport error whose message may embed URLs, params or results — collapses to a fixed
35
+ * `unavailable`.
36
+ */
37
+ const fromSdk = (error) => {
38
+ if (error instanceof Fiat24AppError) return error;
39
+ if (isFiat24Error(error)) return new Fiat24AppError("protocol", error.message, { code: error.code });
40
+ return new Fiat24AppError("unavailable", "the fiat24 chain read failed");
41
+ };
42
+ // src/apps/fiat24/account.ts
43
+ /**
44
+ * The group's Fiat24 account read: `loadAccount` over the cross-checked client — `deployment` is
45
+ * never passed, so the SDK's pinned-deployment verification stays on (`verifiedBlock` asserts the
46
+ * EIP-1967 slots of every contract the reads touch). A `contract-changed` drift is a state, not an
47
+ * error: writes must fail closed while the deployment disagrees with the pin. Every other SDK
48
+ * failure maps through `fromSdk` — fixed messages, no `cause`, the closed `code` carried.
49
+ */
50
+ function createFiat24Account(options) {
51
+ return async (group) => {
52
+ let owner;
53
+ try {
54
+ owner = await options.owner(group);
55
+ } catch (error) {
56
+ throw fromSdk(error);
57
+ }
58
+ let view;
59
+ try {
60
+ view = await loadAccount({ client: options.client }, { owner });
61
+ } catch (error) {
62
+ if (isFiat24Error(error) && error.code === "contract-changed") return {
63
+ status: "contract-changed",
64
+ owner
65
+ };
66
+ throw fromSdk(error);
67
+ }
68
+ return view.step === "no-account" ? {
69
+ status: "no-account",
70
+ owner
71
+ } : {
72
+ status: view.step,
73
+ owner,
74
+ view
75
+ };
76
+ };
77
+ }
78
+ // src/apps/fiat24/enable.ts
79
+ /** The group's enablement record — presence IS the fact; the payload is deliberately empty. */
80
+ const RECORD = "enabled";
81
+ /** `getAllowances`' deposit-side keys in order. */
82
+ const DEPOSIT_ASSETS = [...CURRENCIES, "USDC"];
83
+ const ENABLED_BYTES = new TextEncoder().encode("{}");
84
+ const errorOf = (error) => error instanceof Fiat24AppError ? {
85
+ category: error.category,
86
+ message: error.message
87
+ } : {
88
+ category: "unavailable",
89
+ message: "the fiat24 enablement write failed"
90
+ };
91
+ /** Run `body`; a stale flow stops writing but a thrown error still surfaces to the caller. */
92
+ const guard = async (flow, body) => {
93
+ try {
94
+ await body();
95
+ } catch (error) {
96
+ if (!flow.stale()) flow.write({
97
+ error: errorOf(error),
98
+ requestId: void 0
99
+ });
100
+ throw error;
101
+ }
102
+ };
103
+ function createFiat24Enable(options) {
104
+ const enabled = async (group) => await options.storage.get(group, RECORD) !== void 0;
105
+ const enable = async (group, flow) => {
106
+ if (flow.current().status !== "enabling") flow.write({
107
+ status: "enabling",
108
+ error: void 0
109
+ });
110
+ if (!flow.current().termsAcknowledged) throw new Fiat24AppError("invalid-input", "Fiat24 terms have not been acknowledged");
111
+ await options.storage.put(group, RECORD, ENABLED_BYTES);
112
+ flow.write({
113
+ status: "enabled",
114
+ error: void 0
115
+ });
116
+ };
117
+ return {
118
+ error: (category, message) => new Fiat24AppError(category, message),
119
+ groups: options.storage.groups,
120
+ reconcile: async (group, flow) => {
121
+ let hasRecord;
122
+ try {
123
+ hasRecord = await enabled(group);
124
+ } catch (error) {
125
+ if (error instanceof EngineStoreError && error.code === "closed") return;
126
+ throw error;
127
+ }
128
+ flow.write({
129
+ status: hasRecord ? "enabled" : "disabled",
130
+ error: void 0
131
+ });
132
+ if (hasRecord) options.onEnabled(group);
133
+ },
134
+ enable: async (group, flow) => guard(flow, async () => enable(group, flow)),
135
+ renew: async (group, flow) => guard(flow, async () => enable(group, flow)),
136
+ disable: async (group, _options, flow) => guard(flow, async () => {
137
+ await options.storage.delete(group, RECORD);
138
+ options.onDisable(group);
139
+ flow.write({
140
+ status: "disabled",
141
+ error: void 0
142
+ });
143
+ }),
144
+ cancel: async (_group, flow) => {
145
+ flow.write({
146
+ status: "disabled",
147
+ error: void 0
148
+ });
149
+ await Promise.resolve();
150
+ },
151
+ authorities: async (group) => {
152
+ const state = await options.account(group);
153
+ if (state.status === "no-account") return [];
154
+ const allowances = await getAllowances(options.client, { owner: state.owner }).catch((error) => {
155
+ throw fromSdk(error);
156
+ });
157
+ const UINT256_MAX = 2n ** 256n - 1n;
158
+ const rows = [];
159
+ const row = (holder, asset, amount) => {
160
+ if (amount <= 0n) return;
161
+ rows.push({
162
+ kind: "token-allowance",
163
+ network: "eip155:42161",
164
+ account: state.owner,
165
+ holder,
166
+ asset,
167
+ ...amount === UINT256_MAX ? {} : { limit: amount.toString() },
168
+ revoke: "approvals"
169
+ });
170
+ };
171
+ for (const currency of CURRENCIES) row(arbitrum.card.proxy, arbitrum.tokens[currency].proxy, allowances.card[currency]);
172
+ for (const asset of DEPOSIT_ASSETS) row(arbitrum.deposit.proxy, asset === "USDC" ? arbitrum.usdc : arbitrum.tokens[asset].proxy, allowances.deposit[asset]);
173
+ row(arbitrum.account.proxy, arbitrum.f24.address, allowances.account.F24);
174
+ return rows;
175
+ }
176
+ };
177
+ }
178
+ // src/apps/fiat24/flows.ts
179
+ /**
180
+ * The Fiat24 resumable flows over the app's SPI: state starts through the SDK, persists as
181
+ * `flow/<id>` (`encodeFlowState` text — untrusted on the way back in, re-decoded per advance), and
182
+ * advances one-at-a-time per group through the layer-1 client and the request-pipeline signer.
183
+ * Payout drafts hold payee PII so they stay in a memory-only map until the first `advancePayout`
184
+ * verifies them into a persisted `verified` state. Sessions and the public api are optional
185
+ * `FlowDeps` — the SDK refuses with its own codes when a flow needs one the host never wired.
186
+ * Reconcile never sends: it enqueues advances only for records whose last phase is
187
+ * `sending`/`submitted`/`unknown`, the three phases where the SDK's `advanceTx` polls and never
188
+ * reaches `readyPhase` (flows/tx.ts gates the signer behind `phase === "ready"` or no record).
189
+ */
190
+ /**
191
+ * The record name the enable provider writes — a flow reads it to gate reconcile before
192
+ * `groupState` is derived (the unlock hook runs before `init`).
193
+ */
194
+ const ENABLED = "enabled";
195
+ const FLOW_PREFIX = "flow/";
196
+ /** The reconcile cadence — the same 15 s the account live view polls at. */
197
+ const FIAT24_RECONCILE_MS = 15e3;
198
+ /** Reconcile-only phases — `advanceTx` in these polls receipts/nonces and can never sign. */
199
+ const UNRESOLVED = /* @__PURE__ */ new Set([
200
+ "sending",
201
+ "submitted",
202
+ "unknown"
203
+ ]);
204
+ /**
205
+ * Whether the state's next move must reach api.fiat24.com — read off the SDK's own dispatch: a
206
+ * payout `draft` with a `bank`/`swiss-qr` target (`verifyTarget` → `checkedSession`,
207
+ * flows/payout.ts:313 — contact targets skip the session); a card `ready` with no chain leg
208
+ * (`advanceApiWrite` → `checkedSession`, flows/card.ts:438,256) or a `tx`/`confirmed` whose last
209
+ * record is a `main` write; onboarding `tourist`/`kyc` (`api.kycStatus`, flows/onboarding.ts:313).
210
+ * The one reach it cannot see statically — a card `ready` with a chain leg (cap or set-cap), where
211
+ * the write follows only when the allowance already matches — throws `session-required` in the SDK
212
+ * and the advance catch maps it to the same `api-unavailable`.
213
+ */
214
+ const needsApi = (state) => {
215
+ switch (state.flow) {
216
+ case "payout": return state.step === "draft" && state.target.kind !== "contact";
217
+ case "card":
218
+ if (state.step === "tx" || state.step === "confirmed") return state.txs.at(-1)?.purpose === "main";
219
+ return state.step === "ready" && state.cap === void 0 && state.operation.kind !== "set-cap";
220
+ case "onboarding": return state.step === "tourist" || state.step === "kyc";
221
+ default: return false;
222
+ }
223
+ };
224
+ const groupKey$1 = (group) => `${group.walletId}/${group.groupIndex}`;
225
+ const text = new TextEncoder();
226
+ const read = new TextDecoder();
227
+ const lastPhase = (state) => state.txs.at(-1)?.phase;
228
+ function createFiat24Flows(options) {
229
+ const { storage, requests } = options;
230
+ /** Per-group serial advance queue — the SDK forbids concurrent advances of one group. */
231
+ const queue = /* @__PURE__ */ new Map();
232
+ /** Payout drafts by group — payee PII never touches storage. */
233
+ const drafts = /* @__PURE__ */ new Map();
234
+ /** Every group the flows module has touched — the wallet-removal sweep's candidates. */
235
+ const known = /* @__PURE__ */ new Map();
236
+ let visible = false;
237
+ let timer;
238
+ let polling = false;
239
+ const unlocked = () => options.wallet.getSnapshot().vault === "unlocked";
240
+ const requireUnlocked = () => {
241
+ if (!unlocked()) throw new Fiat24AppError("unlock-required", "unlock the vault to use the Fiat24 app");
242
+ };
243
+ const requireEnabled = (group) => {
244
+ requireUnlocked();
245
+ if (options.groupState(group)?.status !== "enabled") throw new Fiat24AppError("not-enabled", "enable the Fiat24 app for this group first");
246
+ };
247
+ const enabledRecord = async (group) => {
248
+ try {
249
+ return await storage.get(group, ENABLED) !== void 0;
250
+ } catch {
251
+ return false;
252
+ }
253
+ };
254
+ const draftsOf = (group) => {
255
+ const key = groupKey$1(group);
256
+ known.set(key, group);
257
+ let groupDrafts = drafts.get(key);
258
+ if (groupDrafts === void 0) {
259
+ groupDrafts = /* @__PURE__ */ new Map();
260
+ drafts.set(key, groupDrafts);
261
+ }
262
+ return groupDrafts;
263
+ };
264
+ const persisted = async (group) => {
265
+ known.set(groupKey$1(group), group);
266
+ const names = (await storage.list(group)).filter((name) => name.startsWith(FLOW_PREFIX));
267
+ const records = await Promise.all(names.map(async (name) => storage.get(group, name)));
268
+ const out = [];
269
+ for (const [index, bytes] of records.entries()) {
270
+ const id = (names[index] ?? "").slice(5);
271
+ if (bytes === void 0) continue;
272
+ try {
273
+ out.push({
274
+ id,
275
+ state: decodeFlowState(read.decode(bytes))
276
+ });
277
+ } catch {
278
+ out.push({
279
+ id,
280
+ invalid: true
281
+ });
282
+ }
283
+ }
284
+ return out;
285
+ };
286
+ /**
287
+ * A sending/unknown last record blocks a replacement start — the SDK never resends it. An
288
+ * undecodable record blocks too: it cannot be proven not to be sending, so it fails closed.
289
+ */
290
+ const requireResolved = async (group) => {
291
+ for (const record of await persisted(group)) if ("invalid" in record || lastPhase(record.state) === "sending" || lastPhase(record.state) === "unknown") throw new Fiat24AppError("flow-unresolved", "a Fiat24 transaction is still sending — reconcile it before starting another");
292
+ };
293
+ /** The group's owned live tokenId — payout and card flows cannot run without it. */
294
+ const tokenIdOf = async (group) => {
295
+ const account = await options.account(group);
296
+ if (account.status !== "live" || !account.view.account.ownsToken) throw new Fiat24AppError("no-account", "the group owns no live Fiat24 account");
297
+ return account.view.account.tokenId;
298
+ };
299
+ const requireAvailable = () => {
300
+ const availability = options.availability();
301
+ if (availability === "close-only") throw new Fiat24AppError("close-only", "Fiat24 is close-only in this jurisdiction");
302
+ if (availability !== "available") throw new Fiat24AppError("unavailable", "Fiat24 availability is unknown");
303
+ };
304
+ const persist = async (group, id, state) => {
305
+ await storage.put(group, `${FLOW_PREFIX}${id}`, text.encode(encodeFlowState(state)));
306
+ };
307
+ const persistFromSdk = async (group, id, state) => {
308
+ try {
309
+ await persist(group, id, state);
310
+ } catch (error) {
311
+ throw fromSdk(error);
312
+ }
313
+ };
314
+ const start = async (group, input) => {
315
+ requireEnabled(group);
316
+ const owner = await options.owner(group);
317
+ if (input.flow === "onboarding" || input.flow === "top-up") requireAvailable();
318
+ await requireResolved(group);
319
+ let state;
320
+ try {
321
+ switch (input.flow) {
322
+ case "transfer":
323
+ state = startTransfer({
324
+ owner,
325
+ currency: input.currency,
326
+ amount: input.amount,
327
+ to: input.to
328
+ });
329
+ break;
330
+ case "exchange":
331
+ state = startExchange({
332
+ owner,
333
+ side: input.side,
334
+ from: input.from,
335
+ to: input.to,
336
+ amount: input.amount
337
+ });
338
+ break;
339
+ case "payout":
340
+ state = startPayout({
341
+ owner,
342
+ tokenId: await tokenIdOf(group),
343
+ currency: input.currency,
344
+ amount: input.amount,
345
+ target: input.target
346
+ });
347
+ break;
348
+ case "top-up":
349
+ state = startTopUp({
350
+ owner,
351
+ output: input.output,
352
+ usdcAmount: input.usdcAmount
353
+ });
354
+ break;
355
+ case "onboarding":
356
+ state = startOnboarding({
357
+ owner,
358
+ tokenId: input.tokenId,
359
+ payment: input.payment
360
+ });
361
+ break;
362
+ case "card-setup":
363
+ state = startCardSetup({
364
+ owner,
365
+ tokenId: await tokenIdOf(group),
366
+ cap: input.cap
367
+ });
368
+ break;
369
+ case "card": state = startCardOperation({
370
+ owner,
371
+ tokenId: await tokenIdOf(group),
372
+ operation: input.operation
373
+ });
374
+ }
375
+ } catch (error) {
376
+ throw fromSdk(error);
377
+ }
378
+ const id = bytesToHex(options.random(8)).slice(2);
379
+ if (state.flow === "payout" && state.step === "draft") draftsOf(group).set(id, state);
380
+ else await persist(group, id, state);
381
+ return {
382
+ id,
383
+ state
384
+ };
385
+ };
386
+ /** The advance deps for one state — signer, persistence, and the optional session/api. */
387
+ const depsFor = async (group, id, state, capture) => {
388
+ const owner = await options.owner(group);
389
+ const tokenId = "tokenId" in state ? state.tokenId : void 0;
390
+ const signer = options.sessions.signer({
391
+ group,
392
+ owner,
393
+ ...tokenId === void 0 ? {} : { tokenId },
394
+ refused: (reason) => {
395
+ capture.refusal = reason;
396
+ }
397
+ });
398
+ const deps = {
399
+ client: options.client,
400
+ signer,
401
+ persist: async (next) => persistFromSdk(group, id, next)
402
+ };
403
+ if ((state.flow === "payout" || state.flow === "card") && tokenId !== void 0) {
404
+ const session = await options.sessions.sdk(group, tokenId);
405
+ if (session !== void 0) deps.session = session;
406
+ }
407
+ if (state.flow === "onboarding" && options.api !== void 0) deps.api = options.api;
408
+ return deps;
409
+ };
410
+ const advanceOnce = async (group, id) => {
411
+ const draft = draftsOf(group).get(id);
412
+ let state;
413
+ let persistedId = false;
414
+ if (draft === void 0) {
415
+ const bytes = await storage.get(group, `${FLOW_PREFIX}${id}`);
416
+ if (bytes === void 0) throw new Fiat24AppError("unknown-flow", "unknown Fiat24 flow");
417
+ try {
418
+ state = decodeFlowState(read.decode(bytes));
419
+ } catch (error) {
420
+ throw fromSdk(error);
421
+ }
422
+ persistedId = true;
423
+ } else state = draft;
424
+ if (options.api === void 0 && needsApi(state)) throw new Fiat24AppError("api-unavailable", "the fiat24 api is not configured");
425
+ const capture = {};
426
+ let next;
427
+ try {
428
+ const deps = await depsFor(group, id, state, capture);
429
+ switch (state.flow) {
430
+ case "transfer":
431
+ next = await advanceTransfer(deps, state);
432
+ break;
433
+ case "exchange":
434
+ next = await advanceExchange(deps, state);
435
+ break;
436
+ case "payout":
437
+ next = await advancePayout(deps, state);
438
+ break;
439
+ case "card":
440
+ next = await advanceCard(deps, state);
441
+ break;
442
+ case "onboarding":
443
+ next = await advanceOnboarding(deps, state);
444
+ break;
445
+ case "top-up": next = await advanceTopUp(deps, state);
446
+ }
447
+ } catch (error) {
448
+ if (isFiat24Error(error) && error.code === "session-required") throw new Fiat24AppError("api-unavailable", "the fiat24 api is not configured");
449
+ throw fromSdk(error);
450
+ }
451
+ if (!persistedId) draftsOf(group).delete(id);
452
+ return {
453
+ id,
454
+ state: next,
455
+ ...capture.refusal === void 0 ? {} : { refusal: capture.refusal }
456
+ };
457
+ };
458
+ /** Serialises the group's advances; `enabledBy` is the gate at run time, not enqueue time. */
459
+ const enqueue = async (group, run) => {
460
+ const key = groupKey$1(group);
461
+ const next = (queue.get(key) ?? Promise.resolve()).then(run, run);
462
+ queue.set(key, next.catch(() => void 0));
463
+ return next;
464
+ };
465
+ const advance = async (group, id) => enqueue(group, async () => {
466
+ requireEnabled(group);
467
+ return advanceOnce(group, id);
468
+ });
469
+ /** Reconcile advance — gated on the storage record, safe before `init` derives groupState. */
470
+ const reconcileAdvance = async (group, id) => enqueue(group, async () => {
471
+ requireUnlocked();
472
+ if (!await enabledRecord(group)) throw new Fiat24AppError("not-enabled", "enable the Fiat24 app for this group first");
473
+ return advanceOnce(group, id);
474
+ });
475
+ const discard = async (group, id) => {
476
+ requireEnabled(group);
477
+ if (draftsOf(group).get(id) !== void 0) {
478
+ draftsOf(group).delete(id);
479
+ return;
480
+ }
481
+ const bytes = await storage.get(group, `${FLOW_PREFIX}${id}`);
482
+ if (bytes === void 0) throw new Fiat24AppError("unknown-flow", "unknown Fiat24 flow");
483
+ let state;
484
+ try {
485
+ state = decodeFlowState(read.decode(bytes));
486
+ } catch {
487
+ await storage.delete(group, `${FLOW_PREFIX}${id}`);
488
+ return;
489
+ }
490
+ const phase = lastPhase(state);
491
+ if (phase !== void 0 && UNRESOLVED.has(phase)) throw new Fiat24AppError("flow-unresolved", "a Fiat24 transaction is still sending — reconcile it before discarding");
492
+ await storage.delete(group, `${FLOW_PREFIX}${id}`);
493
+ };
494
+ const payoutSettlement = async (group, id) => {
495
+ requireEnabled(group);
496
+ const bytes = await storage.get(group, `${FLOW_PREFIX}${id}`);
497
+ if (bytes === void 0) throw new Fiat24AppError("unknown-flow", "unknown Fiat24 flow");
498
+ let state;
499
+ try {
500
+ state = decodeFlowState(read.decode(bytes));
501
+ } catch (error) {
502
+ throw fromSdk(error);
503
+ }
504
+ if (state.flow !== "payout") throw new Fiat24AppError("invalid-input", "the flow is not a payout");
505
+ try {
506
+ return await loadPayoutSettlement({ client: options.client }, state);
507
+ } catch (error) {
508
+ throw fromSdk(error);
509
+ }
510
+ };
511
+ /** (group, id) pairs with a reconcile advance already queued or running — never enqueued twice. */
512
+ const inflight = /* @__PURE__ */ new Set();
513
+ /**
514
+ * One reconcile pass over the group's persisted flows — never sends. Driven by the provider's
515
+ * `reconcile` (which runs per group once the store is open at init) and by the 15 s poll.
516
+ */
517
+ const reconcileGroup = async (group) => {
518
+ if (!unlocked()) return;
519
+ try {
520
+ if (!await enabledRecord(group)) return;
521
+ } catch {
522
+ return;
523
+ }
524
+ let records;
525
+ try {
526
+ records = await persisted(group);
527
+ } catch (error) {
528
+ warn(group, error);
529
+ return;
530
+ }
531
+ for (const record of records) {
532
+ if ("invalid" in record) {
533
+ options.logger.warn("fiat24 reconcile skipped an undecodable flow", {
534
+ category: "protocol",
535
+ code: "invalid-state"
536
+ });
537
+ continue;
538
+ }
539
+ const phase = lastPhase(record.state);
540
+ if (phase === void 0 || !UNRESOLVED.has(phase)) continue;
541
+ const inflightKey = `${groupKey$1(group)}:${record.id}`;
542
+ if (inflight.has(inflightKey)) continue;
543
+ inflight.add(inflightKey);
544
+ reconcileAdvance(group, record.id).catch((error) => warn(group, error)).finally(() => {
545
+ inflight.delete(inflightKey);
546
+ });
547
+ }
548
+ };
549
+ /** One reconcile pass over every group's persisted flows — never sends. */
550
+ const reconcilePass = async () => {
551
+ if (!unlocked()) return;
552
+ let groups;
553
+ try {
554
+ groups = await storage.groups();
555
+ } catch {
556
+ return;
557
+ }
558
+ await Promise.all(groups.map(async (group) => reconcileGroup(group)));
559
+ };
560
+ const warn = (group, error) => {
561
+ const category = error instanceof Fiat24AppError ? error.category : "protocol";
562
+ const code = error instanceof Fiat24AppError ? error.code : void 0;
563
+ options.logger.warn(`fiat24 reconcile ${groupKey$1(group)} failed`, {
564
+ category,
565
+ code
566
+ });
567
+ };
568
+ const poll = async () => {
569
+ polling = true;
570
+ try {
571
+ await reconcilePass();
572
+ } finally {
573
+ polling = false;
574
+ timer = visible && unlocked() ? options.setTimer(FIAT24_RECONCILE_MS, () => void poll()) : void 0;
575
+ }
576
+ };
577
+ const dropGroup = (group) => {
578
+ options.sessions.end(group);
579
+ drafts.delete(groupKey$1(group));
580
+ for (const id of options.sessions.openedIds(group)) try {
581
+ requests.reject(id);
582
+ } catch {}
583
+ };
584
+ return {
585
+ flows: {
586
+ list: async (group) => {
587
+ requireEnabled(group);
588
+ const out = [];
589
+ for (const record of await persisted(group)) out.push(record);
590
+ for (const [id, state] of draftsOf(group)) out.push({
591
+ id,
592
+ state
593
+ });
594
+ return out;
595
+ },
596
+ start,
597
+ advance,
598
+ discard,
599
+ payoutSettlement
600
+ },
601
+ reconcileGroup,
602
+ unlock: () => {
603
+ if (visible && timer === void 0 && !polling) timer = options.setTimer(FIAT24_RECONCILE_MS, () => void poll());
604
+ },
605
+ setVisible: (next) => {
606
+ visible = next;
607
+ if (visible && unlocked() && timer === void 0 && !polling) poll().catch(() => void 0);
608
+ else if (!visible && timer !== void 0) {
609
+ timer();
610
+ timer = void 0;
611
+ }
612
+ },
613
+ lock: () => {
614
+ if (timer !== void 0) {
615
+ timer();
616
+ timer = void 0;
617
+ }
618
+ drafts.clear();
619
+ options.sessions.endAll();
620
+ },
621
+ dropGroup,
622
+ dropMissing: (wallets) => {
623
+ const groups = new Map(known);
624
+ for (const group of options.sessions.tracked()) groups.set(groupKey$1(group), group);
625
+ for (const group of groups.values()) if (!wallets.has(group.walletId)) dropGroup(group);
626
+ },
627
+ close: () => {
628
+ visible = false;
629
+ if (timer !== void 0) {
630
+ timer();
631
+ timer = void 0;
632
+ }
633
+ drafts.clear();
634
+ options.sessions.endAll();
635
+ }
636
+ };
637
+ }
638
+ // src/apps/fiat24/live.ts
639
+ /** The pacing the SDK README gives for advancing an in-flight flow — reused for account polls. */
640
+ const FIAT24_POLL_MS = 15e3;
641
+ const CLEARED = {
642
+ status: "stale",
643
+ data: void 0,
644
+ updatedAt: void 0
645
+ };
646
+ function createFiat24Live(options) {
647
+ const views = /* @__PURE__ */ new Set();
648
+ let visible = false;
649
+ let locked = false;
650
+ let closedAll = false;
651
+ const emit = (view) => {
652
+ for (const listener of view.listeners) listener(view.state);
653
+ };
654
+ const set = (view, next) => {
655
+ view.state = next;
656
+ emit(view);
657
+ };
658
+ const active = (view) => !closedAll && !view.closed && visible && !locked && options.wallet.getSnapshot().vault === "unlocked";
659
+ const arm = (view) => {
660
+ if (view.cancel !== void 0 || !active(view)) return;
661
+ view.cancel = options.setTimer(FIAT24_POLL_MS, () => {
662
+ view.cancel = void 0;
663
+ poll(view);
664
+ });
665
+ };
666
+ const poll = async (view) => {
667
+ if (view.polling || !active(view)) return;
668
+ view.polling = true;
669
+ try {
670
+ const data = await options.account(view.group);
671
+ if (active(view)) set(view, {
672
+ status: "live",
673
+ data,
674
+ updatedAt: options.now(),
675
+ error: void 0
676
+ });
677
+ } catch (error) {
678
+ if (active(view)) {
679
+ const mapped = fromSdk(error);
680
+ set(view, {
681
+ status: "stale",
682
+ data: view.state.data,
683
+ updatedAt: view.state.updatedAt,
684
+ error: {
685
+ category: mapped.category,
686
+ code: mapped.code
687
+ }
688
+ });
689
+ }
690
+ } finally {
691
+ view.polling = false;
692
+ arm(view);
693
+ }
694
+ };
695
+ /** Cancel the pending tick and drop the account data — lock and close share this. */
696
+ const clearView = (view) => {
697
+ view.cancel?.();
698
+ view.cancel = void 0;
699
+ set(view, CLEARED);
700
+ };
701
+ return {
702
+ view: (group) => {
703
+ const view = {
704
+ group,
705
+ state: {
706
+ status: "loading",
707
+ data: void 0,
708
+ updatedAt: void 0
709
+ },
710
+ listeners: /* @__PURE__ */ new Set(),
711
+ closed: false,
712
+ cancel: void 0,
713
+ polling: false
714
+ };
715
+ views.add(view);
716
+ poll(view);
717
+ return {
718
+ getState: () => view.state,
719
+ subscribe: (listener) => {
720
+ view.listeners.add(listener);
721
+ return () => {
722
+ view.listeners.delete(listener);
723
+ };
724
+ },
725
+ close: async () => {
726
+ if (view.closed) return;
727
+ view.closed = true;
728
+ views.delete(view);
729
+ clearView(view);
730
+ await Promise.resolve();
731
+ }
732
+ };
733
+ },
734
+ setVisible: (next) => {
735
+ if (next === visible) return;
736
+ visible = next;
737
+ for (const view of views) if (visible) poll(view);
738
+ else {
739
+ view.cancel?.();
740
+ view.cancel = void 0;
741
+ set(view, {
742
+ ...view.state,
743
+ status: "stale"
744
+ });
745
+ }
746
+ },
747
+ unlock: async () => {
748
+ locked = false;
749
+ for (const view of views) poll(view);
750
+ await Promise.resolve();
751
+ },
752
+ lock: () => {
753
+ locked = true;
754
+ for (const view of views) clearView(view);
755
+ },
756
+ close: () => {
757
+ closedAll = true;
758
+ for (const view of views) {
759
+ view.closed = true;
760
+ clearView(view);
761
+ }
762
+ views.clear();
763
+ }
764
+ };
765
+ }
766
+ // src/apps/fiat24/owner.ts
767
+ /**
768
+ * The group's Fiat24 owner: its `evm.bip44` address on Arbitrum One — the address every Fiat24 read
769
+ * and every request is scoped to (the same derivation polymarket's `signerOf` performs on Polygon).
770
+ * A locked vault maps to `unlock-required`; every other failure collapses to a fixed `unavailable`
771
+ * through `fromSdk` — kernel error messages never reach the host.
772
+ */
773
+ const isEvmAddress$1 = (address) => /^0x[0-9a-fA-F]{40}$/.test(address);
774
+ function createFiat24Owner(account) {
775
+ return async (group) => {
776
+ let resolved;
777
+ try {
778
+ resolved = await account({
779
+ walletId: group.walletId,
780
+ groupIndex: group.groupIndex,
781
+ template: "evm.bip44",
782
+ network: "eip155:42161"
783
+ });
784
+ } catch (error) {
785
+ if (error instanceof WalletError && error.code === "locked") throw new Fiat24AppError("unlock-required", "the vault is locked");
786
+ throw fromSdk(error);
787
+ }
788
+ if (!("address" in resolved) || !isEvmAddress$1(resolved.address)) throw new Fiat24AppError("unavailable", "the group has no EVM address");
789
+ return resolved.address;
790
+ };
791
+ }
792
+ // src/apps/fiat24/rpc.ts
793
+ /**
794
+ * The viem `Client` the Fiat24 SDK reads Arbitrum One (`eip155:42161`) through: the engine's
795
+ * primary endpoint corroborated by the independent one, under the same rules the engine's own
796
+ * transaction reads follow.
797
+ *
798
+ * A second upstream decides corroboration per call: `independentClient` `available` → every read
799
+ * runs on both endpoints; `not-needed`/`unavailable` → the primary alone. Rules:
800
+ *
801
+ * - Method allow-list of exactly what the SDK 0.1.0 issues (its `viem/actions` imports); anything
802
+ * else refuses.
803
+ * - `eth_chainId` must answer `0xa4b1` on every queried endpoint.
804
+ * - `eth_blockNumber` returns the LOWER head, so the block the SDK then pins exists on both.
805
+ * - `eth_call`/`eth_getStorageAt`/`eth_getTransactionCount`/`eth_getBlockByNumber` at an explicit hex
806
+ * block, and `eth_getLogs` over a numeric range: both endpoints must agree — normalised results
807
+ * are compared and any disagreement fails (a missing block on one side IS a disagreement). A
808
+ * block read at any other tag refuses (the SDK always pins an explicit block).
809
+ * - `eth_getTransactionCount` at `"pending"`/`"latest"` returns the HIGHER answer — the engine's
810
+ * nonce rule (`transactions/evm.ts` `prepareSpec`).
811
+ * - `eth_getTransactionReceipt`/`eth_getTransactionByHash`: a null on EITHER endpoint answers null —
812
+ * conservative, so the SDK's reconcile can never turn a one-sided gap into a false `not-sent`
813
+ * (`flows/tx.ts` `byNonce` in the SDK); two non-null answers are compared on the binding
814
+ * projection.
815
+ * - An erroring independent endpoint fails the call (fail closed) — the same rule polymarket's
816
+ * `locate` follows. The primary's error propagates verbatim: it may carry revert data the SDK
817
+ * decodes into `contract-revert`.
818
+ * - No batching and no retries: a corroboration failure must never re-fire the read pair.
819
+ *
820
+ * Every error thrown here is a plain `Error` with a fixed message — the SDK maps them to
821
+ * `rpc-error`; params, results and endpoint details never enter a message.
822
+ */
823
+ const NETWORK$1 = "eip155:42161";
824
+ /** `numberToHex(42161)` — what every endpoint must answer for `eth_chainId`. */
825
+ const ARBITRUM_ONE = "0xa4b1";
826
+ const MISMATCH = "the rpc endpoints disagree";
827
+ const MALFORMED = "the rpc endpoint returned a malformed result";
828
+ const UNPINNED = "fiat24 rpc reads must pin an explicit block";
829
+ const REFUSED$1 = "fiat24 rpc method not allowed";
830
+ const isObject = (value) => typeof value === "object" && value !== null;
831
+ /** Params shaped as an array — `Array.isArray` on `unknown` would narrow to `any[]`. */
832
+ const isArgs = (value) => Array.isArray(value);
833
+ /** An explicit block quantity — never a named tag. */
834
+ const isBlock = (value) => typeof value === "string" && /^0x[0-9a-fA-F]+$/.test(value);
835
+ const hexBig = (value) => isBlock(value) ? BigInt(value) : void 0;
836
+ const quantity = (value) => {
837
+ const parsed = hexBig(value);
838
+ if (parsed === void 0) throw new Error(MALFORMED);
839
+ return parsed;
840
+ };
841
+ /** Hex-string fields compare case-insensitively; anything else by identity. */
842
+ const fieldEq = (a, b) => typeof a === "string" && typeof b === "string" ? a.toLowerCase() === b.toLowerCase() : a === b;
843
+ const sameLog = (a, b) => {
844
+ if (!isObject(a) || !isObject(b)) return false;
845
+ const topicsA = a["topics"];
846
+ const topicsB = b["topics"];
847
+ return fieldEq(a["address"], b["address"]) && Array.isArray(topicsA) && Array.isArray(topicsB) && topicsA.length === topicsB.length && topicsA.every((topic, i) => fieldEq(topic, topicsB[i])) && fieldEq(a["data"], b["data"]) && hexBig(a["blockNumber"]) === hexBig(b["blockNumber"]) && fieldEq(a["blockHash"], b["blockHash"]) && fieldEq(a["transactionHash"], b["transactionHash"]) && hexBig(a["logIndex"]) === hexBig(b["logIndex"]) && a["removed"] === b["removed"];
848
+ };
849
+ const sameLogs = (a, b) => Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((log, i) => sameLog(log, b[i]));
850
+ const RECEIPT_FIELDS = [
851
+ "transactionHash",
852
+ "blockHash",
853
+ "blockNumber",
854
+ "status",
855
+ "from",
856
+ "to"
857
+ ];
858
+ /** A receipt compares on the binding projection plus its normalised logs. */
859
+ const sameReceipt = (a, b) => isObject(a) && isObject(b) && RECEIPT_FIELDS.every((name) => name === "blockNumber" ? hexBig(a[name]) === hexBig(b[name]) : fieldEq(a[name], b[name])) && sameLogs(a["logs"], b["logs"]);
860
+ const TX_QUANTITY_FIELDS = [
861
+ "nonce",
862
+ "value",
863
+ "blockNumber"
864
+ ];
865
+ const TX_HEX_FIELDS = [
866
+ "hash",
867
+ "from",
868
+ "to",
869
+ "input",
870
+ "blockHash"
871
+ ];
872
+ const sameTransaction = (a, b) => isObject(a) && isObject(b) && TX_QUANTITY_FIELDS.every((name) => hexBig(a[name]) === hexBig(b[name])) && TX_HEX_FIELDS.every((name) => fieldEq(a[name], b[name]));
873
+ const sameBlock = (a, b) => isObject(a) && isObject(b) && fieldEq(a["hash"], b["hash"]) && hexBig(a["number"]) === hexBig(b["number"]) && hexBig(a["timestamp"]) === hexBig(b["timestamp"]);
874
+ const SECOND_FAILED = Symbol("independent-failed");
875
+ /**
876
+ * `createFiat24Client` — the cross-checked Arbitrum One client handed to every SDK read. The
877
+ * primary is `networks.client(NETWORK)`; `networks.independentClient(NETWORK)` is resolved per
878
+ * request so a mid-session endpoint change takes effect on the next read.
879
+ */
880
+ function createFiat24Client(networks) {
881
+ const primary = networks.client(NETWORK$1);
882
+ /** Both endpoints, or the primary alone; an independent failure fails closed. */
883
+ const both = async (call) => {
884
+ const independent = networks.independentClient(NETWORK$1);
885
+ if (independent.kind !== "available") return {
886
+ result: await primary.transport.request(call),
887
+ other: void 0
888
+ };
889
+ const corroborate = async () => {
890
+ try {
891
+ return await independent.client.transport.request(call);
892
+ } catch {
893
+ return SECOND_FAILED;
894
+ }
895
+ };
896
+ const pending = corroborate();
897
+ const result = await primary.transport.request(call);
898
+ const other = await pending;
899
+ if (other === SECOND_FAILED) throw new Error("the second rpc endpoint failed");
900
+ return {
901
+ result,
902
+ other: { value: other }
903
+ };
904
+ };
905
+ /** One answer corroborated byte-exact (hex compare is case-insensitive). */
906
+ const equal = async (call) => {
907
+ const { result, other } = await both(call);
908
+ if (other !== void 0 && !fieldEq(result, other.value)) throw new Error(MISMATCH);
909
+ return result;
910
+ };
911
+ const chainId = async (call) => {
912
+ const { result, other } = await both(call);
913
+ if (!fieldEq(result, ARBITRUM_ONE) || other !== void 0 && !fieldEq(other.value, ARBITRUM_ONE)) throw new Error("the rpc endpoint answered a different chain");
914
+ return result;
915
+ };
916
+ const blockNumber = async (call) => {
917
+ const { result, other } = await both(call);
918
+ if (other === void 0) return result;
919
+ return quantity(result) <= quantity(other.value) ? result : other.value;
920
+ };
921
+ const transactionCount = async (call, tag) => {
922
+ if (tag === "pending" || tag === "latest") {
923
+ const { result, other } = await both(call);
924
+ if (other === void 0) return result;
925
+ return quantity(result) >= quantity(other.value) ? result : other.value;
926
+ }
927
+ if (!isBlock(tag)) throw new Error(UNPINNED);
928
+ const { result, other } = await both(call);
929
+ if (other !== void 0 && hexBig(result) !== hexBig(other.value)) throw new Error(MISMATCH);
930
+ return result;
931
+ };
932
+ const logs = async (call) => {
933
+ const { result, other } = await both(call);
934
+ if (!Array.isArray(result)) throw new TypeError(MALFORMED);
935
+ if (other !== void 0 && !sameLogs(result, other.value)) throw new Error(MISMATCH);
936
+ return result;
937
+ };
938
+ /** A block both endpoints must serve identically: one side missing it is a disagreement. */
939
+ const block = async (call) => {
940
+ const { result, other } = await both(call);
941
+ if (other === void 0) return result;
942
+ if (result === null || other.value === null || !sameBlock(result, other.value)) throw new Error(MISMATCH);
943
+ return result;
944
+ };
945
+ /** A null on either side answers null — never a false absence on the reconcile path. */
946
+ const nullable = async (call, same) => {
947
+ const { result, other } = await both(call);
948
+ if (other === void 0) return result;
949
+ if (result === null || other.value === null) return null;
950
+ if (!same(result, other.value)) throw new Error(MISMATCH);
951
+ return result;
952
+ };
953
+ const request = async ({ method, params }) => {
954
+ const call = {
955
+ method,
956
+ params
957
+ };
958
+ const args = isArgs(params) ? params : [];
959
+ switch (method) {
960
+ case "eth_chainId": return chainId(call);
961
+ case "eth_blockNumber": return blockNumber(call);
962
+ case "eth_call":
963
+ if (!isBlock(args[1])) throw new Error(UNPINNED);
964
+ return equal(call);
965
+ case "eth_getStorageAt":
966
+ if (!isBlock(args[2])) throw new Error(UNPINNED);
967
+ return equal(call);
968
+ case "eth_getTransactionCount": return transactionCount(call, args[1]);
969
+ case "eth_getBlockByNumber":
970
+ if (!isBlock(args[0])) throw new Error(UNPINNED);
971
+ return block(call);
972
+ case "eth_getLogs": {
973
+ const [filter] = args;
974
+ if (!isObject(filter) || !isBlock(filter["fromBlock"]) || !isBlock(filter["toBlock"])) throw new Error(UNPINNED);
975
+ return logs(call);
976
+ }
977
+ case "eth_getTransactionReceipt": return nullable(call, sameReceipt);
978
+ case "eth_getTransactionByHash": return nullable(call, sameTransaction);
979
+ default: throw new Error(REFUSED$1);
980
+ }
981
+ };
982
+ return createClient({
983
+ chain: arbitrum$1,
984
+ transport: custom({ request }, { retryCount: 0 }),
985
+ ccipRead: false
986
+ });
987
+ }
988
+ // src/apps/fiat24/signer.ts
989
+ /**
990
+ * The SDK's `Fiat24Signer` over the engine's request pipeline. `sendTransaction` opens an app
991
+ * request carrying the SDK's exact `to`/`data`/`value` and pins the SDK-chosen `nonce`: the engine
992
+ * rebuilds the transaction with fresh fees but refuses — `NonceConflictError`, before anything is
993
+ * shown — when the sender's next free nonce differs. A refusal surfaces to the SDK only while it
994
+ * can prove nothing was broadcast: an outcome that ended before the `signed` stage — mapped to a
995
+ * `Fiat24Refusal` — becomes `Fiat24Error("signer-rejected")` (the SDK returns the record to
996
+ * `ready`); a request that reached `signed` gets a plain non-rejection error so the SDK records
997
+ * `unknown` and reconciles by nonce rather than risking a second send. `signSessionGrant` does the
998
+ * same for `evm.fiat24-session`: the grant is validated against the SDK's own `sessionLabel`/
999
+ * `sessionMessage` and the chain decoder's `fiat24SessionMessage` before any request opens. No call
1000
+ * data, hashes, grants or signatures ever enter an error message, `opened`/`refused` or the
1001
+ * returned values beyond what the SDK contract itself returns.
1002
+ */
1003
+ const NETWORK = "eip155:42161";
1004
+ const CHAIN_ID = 42161;
1005
+ /** Every contract address the SDK's call builders may target on the pinned deployment. */
1006
+ const CALL_TARGETS = new Set([
1007
+ arbitrum.account.proxy,
1008
+ ...Object.values(arbitrum.tokens).map((token) => token.proxy),
1009
+ arbitrum.deposit.proxy,
1010
+ arbitrum.card.proxy,
1011
+ arbitrum.priceList.proxy,
1012
+ arbitrum.f24Sales.proxy,
1013
+ arbitrum.f24.address,
1014
+ arbitrum.usdc
1015
+ ].map((address) => address.toLowerCase()));
1016
+ const accountRef = (group) => ({
1017
+ kind: "hd",
1018
+ walletId: group.walletId,
1019
+ groupIndex: group.groupIndex,
1020
+ template: "evm.bip44"
1021
+ });
1022
+ const REFUSED = "the request was refused";
1023
+ const PREPARE_FAILED = "the transaction could not be prepared";
1024
+ const SESSION_FAILED = "the session grant could not be prepared";
1025
+ const rejected = (message) => new Fiat24Error("signer-rejected", message);
1026
+ const refusalOf = (stage) => stage === "failed" ? "failed-before-signing" : stage;
1027
+ const isTransactionOutcome = (outcome) => typeof outcome === "object" && outcome !== null && "hash" in outcome && typeof outcome.hash === "string" && isHash(outcome.hash);
1028
+ const isSessionOutcome = (outcome) => typeof outcome === "object" && outcome !== null && "kind" in outcome && outcome.kind === "evm.fiat24-session" && "signature" in outcome && outcome.signature instanceof Uint8Array && outcome.signature.length === 65;
1029
+ const createFiat24Signer = (options) => {
1030
+ const { requests, group, owner, opened, refused } = options;
1031
+ const invalid = (message) => {
1032
+ refused("invalid-call");
1033
+ throw rejected(message);
1034
+ };
1035
+ const sendTransaction = async (request) => {
1036
+ if (request.chainId !== CHAIN_ID) invalid("the call is for another chain");
1037
+ if (!isAddressEqual(request.from, owner)) invalid("the call is not from this account");
1038
+ if (!CALL_TARGETS.has(request.to.toLowerCase())) invalid("the call targets an unknown contract");
1039
+ if (!Number.isSafeInteger(request.nonce) || request.nonce < 0) invalid("the call carries an invalid nonce");
1040
+ const account = accountRef(group);
1041
+ let pending;
1042
+ try {
1043
+ pending = await requests.prepare({
1044
+ method: "evm-sign",
1045
+ account,
1046
+ network: NETWORK,
1047
+ request: {
1048
+ kind: "evm.transaction",
1049
+ network: NETWORK,
1050
+ account,
1051
+ tx: {
1052
+ type: "eip1559",
1053
+ chainId: CHAIN_ID,
1054
+ nonce: 0,
1055
+ gas: "0x0",
1056
+ to: request.to,
1057
+ value: `0x${request.value.toString(16)}`,
1058
+ data: request.data,
1059
+ accessList: [],
1060
+ maxFeePerGas: "0x0",
1061
+ maxPriorityFeePerGas: "0x0"
1062
+ }
1063
+ },
1064
+ nonce: request.nonce
1065
+ });
1066
+ } catch (error) {
1067
+ refused(error instanceof NonceConflictError ? "nonce-conflict" : "prepare-failed");
1068
+ throw rejected(PREPARE_FAILED);
1069
+ }
1070
+ opened(pending.id);
1071
+ let outcome;
1072
+ try {
1073
+ outcome = await requests.outcome(pending.id);
1074
+ } catch (error) {
1075
+ if (error instanceof RequestEndedError) {
1076
+ if (!error.signed) {
1077
+ refused(refusalOf(error.stage));
1078
+ throw rejected(REFUSED);
1079
+ }
1080
+ throw new Error("the request was signed but its outcome is unknown", { cause: error });
1081
+ }
1082
+ throw error;
1083
+ }
1084
+ if (isTransactionOutcome(outcome)) {
1085
+ const hash = outcome.hash.toLowerCase();
1086
+ if (isHash(hash)) return hash;
1087
+ }
1088
+ throw new Error("the request ended without a transaction hash");
1089
+ };
1090
+ const signSessionGrant = async (grant) => {
1091
+ const tokenId = options.tokenId ?? invalid("the session grant does not match this account");
1092
+ const sessionArgs = {
1093
+ chainId: CHAIN_ID,
1094
+ tokenId,
1095
+ deadline: grant.deadline
1096
+ };
1097
+ if (grant.chainId !== CHAIN_ID || grant.tokenId !== tokenId || grant.deadline < 1n || grant.deadline > BigInt(Number.MAX_SAFE_INTEGER) || grant.hash !== sessionLabel(sessionArgs) || grant.message !== sessionMessage(sessionArgs) || grant.message !== fiat24SessionMessage(CHAIN_ID, tokenId.toString(10), Number(grant.deadline))) invalid("the session grant does not match this account");
1098
+ const account = accountRef(group);
1099
+ let pending;
1100
+ try {
1101
+ pending = await requests.prepare({
1102
+ method: "evm-sign",
1103
+ account,
1104
+ network: NETWORK,
1105
+ request: {
1106
+ kind: "evm.fiat24-session",
1107
+ network: NETWORK,
1108
+ account,
1109
+ tokenId: tokenId.toString(10),
1110
+ deadline: Number(grant.deadline)
1111
+ }
1112
+ });
1113
+ } catch {
1114
+ refused("prepare-failed");
1115
+ throw rejected(SESSION_FAILED);
1116
+ }
1117
+ opened(pending.id);
1118
+ let outcome;
1119
+ try {
1120
+ outcome = await requests.outcome(pending.id);
1121
+ } catch (error) {
1122
+ if (error instanceof RequestEndedError) {
1123
+ refused(refusalOf(error.stage));
1124
+ throw rejected(REFUSED);
1125
+ }
1126
+ throw error;
1127
+ }
1128
+ if (isSessionOutcome(outcome)) return bytesToHex(outcome.signature);
1129
+ throw new Error("the request ended without a signature");
1130
+ };
1131
+ return {
1132
+ address: owner,
1133
+ sendTransaction,
1134
+ signSessionGrant
1135
+ };
1136
+ };
1137
+ // src/apps/fiat24/sessions.ts
1138
+ const groupKey = (group) => `${group.walletId}/${group.groupIndex}`;
1139
+ function createFiat24Sessions(options) {
1140
+ const sessions = /* @__PURE__ */ new Map();
1141
+ const opened = /* @__PURE__ */ new Map();
1142
+ const known = /* @__PURE__ */ new Map();
1143
+ const openedIdsOf = (group) => {
1144
+ const key = groupKey(group);
1145
+ known.set(key, group);
1146
+ let ids = opened.get(key);
1147
+ if (ids === void 0) {
1148
+ ids = /* @__PURE__ */ new Set();
1149
+ opened.set(key, ids);
1150
+ }
1151
+ return ids;
1152
+ };
1153
+ const sdk = async (group, tokenId) => {
1154
+ if (options.api === void 0) return;
1155
+ const key = groupKey(group);
1156
+ known.set(key, group);
1157
+ let session = sessions.get(key);
1158
+ if (session === void 0) {
1159
+ const owner = await options.owner(group);
1160
+ session = options.api.openSession({
1161
+ tokenId,
1162
+ signer: {
1163
+ address: owner,
1164
+ signSessionGrant: signer({
1165
+ group,
1166
+ owner,
1167
+ tokenId
1168
+ }).signSessionGrant
1169
+ }
1170
+ });
1171
+ sessions.set(key, session);
1172
+ }
1173
+ return session;
1174
+ };
1175
+ const signer = ({ group, owner, tokenId, opened: onOpened, refused }) => {
1176
+ known.set(groupKey(group), group);
1177
+ const ids = openedIdsOf(group);
1178
+ return createFiat24Signer({
1179
+ requests: {
1180
+ prepare: options.requests.prepare,
1181
+ outcome: async (id) => {
1182
+ try {
1183
+ return await options.requests.outcome(id);
1184
+ } finally {
1185
+ ids.delete(id);
1186
+ }
1187
+ }
1188
+ },
1189
+ group,
1190
+ owner,
1191
+ ...tokenId === void 0 ? {} : { tokenId },
1192
+ opened: (id) => {
1193
+ ids.add(id);
1194
+ onOpened?.(id);
1195
+ },
1196
+ refused: (reason) => refused?.(reason)
1197
+ });
1198
+ };
1199
+ return {
1200
+ sdk,
1201
+ reads: (group, tokenId) => {
1202
+ if (options.api === void 0) return;
1203
+ const read = async (body) => {
1204
+ const session = await sdk(group, tokenId);
1205
+ if (session === void 0) throw new Fiat24AppError("api-unavailable", "the fiat24 api is not configured");
1206
+ return body(session);
1207
+ };
1208
+ return {
1209
+ profile: async () => read(async (session) => session.profile()),
1210
+ cards: async () => read(async (session) => session.cards()),
1211
+ cardDisplayToken: async (externalId) => read(async (session) => session.cardDisplayToken(externalId)),
1212
+ transactions: async (query) => read(async (session) => session.transactions(query)),
1213
+ end: () => {
1214
+ sessions.get(groupKey(group))?.end();
1215
+ sessions.delete(groupKey(group));
1216
+ }
1217
+ };
1218
+ },
1219
+ signer,
1220
+ openedIds: (group) => openedIdsOf(group),
1221
+ tracked: () => [...known.values()],
1222
+ end: (group) => {
1223
+ const key = groupKey(group);
1224
+ sessions.get(key)?.end();
1225
+ sessions.delete(key);
1226
+ },
1227
+ endAll: () => {
1228
+ for (const session of sessions.values()) session.end();
1229
+ sessions.clear();
1230
+ }
1231
+ };
1232
+ }
1233
+ // src/apps/fiat24/app.ts
1234
+ /**
1235
+ * The Fiat24 app definition: `fiat24()` returns the `AppDefinition` `createApps` builds over the
1236
+ * shared `AppContext` — the account read over the cross-checked Arbitrum One client, the visible-
1237
+ * and-unlocked live view, the enablement record machine, the resumable flows, the secured-read
1238
+ * sessions and the public REST reads. `enableWhen` allows `close-only`: a restricted jurisdiction
1239
+ * may still need the read surface to wind positions down. The REST api at api.fiat24.com has no
1240
+ * CORS and is reachable only through the host-injected `config.fetch` — `context.fetch` is never a
1241
+ * fallback. A wallet removal drops its groups' sessions, drafts and open requests; the group's
1242
+ * persisted flow records are pruned by the generic store cleanup with everything else.
1243
+ */
1244
+ function fiat24(config = {}) {
1245
+ if (config.fetch !== void 0 && typeof config.fetch !== "function") throw new Error("the fiat24 api fetch must be a function");
1246
+ return {
1247
+ id: "fiat24",
1248
+ enableWhen: ["available", "close-only"],
1249
+ create: (context) => {
1250
+ const owner = createFiat24Owner(context.account);
1251
+ const client = createFiat24Client(context.networks);
1252
+ const account = createFiat24Account({
1253
+ owner,
1254
+ client
1255
+ });
1256
+ const live = createFiat24Live({
1257
+ account,
1258
+ wallet: context.wallet,
1259
+ setTimer: context.setTimer,
1260
+ now: context.now
1261
+ });
1262
+ const api = config.fetch === void 0 ? void 0 : createFiat24Api({
1263
+ fetch: config.fetch,
1264
+ now: context.now
1265
+ });
1266
+ const sessions = createFiat24Sessions({
1267
+ requests: context.requests,
1268
+ owner,
1269
+ api
1270
+ });
1271
+ const flows = createFiat24Flows({
1272
+ wallet: context.wallet,
1273
+ requests: context.requests,
1274
+ storage: context.storage,
1275
+ random: context.random,
1276
+ setTimer: context.setTimer,
1277
+ logger: context.logger,
1278
+ availability: context.availability,
1279
+ groupState: context.groupState,
1280
+ client,
1281
+ owner,
1282
+ account,
1283
+ api,
1284
+ sessions
1285
+ });
1286
+ const requireApi = () => {
1287
+ if (api === void 0) throw new Fiat24AppError("api-unavailable", "no api.fiat24.com fetch was injected — the Fiat24 REST api is off");
1288
+ return api;
1289
+ };
1290
+ /** Api.fiat24.com answers are untrusted — the SDK validates and we normalize its errors. */
1291
+ const call = async (body) => {
1292
+ try {
1293
+ return await body(requireApi());
1294
+ } catch (error) {
1295
+ throw fromSdk(error);
1296
+ }
1297
+ };
1298
+ const publicReads = {
1299
+ rates: async () => call(async (a) => a.rates()),
1300
+ paymentPurposes: async () => call(async (a) => a.paymentPurposes()),
1301
+ countries: async () => call(async (a) => a.countries()),
1302
+ countryCities: async () => call(async (a) => a.countryCities()),
1303
+ banks: async () => call(async (a) => a.banks()),
1304
+ bankByIban: async (iban) => call(async (a) => a.bankByIban(iban)),
1305
+ kycUrl: (walletProviderId) => kycUrl(walletProviderId)
1306
+ };
1307
+ /** The group's tokenId once it has an owned live account — the session's identity. */
1308
+ const session = (group) => {
1309
+ const gated = async () => {
1310
+ if (context.wallet.getSnapshot().vault !== "unlocked") throw new Fiat24AppError("unlock-required", "unlock the vault to use the Fiat24 app");
1311
+ if (context.groupState(group)?.status !== "enabled") throw new Fiat24AppError("not-enabled", "enable the Fiat24 app for this group first");
1312
+ requireApi();
1313
+ const state = await account(group);
1314
+ if (state.status !== "live" || !state.view.account.ownsToken) throw new Fiat24AppError("no-account", "the group owns no live Fiat24 account");
1315
+ const reads = sessions.reads(group, state.view.account.tokenId);
1316
+ if (reads === void 0) throw new Fiat24AppError("api-unavailable", "no api.fiat24.com fetch was injected — the Fiat24 REST api is off");
1317
+ return reads;
1318
+ };
1319
+ /** Secured answers are untrusted too — every error normalizes through `fromSdk`. */
1320
+ const secured = async (body) => {
1321
+ try {
1322
+ return await body(await gated());
1323
+ } catch (error) {
1324
+ throw fromSdk(error);
1325
+ }
1326
+ };
1327
+ return {
1328
+ profile: async () => secured(async (reads) => reads.profile()),
1329
+ cards: async () => secured(async (reads) => reads.cards()),
1330
+ cardDisplayToken: async (externalId) => secured(async (reads) => reads.cardDisplayToken(externalId)),
1331
+ transactions: async (query) => secured(async (reads) => reads.transactions(query)),
1332
+ end: () => sessions.end(group)
1333
+ };
1334
+ };
1335
+ const unsubscribe = context.wallet.subscribe(() => {
1336
+ const wallets = new Set(context.wallet.getSnapshot().wallets.map((wallet) => wallet.walletId));
1337
+ flows.dropMissing(wallets);
1338
+ });
1339
+ return {
1340
+ api: {
1341
+ account,
1342
+ live: live.view,
1343
+ setVisible: (visible) => {
1344
+ live.setVisible(visible);
1345
+ flows.setVisible(visible);
1346
+ },
1347
+ flows: flows.flows,
1348
+ session,
1349
+ api: publicReads
1350
+ },
1351
+ provider: createFiat24Enable({
1352
+ storage: context.storage,
1353
+ onDisable: flows.dropGroup,
1354
+ onEnabled: (group) => void flows.reconcileGroup(group),
1355
+ owner,
1356
+ client,
1357
+ account
1358
+ }),
1359
+ unlock: async () => {
1360
+ await live.unlock();
1361
+ flows.unlock();
1362
+ },
1363
+ lock: () => {
1364
+ live.lock();
1365
+ flows.lock();
1366
+ },
1367
+ close: () => {
1368
+ unsubscribe();
1369
+ live.close();
1370
+ flows.close();
1371
+ }
1372
+ };
1373
+ }
1374
+ };
1375
+ }
1376
+ export { FIAT24_POLL_MS, Fiat24AppError, fiat24 };
1377
+
1378
+ //# sourceMappingURL=apps-fiat24.mjs.map