@fun-xyz/fiat-contract 0.30.0 → 0.30.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/assert.d.ts CHANGED
@@ -55,4 +55,3 @@ export interface ValidatedFixture {
55
55
  export declare function assertFixture(id: string): ValidatedFixture;
56
56
  /** Validate every recorded fixture. Throws on the first violation. */
57
57
  export declare function assertAllFixtures(): ValidatedFixture[];
58
- //# sourceMappingURL=assert.d.ts.map
@@ -8,4 +8,3 @@ var ROUTING_ENDPOINTS = {
8
8
  export {
9
9
  ROUTING_ENDPOINTS
10
10
  };
11
- //# sourceMappingURL=chunk-3SZPKXVL.mjs.map
@@ -1,5 +1,5 @@
1
1
  // package.json
2
- var version = "0.30.0";
2
+ var version = "0.30.1";
3
3
 
4
4
  // src/table.ts
5
5
  var TABLE_VERSION = version;
@@ -514,4 +514,3 @@ export {
514
514
  tableEntry,
515
515
  isTerminal
516
516
  };
517
- //# sourceMappingURL=chunk-OLRRCFJQ.mjs.map
@@ -41,4 +41,3 @@ export {
41
41
  FUN_KYC_CONSENT_DOCUMENTS,
42
42
  PUBLISHED_TERMS_DOCUMENTS
43
43
  };
44
- //# sourceMappingURL=chunk-XKI5XTUO.mjs.map
@@ -6,4 +6,3 @@ var MOONPAY_ENDPOINTS = {
6
6
  export {
7
7
  MOONPAY_ENDPOINTS
8
8
  };
9
- //# sourceMappingURL=chunk-F4NRKWF5.mjs.map
File without changes
package/dist/codes.d.ts CHANGED
@@ -1270,4 +1270,3 @@ export declare const COUNTRY_TO_CURRENCY: { [K in CountryCodeLiteral]: FiatCurre
1270
1270
  export declare const PAYMENT_METHOD_CATEGORIES: readonly ["card", "apple_pay", "google_pay", "bank_transfer"];
1271
1271
  export type PaymentMethodCategory = (typeof PAYMENT_METHOD_CATEGORIES)[number];
1272
1272
  export {};
1273
- //# sourceMappingURL=codes.d.ts.map
@@ -5,4 +5,3 @@
5
5
  * inlines them so the package never touches the filesystem (React Native, browsers, CJS output).
6
6
  */
7
7
  export declare const FIXTURE_DATA: Readonly<Record<string, unknown>>;
8
- //# sourceMappingURL=data.d.ts.map
@@ -49,4 +49,3 @@ export interface LoadedFixture {
49
49
  json: unknown;
50
50
  }
51
51
  export declare function loadFixtures(): LoadedFixture[];
52
- //# sourceMappingURL=index.d.ts.map
package/dist/index.d.ts CHANGED
@@ -15,4 +15,3 @@ export * from './routing';
15
15
  export * from './providers/moonpay';
16
16
  export * from './providers/moonpay.schemas';
17
17
  export { FIXTURES, FIXTURE_COVERAGE_GAPS, fixtureMeta, loadFixture, loadFixtures, type FixtureMeta, type FixtureSource, type LoadedFixture, } from './fixtures/index';
18
- //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1242,7 +1242,7 @@ var $stepResponse = import_zod.z.union([$providerBoundStepResponse, $blockedStep
1242
1242
  var FiatStepResponseSchema = $stepResponse;
1243
1243
 
1244
1244
  // package.json
1245
- var version = "0.30.0";
1245
+ var version = "0.30.1";
1246
1246
 
1247
1247
  // src/table.ts
1248
1248
  var TABLE_VERSION = version;
@@ -2994,4 +2994,3 @@ var $fault = obj2($faultFields);
2994
2994
  var MoonPayFaultSchema = $fault;
2995
2995
  var $errorBody = obj2({ ...$faultFields, errorCode: $nonEmpty, errorMsg: import_zod2.z.string(), reqId: import_zod2.z.string().optional() });
2996
2996
  var MoonPayErrorBodySchema = $errorBody;
2997
- //# sourceMappingURL=index.js.map
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import "./chunk-KIQOUUEZ.mjs";
1
+ import "./chunk-WBQAMGXK.mjs";
2
2
  import {
3
3
  DOCUMENTED_ENDPOINTS,
4
4
  STATE_KEYS,
@@ -12,19 +12,19 @@ import {
12
12
  tableEntry,
13
13
  unofferedEndpoints,
14
14
  unreachableStates
15
- } from "./chunk-OLRRCFJQ.mjs";
15
+ } from "./chunk-3GKD4CGN.mjs";
16
16
  import {
17
17
  MOONPAY_ENDPOINTS
18
- } from "./chunk-F4NRKWF5.mjs";
18
+ } from "./chunk-TIEGTTFY.mjs";
19
19
  import {
20
20
  FIAT_TERMS_ENDPOINT,
21
21
  FUN_KYC_CONSENT_DOCUMENTS,
22
22
  PROVIDER_CHECKOUT_DOCUMENTS,
23
23
  PUBLISHED_TERMS_DOCUMENTS
24
- } from "./chunk-XKI5XTUO.mjs";
24
+ } from "./chunk-EFWIJWBC.mjs";
25
25
  import {
26
26
  ROUTING_ENDPOINTS
27
- } from "./chunk-3SZPKXVL.mjs";
27
+ } from "./chunk-2NZSOZHV.mjs";
28
28
 
29
29
  // src/codes.ts
30
30
  var US_STATE_CODES = [
@@ -2448,4 +2448,3 @@ export {
2448
2448
  unreachableStates,
2449
2449
  walkTable
2450
2450
  };
2451
- //# sourceMappingURL=index.mjs.map
@@ -204,4 +204,3 @@ export type MoonPayErrorBody = MoonPayFault & {
204
204
  errorMsg: string;
205
205
  reqId?: string;
206
206
  };
207
- //# sourceMappingURL=moonpay.d.ts.map
@@ -26,4 +26,3 @@ module.exports = __toCommonJS(moonpay_exports);
26
26
  var MOONPAY_ENDPOINTS = {
27
27
  next: "POST /fiat/next"
28
28
  };
29
- //# sourceMappingURL=moonpay.js.map
@@ -1,7 +1,6 @@
1
1
  import {
2
2
  MOONPAY_ENDPOINTS
3
- } from "../chunk-F4NRKWF5.mjs";
3
+ } from "../chunk-TIEGTTFY.mjs";
4
4
  export {
5
5
  MOONPAY_ENDPOINTS
6
6
  };
7
- //# sourceMappingURL=moonpay.mjs.map
@@ -30,4 +30,3 @@ export declare const MoonPayResponseSchemaFor: {
30
30
  };
31
31
  export declare const MoonPayFaultSchema: z.ZodType<MoonPayFault>;
32
32
  export declare const MoonPayErrorBodySchema: z.ZodType<MoonPayErrorBody>;
33
- //# sourceMappingURL=moonpay.schemas.d.ts.map
package/dist/routing.d.ts CHANGED
@@ -217,4 +217,3 @@ export type FiatRoutingTableErrorBody = RoutingRateLimitedErrorBody | RoutingFau
217
217
  */
218
218
  export type FiatRoutingQuoteErrorBody = RoutingNoRouteErrorBody | RoutingAmountErrorBody | RoutingFaultErrorBody;
219
219
  export {};
220
- //# sourceMappingURL=routing.d.ts.map
package/dist/routing.js CHANGED
@@ -28,4 +28,3 @@ var ROUTING_ENDPOINTS = {
28
28
  /** Temporary: `POST /fiat/next` replaces it for each provider that moves there. */
29
29
  quote: "POST /fiat/routing/quote"
30
30
  };
31
- //# sourceMappingURL=routing.js.map
package/dist/routing.mjs CHANGED
@@ -1,7 +1,6 @@
1
1
  import {
2
2
  ROUTING_ENDPOINTS
3
- } from "./chunk-3SZPKXVL.mjs";
3
+ } from "./chunk-2NZSOZHV.mjs";
4
4
  export {
5
5
  ROUTING_ENDPOINTS
6
6
  };
7
- //# sourceMappingURL=routing.mjs.map
package/dist/schemas.d.ts CHANGED
@@ -125,4 +125,3 @@ export declare const FiatGeoSchema: z.ZodType<FiatGeo>;
125
125
  export declare const FiatNextRequestSchema: z.ZodType<FiatNextRequest>;
126
126
  export declare const FiatStepResponseSchema: z.ZodType<FiatStepResponse>;
127
127
  export {};
128
- //# sourceMappingURL=schemas.d.ts.map
package/dist/table.d.ts CHANGED
@@ -130,4 +130,3 @@ export declare const tableEntry: (state: FlowState) => TableEntry;
130
130
  * `ORDER{CREATED}` is terminal when its status is in the entry's `terminalStatuses`.
131
131
  */
132
132
  export declare function isTerminal(state: FlowState): boolean;
133
- //# sourceMappingURL=table.d.ts.map
package/dist/table.js CHANGED
@@ -36,7 +36,7 @@ __export(table_exports, {
36
36
  module.exports = __toCommonJS(table_exports);
37
37
 
38
38
  // package.json
39
- var version = "0.30.0";
39
+ var version = "0.30.1";
40
40
 
41
41
  // src/table.ts
42
42
  var TABLE_VERSION = version;
@@ -536,4 +536,3 @@ function isTerminal(state) {
536
536
  }
537
537
  return entry.terminal;
538
538
  }
539
- //# sourceMappingURL=table.js.map
package/dist/table.mjs CHANGED
@@ -11,7 +11,7 @@ import {
11
11
  tableEntry,
12
12
  unofferedEndpoints,
13
13
  unreachableStates
14
- } from "./chunk-OLRRCFJQ.mjs";
14
+ } from "./chunk-3GKD4CGN.mjs";
15
15
  export {
16
16
  DOCUMENTED_ENDPOINTS,
17
17
  STATE_KEYS,
@@ -26,4 +26,3 @@ export {
26
26
  unofferedEndpoints,
27
27
  unreachableStates
28
28
  };
29
- //# sourceMappingURL=table.mjs.map
package/dist/terms.d.ts CHANGED
@@ -70,4 +70,3 @@ export declare const FUN_KYC_CONSENT_DOCUMENTS: Readonly<Record<FunKycConsentLoc
70
70
  * backend accepts any entry, so a client that ships an older version can still check out.
71
71
  */
72
72
  export declare const PUBLISHED_TERMS_DOCUMENTS: readonly TermsDocument[];
73
- //# sourceMappingURL=terms.d.ts.map
package/dist/terms.js CHANGED
@@ -61,4 +61,3 @@ var FUN_KYC_CONSENT_DOCUMENTS = {
61
61
  zh: funKycConsent("7f76d850adaf69783c5d9365e51abb5446f4e5778c63eabbdb4784d72464f855")
62
62
  };
63
63
  var PUBLISHED_TERMS_DOCUMENTS = [MOONPAY_TERMS, ...Object.values(FUN_KYC_CONSENT_DOCUMENTS)];
64
- //# sourceMappingURL=terms.js.map
package/dist/terms.mjs CHANGED
@@ -3,11 +3,10 @@ import {
3
3
  FUN_KYC_CONSENT_DOCUMENTS,
4
4
  PROVIDER_CHECKOUT_DOCUMENTS,
5
5
  PUBLISHED_TERMS_DOCUMENTS
6
- } from "./chunk-XKI5XTUO.mjs";
6
+ } from "./chunk-EFWIJWBC.mjs";
7
7
  export {
8
8
  FIAT_TERMS_ENDPOINT,
9
9
  FUN_KYC_CONSENT_DOCUMENTS,
10
10
  PROVIDER_CHECKOUT_DOCUMENTS,
11
11
  PUBLISHED_TERMS_DOCUMENTS
12
12
  };
13
- //# sourceMappingURL=terms.mjs.map
package/dist/types.d.ts CHANGED
@@ -757,4 +757,3 @@ export type FiatNextRequest = {
757
757
  geo: FiatGeo;
758
758
  } & Record<string, unknown>;
759
759
  export {};
760
- //# sourceMappingURL=types.d.ts.map
package/dist/types.js CHANGED
@@ -16,4 +16,3 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
16
16
  // src/types.ts
17
17
  var types_exports = {};
18
18
  module.exports = __toCommonJS(types_exports);
19
- //# sourceMappingURL=types.js.map
package/dist/types.mjs CHANGED
@@ -1,2 +1 @@
1
- import "./chunk-KIQOUUEZ.mjs";
2
- //# sourceMappingURL=types.mjs.map
1
+ import "./chunk-WBQAMGXK.mjs";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fun-xyz/fiat-contract",
3
- "version": "0.30.0",
3
+ "version": "0.30.1",
4
4
  "description": "Published conformance contract for Fun's headless fiat onramp: FlowState/Transition types, zod schemas, the transition table as data, recorded fixtures, assertion helpers.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -56,9 +56,7 @@
56
56
  "terms.js",
57
57
  "terms.d.ts",
58
58
  "routing.js",
59
- "routing.d.ts",
60
- "README.md",
61
- "!dist/**/*.map"
59
+ "routing.d.ts"
62
60
  ],
63
61
  "engines": {
64
62
  "node": ">=18"
package/README.md DELETED
@@ -1,656 +0,0 @@
1
- # fiat-contract
2
-
3
- The **published contract** between `fun-backend` (emits step responses) and `funkit`/`connect-core`
4
- (renders them). Both repos test against it; neither owns it.
5
-
6
- Four things, zero runtime logic beyond validation:
7
-
8
- | File | What it is |
9
- | --- | --- |
10
- | `src/types.ts` | `FlowState` · `Transition` · `FailureReason` · `Surface` · `Instructions` · `FormDescriptor` · `OrderStatus` · `FiatStepResponse` |
11
- | `src/codes.ts` | Shared country, currency, US subdivision, and payment-method vocabularies |
12
- | `src/schemas.ts` | zod mirrors of every type — the single runtime validator |
13
- | `src/table.ts` | the transition table **as data**: per state, its legal transition set, the states any call from it may return, and `terminal: boolean` |
14
- | `src/assert.ts` + `src/fixtures/` | `assertFiatStepResponse` · `assertLegalEmission` · `assertLegalReturn` · `walkTable` · fixture loader + 18 recorded step responses (inlined as data — no filesystem, so React Native can bundle it) |
15
-
16
- ## Six entry points — production vs test-time
17
-
18
- | Import | Weight | Contains | Used by |
19
- | --- | --- | --- | --- |
20
- | `@fun-xyz/fiat-contract/types` | **0.1 KB** (types erase) | every type; no runtime values | production, both repos |
21
- | `@fun-xyz/fiat-contract/table` | **13.8 KB**, zero deps | `TRANSITION_TABLE`, `stateKey`, `tableEntry`, `isTerminal`, `walkTable`, `TABLE_VERSION`, `TERMINAL_ORDER_STATUSES`, `DOCUMENTED_ENDPOINTS`, `UNOFFERED_ENDPOINTS`, `UNREACHABLE_STATES`, `unofferedEndpoints`, `unreachableStates` | **production frontend** + backend |
22
- | `@fun-xyz/fiat-contract/moonpay` | zero deps | the MoonPay flow on `POST /fiat/next`: action requests, next actions, responses, fault types, and `MOONPAY_ENDPOINTS` | **production frontend** (MoonPay adapter) + backend |
23
- | `@fun-xyz/fiat-contract/terms` | zero deps | the platform terms route: `TermsDocument`, `FiatTermsRequest`, `FiatTermsResponse`, fault types, and `FIAT_TERMS_ENDPOINT` | **production frontend** + backend |
24
- | `@fun-xyz/fiat-contract/routing` | zero deps | the routing table and routing quote: `FiatRoutingTableQuery`, `FiatRoutingTableResponse`, `FiatRoutingQuoteRequest`, both routes' error bodies, and `ROUTING_ENDPOINTS` | **production frontend** + backend |
25
- | `@fun-xyz/fiat-contract` | 47.6 KB, needs zod | the above + 77 zod schemas + assertions + 18 fixtures | tests, and backend dev/test guards |
26
-
27
- `./table` is not a micro-optimisation. Terminality is table data a **shipped** client must read
28
- (litmus rule 3 — clients never infer it), and Metro has no cross-module tree-shaking on by default,
29
- so importing `isTerminal` from the root would ship zod and all 18 fixtures into a React Native
30
- bundle. Two CI jobs hold that line: `consumer` asserts requiring `./table` never loads zod into the
31
- process, and `metro` bundles `./table` with real Metro — in **both** package-exports modes, since
32
- Metro before RN 0.79 ignores `exports` entirely — then greps the emitted bundle for zod, fixtures and
33
- schemas and executes it.
34
-
35
- Source of truth: [Fiat Client Contract](https://app.notion.com/p/3b9fc3b2a002815eb270fa4c818268cc)
36
- (§The fiat step response · §Conformance package · §split `InputSpec` — ACCEPTED) and
37
- [Fiat Frontend — State Machine & Screen Map](https://app.notion.com/p/3bbfc3b2a00281c994c2cebd17b1d6d3)
38
- (✅ Decisions · per-screen State details · Event bindings per flow state), plus
39
- [Fiat KYC — User Flow & API Interfaces](https://app.notion.com/p/3cefc3b2a00281c88e7fe771f0c64332)
40
- for quote-bound KYC states and endpoints, and
41
- [Fiat Routing Engine — Provider Selection, Ranking & Commit](https://app.notion.com/p/3d1fc3b2a00281f2b604c20869ac420a)
42
- for quote-screen limits, provider auth channels, and blocked reasons.
43
- Tracking: [Headless Fiat Onramp](https://linear.app/funxyz/project/headless-fiat-onramp-0147f4102399) ·
44
- this package is [ENG-5268](https://linear.app/funxyz/issue/ENG-5268).
45
-
46
- ## The litmus rules
47
-
48
- 1. **Errors are fields, never states.** Every fallible state carries `error?: FailureReason`.
49
- Stay-on-screen ⇒ an error field. Change-screen ⇒ a different state (session expiry just returns
50
- a `SESSION_AUTH` step response — there is no error routing table).
51
- 2. **`params` = server literals · `inputs` = collected specs · `expects` = injected surface
52
- results.** `body = {…params, …collected(inputs), …injected(expects)}`; a key collision across
53
- the three is a contract violation, not last-write-wins. zod rejects a `FieldSpec` hiding in
54
- `params`, so the old double-duty bug is unrepresentable.
55
- 3. **Terminality comes from the table.** `terminal` is enumerated per state entry — never inferred
56
- from `transitions.length`. `KYC ON_HOLD` carries `transitions: []` and is **not** terminal.
57
- `ORDER{CREATED}` terminality rides `status ∈ TERMINAL_ORDER_STATUSES`, and a terminal status may
58
- still carry a recovery CTA (`FAILED` + retryable `failureReason`).
59
- 4. **`SUBMIT` is a user-fired request, not a POST.** The harness parses the verb off the endpoint
60
- string; `GET /fiat/orders/:id` under `SUBMIT` is legal.
61
- 5. **Fixtures stay synthetic.** `q_8f2`, `o_31c`, `eyJ…`, `"…"` — never paste a real session token,
62
- bank field, or PII value into a fixture. Redaction applies to fixtures too.
63
- 6. **Surface kind names the renderer; provider selects the adapter.** Sumsub capture is
64
- `{ kind: 'KYC_SDK', provider: 'SUMSUB' }`. It is not `URL_EMBED`: the client mounts an SDK,
65
- not a URL or iframe.
66
- 7. **Quote-screen bounds are explicit exact-money strings.** `QUOTE.limits` carries the bounding
67
- minimum/maximum plus the exact `serviceableRanges` when a routing set has gaps; clients do not
68
- infer capacity from provider metadata or floating point.
69
- 8. **Provider auth is capability-shaped.** SMS uses `SMS_OTP`; provider-owned auth uses
70
- `PROVIDER_RENDERED` with an optional `AUTH_COMPONENT` surface rather than provider-specific channels.
71
- 9. **KYC SDK refresh is a transition.** `KYC{CAPTURE}` may offer `refresh_sdk_token` to
72
- `POST /fiat/kyc/sdk-token`; a transition-following client does not invent an auxiliary endpoint call.
73
- 10. **SDK launch is not eligibility authority.** A `KYC_SDK_RESULT` report injects either
74
- `{outcome: 'COMPLETED'}` or `{outcome: 'FAILED', errorType}`. `errorType` is opaque, and raw
75
- messages/errors are excluded. The backend must still read the provider's authoritative state.
76
- 11. **Client-executed delivery is current-session-only.** A provider-owned surface may declare a
77
- `CLIENT_EXECUTED` delivery with `source: 'CURRENT_SESSION_INPUTS'` and a value-free `allowedFieldIds`
78
- allowlist. The delivery shape cannot request or contain backend-stored KYC values.
79
- 12. **Capability skew is explicit.** `BLOCKED{reason: 'CLIENT_UPGRADE_REQUIRED'}` means every
80
- otherwise-viable route needs a client capability absent from the handshake. It is not a provider
81
- decline and should render an upgrade path rather than generic retry copy.
82
- 13. **Providerless is terminal-routing-only.** `FiatStepResponse.provider` may be absent only for
83
- `BLOCKED`, including `ALL_PROVIDERS_DECLINED` when routing selected no provider. Every other state
84
- remains provider-bound and requires `provider`; provider-specific blocked responses may keep it.
85
- 14. **Path commitment is not a quote.** A response may carry `routingSessionRef` while pricing is
86
- legitimately deferred for provider auth or activation. Transitions echo that opaque reference in
87
- `params`; clients submit it unchanged. `Quote.quoteRef` remains required whenever a real `Quote`
88
- is present, and PAY must never be exposed without real current economics.
89
- 15. **KYC may precede pricing.** Provider auth or activation may legitimately defer pricing, so a
90
- KYC state may omit `quote`. A real `Quote` still requires `quoteRef`, and PAY is never quote-less.
91
- 16. **Correction text never decides retry.** A correctable provider rejection returns
92
- `KYC{CAPTURE}` and may carry `correctionReason` for display. Clients decide that retry is allowed
93
- from the state and its transitions; provider-authored text is never a branch key.
94
- 17. **Prepared payment is inert until promotion.** `FiatStepResponse.preparedPayment` may warm a
95
- provider-owned payment surface while auth or KYC continues, but its `CLIENT_SURFACE` transition
96
- is not active yet. A client exposes it only after a later response makes the same `quoteRef`
97
- executable; the prepared surface provider must match the response provider.
98
- 18. **Review duration sets the wait.** `KYC{NO_ACTION_REQUIRED, IN_REVIEW}` may carry `review`. `BRIEF`
99
- means the client keeps the buyer on the current screen with a loading state and polls, then shows
100
- the in-review screen if nothing changes within `holdMs`; `EXTENDED` or absent shows it at once.
101
-
102
- ## Provider-owned flows
103
-
104
- A provider can run its own flow instead of the shared step machine. `POST /fiat/quote` still routes
105
- and prices. When the request's `handoffs` lists the winning provider, the response carries
106
- `handoff: { provider }` and no transitions. The client shows that provider's `CHECKOUT` documents
107
- from `PROVIDER_CHECKOUT_DOCUMENTS`, records them with `POST /fiat/terms` on Continue, and then calls
108
- `POST /fiat/next`. The schema refuses a handoff on any state but `QUOTE`, a
109
- handoff to a provider other than the response's own, and a handoff that still offers transitions.
110
-
111
- **Terms (`./terms`).** Every provider records acceptances through the platform `POST /fiat/terms`
112
- (`FIAT_TERMS_ENDPOINT`). A `TermsDocument` has an `id`, a `kind`
113
- (`PROVIDER_TERMS`, `FUN_KYC_COLLECTION`, `PROVIDER_KYC_SHARING`), a `stage` (`CHECKOUT` or
114
- `KYC`), an opaque `version` and `contentDigest`, and at least one `https` link. `FiatTermsRequest` is
115
- `{ provider, acceptances: [{ documentId, version, contentDigest, acceptedAt }] }`, each document at
116
- most once; `FiatTermsResponse` is `{ recorded }`, the recorded document ids. A fault is a
117
- `FiatTermsErrorBody`: the shared `errorCode`, `errorMsg` and `reqId`, plus `reason` (`STALE_TERMS`,
118
- `INVALID_REQUEST`, `RATE_LIMITED`, `PROVIDER_UNAVAILABLE`) and `recovery`.
119
-
120
- The package publishes every document as a constant, so the client and the backend read the same
121
- text. `PROVIDER_CHECKOUT_DOCUMENTS` maps each provider to its current `CHECKOUT` documents.
122
- `FUN_KYC_CONSENT_DOCUMENTS` is Fun's KYC consent, one digest per `FunKycConsentLocale`.
123
- `PUBLISHED_TERMS_DOCUMENTS` is every version and locale ever published. Every published version
124
- stays valid: the backend refuses only an unknown version, a wrong digest, or an `acceptedAt` older
125
- than 5 minutes. A repeat of a version the login already holds writes nothing and returns the ids.
126
-
127
- **Routing table (`./routing`).** `ROUTING_ENDPOINTS.table` (`POST /fiat/routing/table`) takes a
128
- `FiatRoutingTableRequest` body and answers,
129
- for each requested method, every amount interval and its providers best first, each with `next`
130
- (`READY`, `AUTH`, `DECLARATIVE_KYC`, `DOCUMENTARY_KYC`, `PENDING_REVIEW`) and `visibility`. The
131
- client shows min, max, provider and the Continue label for an amount with no call. A method with no
132
- interval may carry `unavailableReason`, which is not the step response's `BlockedReason`:
133
- `USER_LIMIT`, `KYC_REJECTED`, `PROVIDER_OUTAGE`, or `NOT_SERVED` when every provider was ruled out
134
- for reasons that depend on neither the buyer nor provider health (it does not offer the corridor,
135
- currency, method or asset, or config has not enabled it). An empty method carries no reason when the
136
- cause is unknown. Refetch the table at `expiresAt`, on `refreshLimits: true`, and after auth, KYC or
137
- a `REQUOTE`. The schemas hold the table's invariants: each method once, sorted, non-overlapping
138
- intervals, at least one provider each and none twice, and a reason only on an empty method.
139
-
140
- `ROUTING_ENDPOINTS.table` (`POST /fiat/routing/table`) accepts `FiatRoutingTableRequest`:
141
- `cryptoCurrencyCode`, `chainId`, `country`, optional `region` (required for US), `methods` (array),
142
- optional `fiatCurrencyCode` (default `USD`), and optional `providers`.
143
- See [`FiatRoutingTableMoonPayInputs`](src/routing.ts) for MoonPay credential handling.
144
- Blank tokens, malformed inputs and unknown keys return 400: omit unavailable credentials and
145
- deploy backend support before sending new provider keys.
146
- `GET /fiat/routing/table` is deprecated but still works without provider inputs.
147
-
148
- `ROUTING_ENDPOINTS.quote` (`POST /fiat/routing/quote`) takes the `POST /fiat/quote` body
149
- (`FiatRoutingQuoteTerms`), plus one of two forms:
150
-
151
- - `providers`: the interval's providers, best first. The backend prices them in order, falls
152
- through on the refusals marked "next provider" below, and answers the first that prices or the
153
- last provider's refusal.
154
- - `provider`: one provider only. The client falls through itself.
155
-
156
- Routing quotes may include `routingOverrides: { providers: [...] }` with the host’s full allowlist.
157
- The selected `provider` or ordered `providers` must be a subset. The server preserves the allowlist
158
- through later KYC rerouting; the amount-specific candidate list alone does not restrict rediscovery.
159
- Omitting the field preserves existing behavior. An empty allowlist permits no quote candidate.
160
-
161
- It answers the same `FiatStepResponse`, whose `provider` names the one that priced. A refusal is a
162
- `FiatRoutingQuoteErrorBody`, and it decides whether the next provider may still price:
163
-
164
- | Status | `errorCode` | Then |
165
- | --- | --- | --- |
166
- | 404 | `FiatNoRouteError`, `reason` `NO_CANDIDATE`, `PROVIDER_DECLINED`, `PROVIDER_OUTAGE` or `KYC_REJECTED` | next provider |
167
- | 400 | `FiatNoRouteError`, `reason: USER_LIMIT`, `code: LIMITS_EXCEEDED`, `recovery: REQUOTE` | next provider |
168
- | 400 | `FiatAmountBelowMinimumError` (`minFiatAmount`) or `FiatAmountAboveMaximumError` (`maxFiatAmount`) | next provider |
169
- | 400 | `InvalidParameterError`: a bad request, an asset Fun cannot deliver, or no verified email | stop |
170
- | 401, 5xx | any other: a missing or invalid identity assertion, or a server error | stop |
171
-
172
- Every fall-through refusal is that provider's alone, because each attempt prices only one provider:
173
- `KYC_REJECTED` there means that provider refused the buyer's identity, not every provider. With no
174
- provider left in the interval, refetch the table. The table route refuses with a
175
- `FiatRoutingTableErrorBody`: a 429 `TooManyRequestsError` with `retryAfterSeconds` when the
176
- per-login budget is spent, or a 400 or 5xx as above. The quote route has no rate limit of its own.
177
-
178
- Both routes take geo under the `POST /fiat/quote` rules: a known `CountryCode`, a `UsStateCode`
179
- region for a US buyer, and an empty `region` or `ip` read as absent. The quote route's `geo` is the
180
- Fun geo endpoint's response forwarded as is. The request schemas are strict like every schema here,
181
- so a client sends only the declared keys and no blank strings. `provider` and each `providers`
182
- entry are one of the five providers the backend routes (`RoutingProvider`), `providers` with no
183
- duplicates. The quote route is temporary: `POST /fiat/next` replaces it for each provider that
184
- moves there.
185
-
186
- **MoonPay (`./moonpay`).** MoonPay runs on the shared `POST /fiat/next` (`MOONPAY_ENDPOINTS.next`).
187
- Every `/next` body is a `FiatNextRequest`: `provider`, `geo` (a `FiatGeo`, the geo endpoint's
188
- response), and the provider's own request, which names its `action`. The orchestrator reads
189
- `provider` and `geo`; the provider's action schema reads the rest. MoonPay's body is a
190
- `MoonPayNextRequest`, and every MoonPay request also carries the context `checkout` and, after
191
- `connect`, `credentials` (`customerId`, `accessToken`).
192
-
193
- Each `MoonPayAction` has one name. A response names the next action in `next` and carries what the
194
- client needs; the client's request names it in `action` and carries the result:
195
-
196
- | Action | Next action carries | Request carries | A repeat |
197
- | --- | --- | --- | --- |
198
- | `observe` | no next action of its own: the answer is the current next action | nothing | writes nothing |
199
- | `consent` | `documents` (at least one, unique ids) | `acceptances`, the `POST /fiat/terms` items | writes nothing new |
200
- | `connect` | `sessionToken`, `quoteInput`, `resetConnection?` (`true` when the device's MoonPay connection is another buyer's) | `customerId`, `accessToken` | rebinds the same customer |
201
- | `kyc` | `fields`, `fieldErrors?` (each naming a field in `fields`, with `code?` `PHONE_IN_USE` on `PHONE_NUMBER` or `TAX_ID_IN_USE` on `TAX_IDENTIFIER` when another MoonPay customer holds the value) | `credentials`, `values` keyed by `KycFieldId` (no form id) | drops values MoonPay no longer asks for |
202
- | `wait` | `retryAfterMs` (at most 60 s) | no request: the client sends `observe` after the delay | |
203
- | `order` | `orderId`, `quoteInput` | `orderId`, `quotedAmount`, `transactionId?` | returns the recorded order |
204
-
205
- Every response is the next action, `done`, or `refused` (`MoonPayRefused`), and
206
- `MoonPayResponseFor` maps each request action to its union. `observe`, `consent`, `connect` and `kyc`
207
- answer a `MoonPayStepResponse`: any `MoonPayNextAction`, or `refused` with `reason` (`NOT_ELIGIBLE`,
208
- `DOCUMENTS_REQUIRED`, `FINAL_REJECTION`, `CUSTOMER_MISMATCH`) and `recovery: REQUOTE | NONE`.
209
-
210
- `order` runs after every charge attempt, a failed one too, and answers a `MoonPayOrderResponse`:
211
- `done` with `order`, the `GET /fiat/orders/:orderId` response; `order` again while MoonPay does not
212
- list the transaction yet; or `refused` with `reason` (`CUSTOMER_MISMATCH`, `WALLET_MISMATCH`,
213
- `UNRECORDABLE`) and `recovery: NONE`. `transactionId` is optional because a failed charge may have
214
- none; without it the backend records the failed charges MoonPay lists for `orderId`. `quotedAmount`
215
- is the fiat amount the device quote showed. The order records the body's `geo.alpha2` as its country.
216
- A failed charge answers `done` with the order in `FAILED`, and the client requotes for a new `orderId`.
217
-
218
- A first-time buyer goes `observe` → `consent` → `connect` → `kyc` → `wait` → `observe` → `order` →
219
- `done`; a returning buyer `observe` → `connect` → `order` → `done`. Both walks are recorded in
220
- `test/fixtures/moonpay-next/`.
221
-
222
- A fault is a 4xx or 5xx with a `MoonPayErrorBody`: the shared `errorCode`, `errorMsg` and `reqId`,
223
- plus `reason` and `recovery`. The reasons are `SESSION_BUDGET_SPENT`, `RATE_LIMITED`,
224
- `PROVIDER_UNAVAILABLE` (MoonPay is down), `KYC_PROVIDER_UNAVAILABLE` (Sumsub is down),
225
- `SERVICE_UNAVAILABLE` (one of Fun's own stores is down) and `INVALID_REQUEST`. The recoveries are
226
- `RETRY` (send the same request again), `REQUOTE`, or `NONE`. A field error is a `kyc`
227
- next action, not a fault. The zod schemas (`MoonPay*Schema`, `FiatGeoSchema`, `FiatNextRequestSchema`,
228
- `TermsDocumentSchema`, `FiatTerms*Schema`) are exported from the root only.
229
-
230
- ## KYC SDK hints, results, and client delivery
231
-
232
- `KYC_SDK` is a dedicated `Surface` union member. Its optional
233
- `preferredDocuments.IDENTITY` contains the exact adapter input needed to bias document capture:
234
- the identity-vendor `idDocType` plus its ISO alpha-3 `country`. The hint changes presentation only;
235
- it does not establish that the document is accepted or available.
236
-
237
- When `report.result` is `{type: 'KYC_SDK_RESULT', bodyKey: 'result'}`, the harness injects a
238
- `KycSdkResultReport` under that body key. Completion means the SDK launch completed, not that KYC passed.
239
- Failure exposes only the provider's opaque `errorType` (for example `Unauthorized`), never a raw
240
- error object or message.
241
-
242
- `surface.delivery` describes a client-side forwarding boundary on a provider-owned surface, not
243
- transport mechanics. The selected provider adapter may forward only the declared `allowedFieldIds` that the user entered during the
244
- current mounted session. The schema fixes the source to `CURRENT_SESSION_INPUTS`, requires a unique
245
- non-empty field allowlist, and contains no values. Provider-specific submission mechanics remain
246
- adapter-owned and are intentionally unresolved by this provider-neutral contract.
247
-
248
- “Declarative KYC collection” means the backend sends a `FormDescriptor` listing canonical field
249
- IDs, input kinds, labels, validation, and select options. The frontend renders that description,
250
- collects values, and submits them through the transition's single `FORM_VALUES` input; it does not
251
- hard-code a separate screen or endpoint for source of funds, occupation, purpose, nationality,
252
- country of birth, employment status, or phone. Field IDs and type-specific properties are closed
253
- unions, so misspelled IDs and impossible combinations such as `options` on a `TEXT` field fail
254
- validation.
255
-
256
- ## Versioning — the package version IS the table version
257
-
258
- `TABLE_VERSION` (exported from `src/table.ts`) is derived from `package.json#version` at build
259
- time — a version bump is one edit, in package.json, and the two can never drift. A test asserts
260
- the wiring still resolves to the package version.
261
- That version rides the capability handshake (`supportedProviders` / `supportedSurfaces` /
262
- `supportedStepKinds` + table version), which is how BE↔FE skew stays explicit and designed-for:
263
- the server never routes a flow into a state kind the installed SDK didn't declare.
264
-
265
- Starting at **0.1.0**. Bump the minor for additive vocabulary (a new field, a new fixture); bump the
266
- major when an existing shape changes meaning. Until 1.0 the contract is MVP-beta: renames and
267
- removals also ride a minor, with no deprecated aliases kept — consumers pin and migrate in one step.
268
-
269
- ## How each repo consumes it
270
-
271
- **`fun-backend`** — adapters compile their provider's real flow into this state machine.
272
-
273
- ```ts
274
- import { assertFiatStepResponse, assertLegalEmission, walkTable } from '@fun-xyz/fiat-contract';
275
-
276
- assertLegalEmission(state, transitions); // per emission: adapter conformance
277
- assertFiatStepResponse(outgoing); // outgoing step-response validation in dev/test
278
- const owed = walkTable((entry) => entry.allowedTransitions); // what the adapter must emit
279
- ```
280
-
281
- Its own suites: adapter conformance (fixture-driven + property-generated states), outgoing step-response
282
- validation, and the scheduled provider-sandbox drift run diffed against `src/fixtures`.
283
-
284
- **`connect-core`** — the harness obeys `transitions` for sequencing and owns rendering.
285
-
286
- ```ts
287
- import { FIXTURES, loadFixture, walkTable } from '@fun-xyz/fiat-contract';
288
-
289
- walkTable((entry) => expect(computePage(entry.key)).toBeDefined()); // exhaustive resolver walk
290
- FIXTURES.forEach(({ id }) => renderCold(loadFixture(id))); // stale-rule survival
291
- ```
292
-
293
- Its own suites: exhaustive `computePage` table-walk, fixture-driven cold-render tests, harness units
294
- (any-state handling, same-state error re-entry retains form values, one-live-response focus gating,
295
- idempotency-key reuse).
296
-
297
- ## Usage
298
-
299
- Everything below is compiled against the packed tarball in CI (`scripts/check-readme-examples.sh`),
300
- so these examples cannot drift from the API.
301
-
302
- ### Production: a backend route handler
303
-
304
- The backend *builds* step responses, so its production use is entirely compile-time — the types are the
305
- verification. Runtime assertions stay behind a dev/test guard.
306
-
307
- ```ts
308
- import type { FlowState, FiatStepResponse, Transition } from '@fun-xyz/fiat-contract/types';
309
-
310
- export async function createOrder(quoteRef: string): Promise<FiatStepResponse> {
311
- const state: FlowState = {
312
- kind: 'PAYMENT',
313
- phase: 'INSTRUCT',
314
- instructions: { kind: 'BANK_FIELDS', fields: await beneficiaryFields(), expiresAt },
315
- };
316
-
317
- const transitions: Transition[] = [
318
- { id: 'confirm_paid', mode: 'SUBMIT', endpoint: `POST /fiat/orders/${orderId}/confirm-payment` },
319
- // endpoint is a bounded union: `POST /fiat/orders/${string}/confirm-paymnt` is a compile error,
320
- // and so is any path outside the documented /fiat/* surface
321
- ];
322
-
323
- if (!isProduction) {
324
- const { assertLegalEmission } = await import('@fun-xyz/fiat-contract');
325
- assertLegalEmission(state, transitions); // dev/test only — never on the hot path
326
- }
327
-
328
- return { state, provider: 'TRANSAK', transitions };
329
- }
330
- ```
331
-
332
- What the types buy at compile time: a state kind that isn't in the union won't type, a transition
333
- mode/shape mismatch won't type, and — since `FiatEndpoint` is a bounded union — neither will a
334
- typo'd endpoint. No runtime cost.
335
-
336
- ### Production: a frontend screen
337
-
338
- The client narrows on the state and reads terminality from the table. Both imports are
339
- production-safe: types erase, `./table` is 13.8 KB with no zod.
340
-
341
- ```ts
342
- import { isTerminal, stateKey } from '@fun-xyz/fiat-contract/table';
343
- import type { FiatStepResponse } from '@fun-xyz/fiat-contract/types';
344
-
345
- export function FiatScreen({ stepResponse }: { stepResponse: FiatStepResponse }) {
346
- const page = computePage(stateKey(stepResponse.state), clientLocal); // client owns state → screen
347
- const done = isTerminal(stepResponse.state); // table data, never inferred
348
-
349
- if (stepResponse.state.kind === 'PAYMENT' && stepResponse.state.phase === 'INSTRUCT') {
350
- return render(page, stepResponse.state.instructions); // narrowed: instructions exists here
351
- }
352
- if (stepResponse.state.kind === 'ORDER' && stepResponse.state.phase === 'CREATED') {
353
- return render(page, { status: stepResponse.state.status, done });
354
- }
355
- return render(page, stepResponse.state);
356
- }
357
- ```
358
-
359
- `isTerminal` is the whole reason `./table` exists as a runtime entry: `KYC ON_HOLD` carries
360
- `transitions: []` and is **not** terminal, while `ORDER{CREATED, SETTLED}` is — no client may
361
- re-derive that rule locally.
362
-
363
- ### Production: the transitions loop
364
-
365
- ```ts
366
- import type { FiatStepResponse, Transition } from '@fun-xyz/fiat-contract/types';
367
-
368
- function useTransitions(stepResponse: FiatStepResponse) {
369
- return {
370
- ctas: stepResponse.transitions.filter((t) => t.mode === 'SUBMIT'), // render buttons
371
- poll: stepResponse.transitions.find((t) => t.mode === 'AWAIT'), // harness schedules
372
- surface: stepResponse.transitions.find((t) => t.mode === 'CLIENT_SURFACE'), // harness mounts
373
- };
374
- }
375
-
376
- function bodyFor(t: Transition, collected: Record<string, unknown>, surface?: Record<string, unknown>) {
377
- if (t.mode === 'SUBMIT') return { ...t.params, ...collected }; // verb parsed from t.endpoint
378
- if (t.mode === 'CLIENT_SURFACE') {
379
- const injected = Object.fromEntries((t.report.expects ?? []).map((k) => [k, surface?.[k]]));
380
- return { ...t.report.params, ...injected };
381
- }
382
- return { ...t.poll.params };
383
- }
384
- ```
385
-
386
- Screens never inspect the array themselves; they receive `ctas` and bind labels
387
- (`label(t.id) ?? t.labelFallback` — the contract carries no display copy). A key colliding across
388
- `params` / `inputs` / `expects` is a contract violation, not last-write-wins.
389
-
390
- ## Testing against it
391
-
392
- These import from the root, which carries zod. Test-time only.
393
-
394
- ### Validate a step response at the boundary
395
-
396
- `assertFiatStepResponse` parses and returns a typed step response, or throws `ContractViolation`
397
- listing every problem. Use it on the way out of `fun-backend` (dev/test) and on the way in to
398
- `connect-core` tests.
399
-
400
- ```ts
401
- import { assertFiatStepResponse, ContractViolation } from '@fun-xyz/fiat-contract';
402
-
403
- try {
404
- const stepResponse = assertFiatStepResponse(await res.json());
405
- // ^? FiatStepResponse — state is a narrowable discriminated union from here on
406
- if (stepResponse.state.kind === 'PAYMENT' && stepResponse.state.phase === 'INSTRUCT') {
407
- render(stepResponse.state.instructions); // narrowed: instructions exists, quote does not
408
- }
409
- } catch (err) {
410
- if (err instanceof ContractViolation) console.error(err.issues); // ['state.quote: Required', …]
411
- throw err;
412
- }
413
- ```
414
-
415
- ### Assert an emission is legal (backend adapter conformance)
416
-
417
- Shape validity is not sequence validity. `assertLegalEmission` judges `(state, transitions)` against
418
- the table: is each transition in this state's legal set, does a terminal state carry none, does a
419
- `CLIENT_SURFACE` transition have a Surface in state, do `params`/`inputs`/`expects` collide.
420
-
421
- ```ts
422
- import { assertLegalEmission, checkLegalEmission } from '@fun-xyz/fiat-contract';
423
-
424
- // Throwing form — use in adapter unit tests
425
- assertLegalEmission(
426
- { kind: 'SESSION_AUTH', channel: 'EMAIL_OTP' },
427
- [{
428
- id: 'verify',
429
- mode: 'SUBMIT',
430
- endpoint: 'POST /fiat/session/verify',
431
- params: { quoteRef: 'q_8f2' }, // server literal, spread verbatim
432
- inputs: { code: { type: 'TEXT', length: 6 } }, // spec the client collects
433
- }],
434
- );
435
-
436
- // Non-throwing form — use when you want to report in bulk across many generated states
437
- const { issues, unjudgeable } = checkLegalEmission(state, transitions);
438
- if (!unjudgeable && issues.length) report(issues);
439
- ```
440
-
441
- `unjudgeable` is `true` only for states the docs publish no transition set for (`FUN_AUTH`) — it
442
- means "cannot judge", never "passed".
443
-
444
- ### Walk the table exhaustively (frontend resolver coverage)
445
-
446
- The table is data, so a runtime walk proves every state resolves to a screen — stronger than TS
447
- exhaustiveness alone, because it also fails when a *new* state is added to the contract.
448
-
449
- ```ts
450
- import { assertFixture, walkTable, isTerminal, TRANSITION_TABLE } from '@fun-xyz/fiat-contract';
451
-
452
- it('every contract state resolves to a screen', () => {
453
- walkTable((entry) => {
454
- expect(computePage(entry.key)).toBeDefined();
455
- });
456
- });
457
-
458
- // Terminality is table data — never `transitions.length === 0`
459
- isTerminal(assertFixture('screen-10-kyc-on-hold').stepResponse.state); // false: empty, not over
460
- isTerminal({ kind: 'ORDER', phase: 'CREATED', status: 'SETTLED' }); // true
461
- isTerminal({ kind: 'ORDER', phase: 'CREATED', status: 'PROCESSING' }); // false
462
-
463
- TRANSITION_TABLE['PAYMENT/INSTRUCT'].mayReturn; // ['ORDER/CREATED']
464
- ```
465
-
466
- ### Render every fixture cold (stale-rule survival)
467
-
468
- Any call may return any state, so every screen must render from a cold step response with no
469
- prior context. The fixtures are the FE doc's own responses, so this is a test against the spec.
470
-
471
- ```ts
472
- import { FIXTURES, loadFixture, assertFixture } from '@fun-xyz/fiat-contract';
473
-
474
- FIXTURES.forEach(({ id, stateKey, docRef }) => {
475
- it(`${id} renders cold (${docRef})`, () => {
476
- const { stepResponse } = assertFixture(id); // validated + emission-legality checked
477
- expect(() => renderCold(stepResponse)).not.toThrow();
478
- expect(computePage(stateKey)).toBeDefined();
479
- });
480
- });
481
-
482
- loadFixture('screen-10-kyc-on-hold'); // raw JSON, fresh deep copy, `unknown` — validate before use
483
- ```
484
-
485
- ### Use a schema directly
486
-
487
- All 77 schemas are exported when you need to validate a fragment rather than a whole step response.
488
- They are typed `z.ZodType<T>`, so you get `.parse` / `.safeParse` / `.optional()` — not `.shape` or
489
- `.extend`, deliberately.
490
-
491
- ```ts
492
- import { FlowStateSchema, QuoteSchema, TransitionSchema } from '@fun-xyz/fiat-contract';
493
-
494
- const quote = QuoteSchema.parse(row.quote_json);
495
- const result = FlowStateSchema.safeParse(input);
496
- if (!result.success) log(result.error.issues);
497
- void TransitionSchema;
498
- ```
499
-
500
- ### Check the handshake version
501
-
502
- ```ts
503
- import { TABLE_VERSION } from '@fun-xyz/fiat-contract';
504
-
505
- const handshake = {
506
- supportedProviders: ['TRANSAK'],
507
- supportedSurfaces: ['PCI_COMPONENT', 'PAY_SHEET'],
508
- supportedStepKinds: ['QUOTE', 'SESSION_AUTH', 'KYC', 'PAYMENT', 'ORDER', 'BLOCKED'],
509
- tableVersion: TABLE_VERSION, // the package version IS the table version
510
- };
511
- ```
512
-
513
- ## Install
514
-
515
- ```bash
516
- pnpm add -D @fun-xyz/fiat-contract
517
- ```
518
-
519
- ```ts
520
- import type { FiatStepResponse } from '@fun-xyz/fiat-contract/types'; // production, 0 KB
521
- import { isTerminal } from '@fun-xyz/fiat-contract/table'; // production, 13.8 KB, no zod
522
- import { assertFiatStepResponse } from '@fun-xyz/fiat-contract'; // tests only, pulls zod
523
- ```
524
-
525
- Public npm — no `.npmrc`, no token, no registry config. Releases fire from a `v*` tag
526
- (`.github/workflows/release.yml`), which refuses to publish when the tag and `package.json` version
527
- disagree, and no-ops when that version is already published.
528
-
529
- Sourcemaps are excluded from the tarball (`"!dist/**/*.map"` in `files`) — unlike the funkit SDK
530
- packages, which publish theirs on purpose. These declarations carry open-decision commentary that has
531
- no reason to reach consumers. 50.5 kB, 21 files.
532
-
533
- ## How connect-core consumes this
534
-
535
- connect-core **bundles `./table` and `./types` into its own `dist`** rather than shipping them as
536
- resolvable dependencies. One line of build config, not a copy of the code: one authored table, pinned
537
- in connect-core's lockfile, recompiled into its output every build. Copy-pasting the table into
538
- `connect-core/src` is not this, and would defeat the package.
539
-
540
- ```js
541
- // funkit/packages/connect-core/build.config.js — inside the externalize plugin
542
- const BUNDLED_SPECIFIERS = new Set([
543
- '@fun-xyz/fiat-contract/table',
544
- '@fun-xyz/fiat-contract/types',
545
- ]);
546
- build.onResolve({ filter }, (args) =>
547
- BUNDLED_SPECIFIERS.has(args.path)
548
- ? undefined // let esbuild bundle it in
549
- : { external: true, path: args.path }, // everything else stays external
550
- );
551
- ```
552
-
553
- Why bundle rather than depend:
554
-
555
- - **Pins the tested pair.** As a dependency, a partner's install resolves the semver range at *their*
556
- install time, so an SDK tested against table 0.2.1 could run against 0.3.0 in the field. Bundling
557
- compiles `TABLE_VERSION` into the release, which is what the handshake then reports.
558
- - **Metro never sees the subpath**, so the package-exports question (§Packaging) cannot reach a
559
- partner's bundler.
560
-
561
- Consequences:
562
-
563
- - The build exception needs its comment, or it gets deleted as dead config. A test in connect-core
564
- asserts the table inlines and that zod and the fixtures stay out.
565
- - `connect` / `connect-rn` should import the table *from connect-core*, not bundle their own copy
566
- (~14 KB apiece).
567
- - The shipped table version is not readable from a partner's `node_modules` — read the handshake.
568
-
569
- The root entry stays a plain `devDependency` in both repos: test-only, so it never reaches a published
570
- artifact.
571
-
572
- ## Packaging
573
-
574
- Dual CJS + ESM, same shape as `@funkit/fun-relay`, because the two consumers load it differently:
575
-
576
- | Requirement | Source | How it's met |
577
- | --- | --- | --- |
578
- | `require()` must work | `fun-backend/apps/api-server` compiles `module: commonjs` and runs plain node — no bundler | esbuild emits `dist/index.js` (CJS) + `dist/index.mjs` (ESM); `exports` maps `require`/`import`; no `"type": "module"` |
579
- | Zero Node builtins | `connect-core` is React Native — Metro cannot resolve `node:fs` | fixtures are inlined as generated TS data (`src/fixtures/data.ts`), so nothing touches the filesystem; `platform: browser`, every bare import external |
580
- | Subpath imports must resolve without `exports` support | Metro only reads `package.json#exports` from RN 0.79 on, and `@funkit/connect-rn` accepts `react-native: >=0.74` | root compat stubs `table.js` / `types.js` / `moonpay.js` / `terms.js` / `routing.js` (+ `.d.ts`) that re-export `dist/`. Without them Metro fails with *"Unable to resolve module"* — verified, not theorised. Resolvers that do read `exports` never see the stubs |
581
- | Production code must not pull zod or fixtures | `connect-core` ships to React Native, where Metro does not tree-shake unused exports by default | six entry points: `./types` (erased), `./table` (13.8 KB, zero deps), `./moonpay`, `./terms` and `./routing` (zero deps), root (schemas + fixtures, test-time). CI asserts `require('.../table')`, `require('.../moonpay')`, `require('.../terms')` and `require('.../routing')` never load zod |
582
- | `.d.ts` must not lock a zod major | Both repos run `skipLibCheck: true`, which turns a broken declaration into a silent `any` | every exported schema is annotated `z.ZodType<T>`, so declarations name only `z.ZodType`; the structural drift checks stay module-private |
583
-
584
- Declarations come from `tsc --emitDeclarationOnly`; esbuild only emits JS. The fixture `.json` files
585
- remain the verbatim record — `data.ts` is generated from them and CI fails if it drifts.
586
-
587
- ## Scripts
588
-
589
- ```
590
- npm run typecheck # tsc --noEmit, strict; includes the schema↔type mirror assertions
591
- npm test # vitest: fixtures, zod round-trip, table integrity, negative asserts
592
- npm run generate:fixtures # regenerate src/fixtures/data.ts from the .json record
593
- npm run build # tsc declarations + esbuild dual CJS/ESM into dist/
594
- npm run check # typecheck + test
595
-
596
- ./scripts/verify-consumer.sh 3.23.8 pnpm # pack, install, require/import, and typecheck a
597
- # consumer with skipLibCheck OFF — catches packaging
598
- # faults the in-repo suite structurally cannot
599
- ./scripts/check-readme-examples.sh # compile every ```ts block in this README against
600
- # the packed package
601
- ./scripts/verify-metro.sh # bundle ./table with real Metro in both
602
- # package-exports modes; assert no zod/fixtures reach
603
- # the bundle, and that it executes
604
- ```
605
-
606
- ## Dependencies
607
-
608
- zod is an **optional peer**, range `^3.22.0 || ^4.0.0`. Only the root entry needs it; `./table` and
609
- `./types` have no runtime dependency on zod, so an install that never imports the root entry needs no
610
- zod at all.
611
-
612
- | Repo | zod | Notes |
613
- | --- | --- | --- |
614
- | `funkit` (pnpm 9.4) | **3.23.8** (`apps/fits`, `apps/frog`) | `connect-core` declares it explicitly — required, see below |
615
- | `fun-backend` (pnpm 10.16) | **3.25.76** | forced tree-wide by `pnpm.overrides` |
616
-
617
- Neither repo is on zod 4; the `|| ^4.0.0` arm is verified, not required. CI runs the suite and a
618
- packed-tarball consumer check on 3.22.4, 3.23.8, 3.25.76 and 4.4.3. (zod `3.25.0` exactly is
619
- unusable — that release ships no `dist/`; 3.25.1+ is fine.)
620
-
621
- **A consumer importing the root entry must declare zod itself.** The peer being optional means pnpm
622
- installs none by default, so a `test/**` import of the root entry fails with a missing module — loud,
623
- and the reason the peer is optional. When it was a required peer, pnpm instead resolved zod 4 and,
624
- under `dedupe-peer-dependents`, moved funkit's viem onto it, which `abitype`'s `^3 >=3.22.0` peer
625
- rejects.
626
-
627
- Declarations never bake in a zod major: every exported schema is annotated `z.ZodType<T>`. Consumers
628
- get `.parse` / `.safeParse` / `.optional()`, not `.shape` / `.extend` — a contract you validate
629
- against, not compose from.
630
-
631
- ## Open decisions — encoded, not resolved
632
-
633
- Every one of these is marked `// TODO(open-decision): <doc ref>` at the site that encodes it.
634
- The current documented shape is what ships; none of these are settled here.
635
-
636
- | Open item | How 0.1.0 encodes it |
637
- | --- | --- |
638
- | `orderId` placement | Both: optional on `PAYMENT{INSTRUCT}` (FE doc v0) **and** optional beside `state` (contract worked example). One fixture of each. |
639
- | `PENDING_ORDER` removal | Kind ships, with the removal proposal flagged on the type, the table entry, and the fixture. Screen 12 stays frozen. |
640
- | `[OQ7]` failure enumeration | The published `FailureReason` taxonomy only. Expired instructions, partial payment, and per-rail cancel eligibility remain unenumerated; KYC rejection is terminal only for an explicit non-retryable outcome. |
641
- | Pre-order KYC sequencing | KYC states carry their quote; SDK submission reports to `POST /fiat/kyc/capture`; expired SDK credentials refresh through the explicit `POST /fiat/kyc/sdk-token` transition; pending review polls the quote resource. There is no `GET /fiat/kyc`. |
642
- | Card capture report target | Both topologies are legal in the table (`POST /fiat/orders` for capture-then-order; `POST /fiat/orders/:id/surface-result` otherwise) pending the Transak answer. |
643
- | Cancel placement | `cancel` is legal on `PAYMENT{INSTRUCT}` and `ORDER{CREATED}`, marked conditional on the placement decision. |
644
- | `FUN_AUTH` shape | `challenge: Record<string, JsonValue>`; the table entry is `docStatus: 'UNSPECIFIED'`, so `assertLegalEmission` reports it unjudgeable instead of guessing. |
645
- | `statusHistory` element shape | The documented minimum (`{status}`) — no invented timestamps. |
646
- | `QR_IMAGE` instruction | In the union per §The fiat step response, flagged against OQ1's "deliberately not pre-declared". |
647
-
648
- `FUN_AUTH` is the only fixture gap declared in `FIXTURE_COVERAGE_GAPS`; its shape remains owned by the auth spike. Every other state has a recorded step response.
649
-
650
- ## Not decided here — needs a human
651
-
652
- - **Whether `PENDING_ORDER` ships in the types** or waits for the removal decision. It ships
653
- today (flagged everywhere) so the current server shape validates.
654
- - **Repo hosting / org placement.** The docs recommend a standalone repo (option B) or `fun-backend`
655
- (option C) — explicitly **not** funkit. Backend sign-off is pending; this repo is standalone,
656
- which is reversible either way.
@@ -1 +0,0 @@
1
- //# sourceMappingURL=chunk-KIQOUUEZ.mjs.map