@capxul/sdk 0.2.0-alpha.3 → 0.2.0-alpha.5

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 (45) hide show
  1. package/README.md +4 -266
  2. package/dist/InMemoryAuthCacheAdapter-BK-B_ERB.mjs +113 -0
  3. package/dist/InMemoryAuthCacheAdapter-BK-B_ERB.mjs.map +1 -0
  4. package/dist/index.d.mts +1263 -0
  5. package/dist/index.d.mts.map +1 -0
  6. package/dist/index.mjs +4740 -0
  7. package/dist/index.mjs.map +1 -0
  8. package/dist/node/index.d.mts +55 -0
  9. package/dist/node/index.d.mts.map +1 -0
  10. package/dist/node/index.mjs +159 -0
  11. package/dist/node/index.mjs.map +1 -0
  12. package/dist/ports/safe-deployment.d.mts +2 -0
  13. package/dist/ports/safe-deployment.mjs +38 -0
  14. package/dist/ports/safe-deployment.mjs.map +1 -0
  15. package/dist/safe-deployment-Vni46k3t.d.mts +137 -0
  16. package/dist/safe-deployment-Vni46k3t.d.mts.map +1 -0
  17. package/dist/signer-oaYGfjDe.d.mts +142 -0
  18. package/dist/signer-oaYGfjDe.d.mts.map +1 -0
  19. package/package.json +37 -71
  20. package/CHANGELOG.md +0 -256
  21. package/LICENSE +0 -44
  22. package/dist/client-B_Z3ThFO.d.cts +0 -1484
  23. package/dist/client-pMBRFcsz.d.ts +0 -1484
  24. package/dist/client.cjs +0 -4324
  25. package/dist/client.d.cts +0 -6
  26. package/dist/client.d.ts +0 -6
  27. package/dist/client.js +0 -4322
  28. package/dist/errors-CwhCWGxm.d.ts +0 -70
  29. package/dist/errors-rqxuUhQP.d.cts +0 -70
  30. package/dist/errors.cjs +0 -35
  31. package/dist/errors.d.cts +0 -2
  32. package/dist/errors.d.ts +0 -2
  33. package/dist/errors.js +0 -31
  34. package/dist/index.cjs +0 -4626
  35. package/dist/index.d.cts +0 -571
  36. package/dist/index.d.ts +0 -571
  37. package/dist/index.js +0 -4585
  38. package/dist/next-action-CTGl8wpy.d.cts +0 -177
  39. package/dist/next-action-CTGl8wpy.d.ts +0 -177
  40. package/dist/types-Brucpq0Z.d.cts +0 -1191
  41. package/dist/types-V_D7qjxY.d.ts +0 -1191
  42. package/dist/webhooks.cjs +0 -118
  43. package/dist/webhooks.d.cts +0 -33
  44. package/dist/webhooks.d.ts +0 -33
  45. package/dist/webhooks.js +0 -116
package/dist/index.js DELETED
@@ -1,4585 +0,0 @@
1
- import { componentsGeneric, anyApi } from 'convex/server';
2
- import { toSafeSmartAccount } from 'permissionless/accounts';
3
- import { getAddress, parseUnits, createPublicClient, http, encodeFunctionData } from 'viem';
4
- import { entryPoint07Address, createPaymasterClient, createBundlerClient } from 'viem/account-abstraction';
5
- import { baseSepolia } from 'viem/chains';
6
- import { deriveSafeAddress as deriveSafeAddress$1, defaultSafeDeriveConfig } from '@repo/safe-derive';
7
- import { ConvexHttpClient } from 'convex/browser';
8
- import { setup, fromPromise, assign } from 'xstate';
9
- import { privateKeyToAccount, generatePrivateKey } from 'viem/accounts';
10
-
11
- // src/_generated/api.js
12
- var api = anyApi;
13
- componentsGeneric();
14
-
15
- // src/errors.ts
16
- var CapxulError = class extends Error {
17
- code;
18
- details;
19
- operationId;
20
- correlationId;
21
- retryable;
22
- constructor(init) {
23
- super(
24
- init.message,
25
- init.cause !== void 0 ? { cause: init.cause } : void 0
26
- );
27
- this.name = "CapxulError";
28
- this.code = init.code;
29
- this.details = init.details;
30
- this.operationId = init.operationId;
31
- this.correlationId = init.correlationId;
32
- this.retryable = init.retryable;
33
- }
34
- };
35
- function notImplemented(method) {
36
- return new CapxulError({
37
- code: "NOT_IMPLEMENTED",
38
- message: `${method} is not yet implemented in @capxul/sdk (Slice C scaffold).`
39
- });
40
- }
41
- function stub(method) {
42
- return [notImplemented(method), null];
43
- }
44
-
45
- // src/internal/convex-error.ts
46
- function isConvexClientError(error) {
47
- if (typeof error !== "object" || error === null || !("data" in error)) {
48
- return false;
49
- }
50
- const data = error.data;
51
- return typeof data === "object" && data !== null;
52
- }
53
- function fromConvexError(error) {
54
- if (error instanceof CapxulError) {
55
- return error;
56
- }
57
- if (isConvexClientError(error)) {
58
- return new CapxulError({
59
- code: error.data.code ?? "UNKNOWN",
60
- message: error.data.message ?? error.message,
61
- details: error.data.details,
62
- correlationId: error.data.correlationId,
63
- cause: error
64
- });
65
- }
66
- return new CapxulError({
67
- code: "UNKNOWN",
68
- message: error instanceof Error ? error.message : String(error),
69
- cause: error
70
- });
71
- }
72
-
73
- // ../observability/src/try-catch.ts
74
- async function tryCatch(promise) {
75
- try {
76
- return [null, await promise];
77
- } catch (e) {
78
- return [e instanceof Error ? e : new Error(String(e)), null];
79
- }
80
- }
81
-
82
- // ../observability/src/debug-log.ts
83
- function isDevelopmentBuild() {
84
- if (typeof process === "undefined") {
85
- return false;
86
- }
87
- return process.env?.NODE_ENV === "development" || process.env?.NODE_ENV === "test";
88
- }
89
- function debugLog(line) {
90
- if (!isDevelopmentBuild()) return;
91
- if (typeof globalThis !== "undefined" && "window" in globalThis && typeof console?.info === "function") {
92
- console.info(line);
93
- return;
94
- }
95
- if (typeof process !== "undefined" && typeof process.stderr?.write === "function") {
96
- process.stderr.write(`${line}
97
- `);
98
- }
99
- }
100
- function formatDebugValue(value) {
101
- if (value === void 0 || value === "") return "";
102
- if (typeof value === "string") return value;
103
- try {
104
- return JSON.stringify(value);
105
- } catch {
106
- return String(value);
107
- }
108
- }
109
- function track(...args) {
110
- const [name, props] = args;
111
- debugLog(`[TRACK] ${name} ${formatDebugValue(props ?? "")}`);
112
- }
113
- function formatDebugValue2(value) {
114
- if (value === void 0 || value === "") return "";
115
- if (typeof value === "string") return value;
116
- try {
117
- return JSON.stringify(value);
118
- } catch {
119
- return String(value);
120
- }
121
- }
122
- function identify(userId, traits) {
123
- debugLog(`[IDENTIFY] ${userId} ${formatDebugValue2(traits ?? "")}`);
124
- }
125
-
126
- // ../config/src/chain.ts
127
- var CAPXUL_PAYMENTS_ADDRESS = "0xe740ea65521edc9bef0ea75d30b5334711db99f4";
128
- var TEST_USDC_ADDRESS = "0xf09fcbb6df9f8f918e58f9c8ab15a76ade862b77";
129
- var CAPXUL_API_BASE_URL = "https://elated-oyster-269.convex.site";
130
-
131
- // ../config/src/timing.ts
132
- var FLOW_INVOKE_TIMEOUT_MS = 3e4;
133
- var WEBHOOK_FRESHNESS_WINDOW_MS = 5 * 60 * 1e3;
134
-
135
- // ../config/src/errors.ts
136
- var CapxulError2 = class extends Error {
137
- code;
138
- details;
139
- correlationId;
140
- layer;
141
- constructor(code, message, options) {
142
- super(message, options?.cause ? { cause: options.cause } : void 0);
143
- this.code = code;
144
- this.details = options?.details;
145
- this.correlationId = options?.correlationId;
146
- this.layer = options?.layer;
147
- }
148
- };
149
- var Errors = {
150
- notAuthenticated: () => new CapxulError2("NOT_AUTHENTICATED", "Not authenticated"),
151
- profileNotFound: (authUserId) => new CapxulError2("PROFILE_NOT_FOUND", `Profile not found for user ${authUserId}`),
152
- smartAccountMissing: (authUserId) => new CapxulError2("SMART_ACCOUNT_MISSING", `Smart account not provisioned for user ${authUserId}`),
153
- envMissing: (name) => new CapxulError2("ENV_MISSING", `Environment variable ${name} not configured`),
154
- openfortApi: (operation, cause) => new CapxulError2(
155
- "PROVIDER_ERROR",
156
- `Openfort ${operation} failed: ${cause instanceof Error ? cause.message : String(cause)}`,
157
- { cause, details: { provider: "openfort", operation } }
158
- ),
159
- shieldApi: (status, detail) => new CapxulError2(
160
- "PROVIDER_ERROR",
161
- `Shield API error (${status}): ${detail}`,
162
- { details: { provider: "shield", status } }
163
- ),
164
- providerError: (provider, operation, cause) => (
165
- // Public `message` is redacted to a fixed shape so provider-side
166
- // exception text never leaks to the client. The original `cause`
167
- // is preserved on `Error.cause` for server-side debugging via
168
- // observability sinks (Sentry, console traces).
169
- new CapxulError2(
170
- "PROVIDER_ERROR",
171
- `Provider error: ${provider} ${operation}`,
172
- { cause, details: { provider, operation } }
173
- )
174
- ),
175
- invalidInput: (field, reason) => new CapxulError2(
176
- "INVALID_INPUT",
177
- `Invalid ${field}: ${reason}`,
178
- { details: { field, reason } }
179
- ),
180
- playerNotFound: (playerId) => new CapxulError2(
181
- "PLAYER_NOT_FOUND",
182
- playerId ? `Openfort player ${playerId} not found` : "Openfort player not found"
183
- ),
184
- accountNotFound: (accountId) => new CapxulError2(
185
- "ACCOUNT_NOT_FOUND",
186
- accountId ? `Openfort account ${accountId} not found` : "Openfort smart account not found"
187
- ),
188
- invalidRecipient: (reason) => new CapxulError2("INVALID_RECIPIENT", reason),
189
- permissionDenied: (reason = "Permission denied") => new CapxulError2("PERMISSION_DENIED", reason),
190
- notFound: (resource, id) => new CapxulError2(
191
- "NOT_FOUND",
192
- id ? `${resource} ${id} not found` : `${resource} not found`
193
- ),
194
- idempotencyConflict: (details) => new CapxulError2(
195
- "IDEMPOTENCY_CONFLICT",
196
- "Idempotency key was already used for a different request",
197
- { details }
198
- ),
199
- emailDeliveryFailed: (detail, details) => new CapxulError2("EMAIL_DELIVERY_FAILED", `Failed to send email: ${detail}`, {
200
- details
201
- }),
202
- rateLimited: (details) => new CapxulError2("RATE_LIMITED", "Request was rate limited", {
203
- details: { ...details }
204
- }),
205
- internalError: (reason) => new CapxulError2("INTERNAL_ERROR", `Internal error: ${reason}`),
206
- /**
207
- * Verification gate. Surfaced when a request hits a verification
208
- * boundary the actor cannot cross under their current state. Two
209
- * variants share this code:
210
- *
211
- * - Rail gate (Withdrawals v1 W2, #465): the resolved
212
- * `external_account.kind` routes to a withdrawal rail (e.g.
213
- * `fiat_offramp`, `card_payout`) that is not yet supported. Carries
214
- * `details.rail` + `details.currentKind`.
215
- * - KYC tier gate (legacy / future): the actor's KYC tier is below
216
- * the required tier. Carries `details.requiredTier`.
217
- *
218
- * Code is shared because both expose the same UX shape ("you cannot
219
- * proceed until verification advances"); the `details.*` keys
220
- * differentiate the route.
221
- */
222
- verificationRequired: (details) => {
223
- const message = "rail" in details ? `Withdrawal rail "${details.rail}" (kind=${details.currentKind}) is not yet supported.` : `Verification tier ${details.requiredTier} is required.`;
224
- return new CapxulError2("VERIFICATION_REQUIRED", message, {
225
- details: { ...details }
226
- });
227
- }
228
- };
229
-
230
- // ../config/src/safe.ts
231
- var SAFE_PROXY_FACTORY = "0x4e1dcf7ad4e460cfd30791ccc4f9c8a4f820ec67";
232
- var SAFE_L2_SINGLETON = "0x29fcb43b46531bca003ddc8fcb67ffe91900c762";
233
- var SAFE_MODULE_SETUP = "0x2dd68b007b46fbe91b9a7c3eda5a7a1063cb5b47";
234
- var SAFE_4337_MODULE = "0x75cf11467937ce3f2f357ce24ffc3dbf8fd5c226";
235
-
236
- // ../config/src/org-roles.ts
237
- function roleKeyFromLabel(label) {
238
- const bytes = new TextEncoder().encode(label);
239
- const hex = Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
240
- return "0x" + hex.padEnd(64, "0");
241
- }
242
- roleKeyFromLabel("OWNER");
243
- roleKeyFromLabel("FINANCE_MANAGER");
244
- roleKeyFromLabel("PAYMENTS_OPERATOR");
245
- async function buildSafeAccount(signer, chain) {
246
- try {
247
- const publicClient = createPublicClient({
248
- chain: baseSepolia,
249
- transport: http(chain.rpcUrl)
250
- });
251
- return await toSafeSmartAccount({
252
- client: publicClient,
253
- entryPoint: { address: entryPoint07Address, version: "0.7" },
254
- version: "1.4.1",
255
- owners: [signer],
256
- saltNonce: computeSaltNonce(signer.address),
257
- safeSingletonAddress: SAFE_L2_SINGLETON,
258
- safeProxyFactoryAddress: SAFE_PROXY_FACTORY,
259
- safeModuleSetupAddress: SAFE_MODULE_SETUP,
260
- safe4337ModuleAddress: SAFE_4337_MODULE,
261
- safeModules: [],
262
- setupTransactions: []
263
- });
264
- } catch (cause) {
265
- throw new CapxulError({
266
- code: "NETWORK_ERROR",
267
- message: cause instanceof Error ? cause.message : String(cause),
268
- cause,
269
- details: { chainId: chain.chainId }
270
- });
271
- }
272
- }
273
- function computeSaltNonce(ownerAddress) {
274
- return BigInt(`0x${ownerAddress.toLowerCase().slice(2).padEnd(64, "0")}`);
275
- }
276
- function deriveSafeAddress(signerAddress) {
277
- return deriveSafeAddress$1(signerAddress, defaultSafeDeriveConfig);
278
- }
279
-
280
- // ../platform-kernel/src/ids.ts
281
- function makePrefixedIdConstructor(prefix, fieldName) {
282
- const re = new RegExp(`^${prefix}_[A-Za-z0-9_\\-]+$`);
283
- return (raw) => {
284
- if (typeof raw !== "string" || !re.test(raw)) {
285
- throw new Error(
286
- `Invalid ${fieldName}: expected string matching ^${prefix}_[A-Za-z0-9_\\-]+$, got ${String(raw)}`
287
- );
288
- }
289
- return raw;
290
- };
291
- }
292
- var toAccountId = makePrefixedIdConstructor(
293
- "acct",
294
- "accountId"
295
- );
296
- var toOrganizationId = makePrefixedIdConstructor("org", "organizationId");
297
- var toMemberId = makePrefixedIdConstructor(
298
- "mb",
299
- "memberId"
300
- );
301
- var toSafeId = makePrefixedIdConstructor(
302
- "safe",
303
- "safeId"
304
- );
305
- var toTreasuryId = makePrefixedIdConstructor(
306
- "try",
307
- "treasuryId"
308
- );
309
- var toApiKeyId = makePrefixedIdConstructor(
310
- "ak",
311
- "apiKeyId"
312
- );
313
- var toOperationId = makePrefixedIdConstructor(
314
- "op",
315
- "operationId"
316
- );
317
- var toCorrelationId = makePrefixedIdConstructor("ctx", "correlationId");
318
- var toKycProfileId = makePrefixedIdConstructor(
319
- "kyc",
320
- "kycProfileId"
321
- );
322
- var toKybProfileId = makePrefixedIdConstructor(
323
- "kyb",
324
- "kybProfileId"
325
- );
326
- var toExternalAccountId = makePrefixedIdConstructor("ext", "externalAccountId");
327
- var toPaymentId = makePrefixedIdConstructor(
328
- "pay",
329
- "paymentId"
330
- );
331
- var toWithdrawalId = makePrefixedIdConstructor(
332
- "wd",
333
- "withdrawalId"
334
- );
335
- var toWebhookEndpointId = makePrefixedIdConstructor("we", "webhookEndpointId");
336
- var toWebhookEventId = makePrefixedIdConstructor("evt", "webhookEventId");
337
- var toSubAccountId = makePrefixedIdConstructor(
338
- "sub",
339
- "subAccountId"
340
- );
341
- var toVirtualAccountId = makePrefixedIdConstructor("va", "virtualAccountId");
342
- var toVirtualCardId = makePrefixedIdConstructor(
343
- "vc",
344
- "virtualCardId"
345
- );
346
- var toTransferId = makePrefixedIdConstructor(
347
- "txfr",
348
- "transferId"
349
- );
350
- var toDocumentId = makePrefixedIdConstructor(
351
- "doc",
352
- "documentId"
353
- );
354
- var toBalanceLedgerEntryId = makePrefixedIdConstructor("bal", "balanceLedgerEntryId");
355
-
356
- // ../platform-kernel/src/value-objects.ts
357
- var PHONE_NUMBER_RE = /^\+[1-9]\d{1,14}$/;
358
- function toPhoneNumber(raw) {
359
- if (typeof raw !== "string" || !PHONE_NUMBER_RE.test(raw)) {
360
- throw new Error(
361
- `Invalid phoneNumber: expected E.164 string matching ^\\+[1-9]\\d{1,14}$, got ${String(raw)}`
362
- );
363
- }
364
- return raw;
365
- }
366
- var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
367
- function toEmail(raw) {
368
- if (typeof raw !== "string") {
369
- throw new Error(
370
- `Invalid email: expected string, got ${String(raw)}`
371
- );
372
- }
373
- const lowered = raw.trim().toLowerCase();
374
- if (!EMAIL_RE.test(lowered)) {
375
- throw new Error(
376
- `Invalid email: expected local@domain.tld, got ${String(raw)}`
377
- );
378
- }
379
- return lowered;
380
- }
381
- var USERNAME_RE = /^[a-z][a-z0-9_-]{2,29}$/;
382
- function toUsername(raw) {
383
- if (typeof raw !== "string") {
384
- throw new Error(
385
- `Invalid username: expected string, got ${String(raw)}`
386
- );
387
- }
388
- const lowered = raw.toLowerCase();
389
- if (!USERNAME_RE.test(lowered)) {
390
- throw new Error(
391
- `Invalid username: expected 3-30 chars, letter-first, [a-z0-9_-], got ${String(raw)}`
392
- );
393
- }
394
- return lowered;
395
- }
396
-
397
- // src/core/external-accounts.ts
398
- function brandExternalAccount(raw) {
399
- return {
400
- ...raw,
401
- id: toExternalAccountId(raw.id),
402
- operation: {
403
- id: toOperationId(raw.operation.id),
404
- status: raw.operation.status,
405
- correlationId: toCorrelationId(raw.operation.correlationId)
406
- }
407
- };
408
- }
409
- function createExternalAccountsClient(config = {}) {
410
- return {
411
- retrieve: async (externalAccountId) => {
412
- if (!config._data) {
413
- return stub(
414
- "externalAccounts.retrieve"
415
- );
416
- }
417
- const [err, raw] = await tryCatch(
418
- config._data.query(api.externalAccounts.queries.retrievePersonal, {
419
- externalAccountId
420
- })
421
- );
422
- if (err) {
423
- return [
424
- fromConvexError(err),
425
- null
426
- ];
427
- }
428
- if (!raw) {
429
- return [
430
- new CapxulError({
431
- code: "NOT_FOUND",
432
- message: `external_account ${externalAccountId} not found`
433
- }),
434
- null
435
- ];
436
- }
437
- return [null, brandExternalAccount(raw)];
438
- },
439
- remove: async (externalAccountId) => {
440
- if (!config._data) {
441
- return stub("externalAccounts.remove");
442
- }
443
- const [err] = await tryCatch(
444
- config._data.mutation(api.externalAccounts.mutations.removePersonal, {
445
- externalAccountId
446
- })
447
- );
448
- if (err) {
449
- return [
450
- fromConvexError(err),
451
- null
452
- ];
453
- }
454
- return [null, void 0];
455
- }
456
- };
457
- }
458
-
459
- // src/core/sub-accounts.ts
460
- function malformedWireError(reason, raw) {
461
- return new CapxulError({
462
- code: "PROVIDER_ERROR",
463
- message: `convex brandSubAccount failed: ${reason}`,
464
- details: {
465
- provider: "convex",
466
- operation: "brandSubAccount",
467
- reason,
468
- // PII discipline (`.claude/rules/posthog.md`): user-authored
469
- // strings on the wire (`name`, `purpose`) are customer-confidential
470
- // — sub-account names like "Q3 Acquisition Reserve" or
471
- // "Vendor ABC payments" must not flow into telemetry. We emit a
472
- // structural keys-only sample via a strict ALLOWLIST so any future
473
- // wire-shape addition (e.g. `recipientEmail`, `tags`) is dropped
474
- // by construction rather than leaked through a denylist gap.
475
- sample: safeSampleShape(raw)
476
- }
477
- });
478
- }
479
- function safeSampleShape(raw) {
480
- if (raw === null || typeof raw !== "object") {
481
- return { type: typeof raw };
482
- }
483
- const r = raw;
484
- const balance = r.balance;
485
- return {
486
- object: typeof r.object === "string" ? r.object : typeof r.object,
487
- idPresent: typeof r.id === "string" && r.id.length > 0,
488
- // First 4 chars only — enough to distinguish "sub_" prefixed IDs
489
- // from accidental other resource IDs without leaking the full ID.
490
- idPrefix: typeof r.id === "string" ? r.id.slice(0, 4) : void 0,
491
- parentKind: r.parent !== null && typeof r.parent === "object" ? r.parent.kind : typeof r.parent,
492
- status: r.status,
493
- hasName: typeof r.name === "string",
494
- hasPurpose: r.purpose !== void 0,
495
- balanceShape: balance !== null && typeof balance === "object" ? Object.keys(balance).sort() : typeof balance,
496
- createdAtType: typeof r.createdAt,
497
- updatedAtType: typeof r.updatedAt
498
- };
499
- }
500
- function isMoneyShape(v) {
501
- if (typeof v !== "object" || v === null) return false;
502
- const m = v;
503
- return typeof m.value === "string" && typeof m.currency === "string";
504
- }
505
- function isParentShape(v) {
506
- if (typeof v !== "object" || v === null) return false;
507
- const p = v;
508
- return (p.kind === "account" || p.kind === "organization") && typeof p.id === "string";
509
- }
510
- function isFiniteNonNegativeInteger(v) {
511
- return typeof v === "number" && Number.isFinite(v) && Number.isInteger(v) && v >= 0;
512
- }
513
- function validateWireSubAccount(raw) {
514
- if (typeof raw !== "object" || raw === null) {
515
- return { ok: false, reason: "not an object" };
516
- }
517
- const r = raw;
518
- if (r.object !== "sub_account") {
519
- return { ok: false, reason: `object must be "sub_account" (got ${String(r.object)})` };
520
- }
521
- if (typeof r.id !== "string" || r.id.length === 0) {
522
- return { ok: false, reason: "id must be a non-empty string" };
523
- }
524
- if (!isParentShape(r.parent)) {
525
- return { ok: false, reason: "parent must be { kind: 'account' | 'organization', id: string }" };
526
- }
527
- if (typeof r.name !== "string") {
528
- return { ok: false, reason: "name must be a string" };
529
- }
530
- if (r.purpose !== void 0 && typeof r.purpose !== "string") {
531
- return { ok: false, reason: "purpose must be a string when present" };
532
- }
533
- if (r.status !== "active" && r.status !== "archived") {
534
- return { ok: false, reason: `status must be "active" | "archived" (got ${String(r.status)})` };
535
- }
536
- if (!isMoneyShape(r.balance)) {
537
- return { ok: false, reason: "balance must be { value: string, currency: string }" };
538
- }
539
- if (!isFiniteNonNegativeInteger(r.createdAt)) {
540
- return { ok: false, reason: "createdAt must be a finite non-negative integer (epoch ms)" };
541
- }
542
- if (r.updatedAt !== void 0 && !isFiniteNonNegativeInteger(r.updatedAt)) {
543
- return { ok: false, reason: "updatedAt must be a finite non-negative integer when present" };
544
- }
545
- return { ok: true, value: r };
546
- }
547
- function brandSubAccount(raw) {
548
- const result = validateWireSubAccount(raw);
549
- if (!result.ok) {
550
- throw malformedWireError(result.reason, raw);
551
- }
552
- const wire = result.value;
553
- return {
554
- object: wire.object,
555
- id: toSubAccountId(wire.id),
556
- parent: wire.parent,
557
- name: wire.name,
558
- ...wire.purpose !== void 0 ? { purpose: wire.purpose } : {},
559
- status: wire.status,
560
- balance: wire.balance,
561
- createdAt: new Date(wire.createdAt).toISOString()
562
- };
563
- }
564
- function tryBrandSubAccount(raw) {
565
- try {
566
- return [null, brandSubAccount(raw)];
567
- } catch (err) {
568
- if (err instanceof CapxulError && err.code === "PROVIDER_ERROR") {
569
- return [err, null];
570
- }
571
- return [
572
- malformedWireError(
573
- err instanceof Error ? err.message : String(err),
574
- raw
575
- ),
576
- null
577
- ];
578
- }
579
- }
580
- function createSubAccountsClient(config = {}) {
581
- return {
582
- retrieve: async (subAccountId) => {
583
- if (!config._data) {
584
- return stub("subAccounts.retrieve");
585
- }
586
- const [err, raw] = await tryCatch(
587
- config._data.query(api.subAccounts.queries.retrieve, {
588
- subAccountId
589
- })
590
- );
591
- if (err) {
592
- return [
593
- fromConvexError(err),
594
- null
595
- ];
596
- }
597
- if (!raw) {
598
- return [
599
- new CapxulError({
600
- code: "NOT_FOUND",
601
- message: `sub_account ${subAccountId} not found`
602
- }),
603
- null
604
- ];
605
- }
606
- const [brandErr, branded] = tryBrandSubAccount(raw);
607
- if (brandErr) {
608
- return [brandErr, null];
609
- }
610
- return [null, branded];
611
- },
612
- remove: async (subAccountId) => {
613
- if (!config._data) {
614
- return stub("subAccounts.remove");
615
- }
616
- const [err, raw] = await tryCatch(
617
- config._data.mutation(api.subAccounts.mutations.archive, {
618
- subAccountId
619
- })
620
- );
621
- if (err) {
622
- return [
623
- fromConvexError(err),
624
- null
625
- ];
626
- }
627
- if (!raw) {
628
- return [
629
- new CapxulError({
630
- code: "NOT_FOUND",
631
- message: `sub_account ${subAccountId} not found`
632
- }),
633
- null
634
- ];
635
- }
636
- const [brandErr, branded] = tryBrandSubAccount(raw);
637
- if (brandErr) {
638
- return [brandErr, null];
639
- }
640
- return [null, branded];
641
- }
642
- };
643
- }
644
-
645
- // src/core/accounts.ts
646
- function createAccountExternalAccountsClient(config) {
647
- return {
648
- create: async (input) => {
649
- if (!config._data) {
650
- return stub(
651
- "accounts.externalAccounts.create"
652
- );
653
- }
654
- const [err, raw] = await tryCatch(
655
- config._data.mutation(
656
- api.externalAccounts.mutations.createPersonal,
657
- {
658
- kind: input.kind,
659
- label: input.label,
660
- address: input.address,
661
- iban: input.iban,
662
- bic: input.bic,
663
- accountHolder: input.accountHolder,
664
- network: input.network,
665
- panToken: input.panToken,
666
- last4: input.last4
667
- }
668
- )
669
- );
670
- if (err) {
671
- return [
672
- fromConvexError(err),
673
- null
674
- ];
675
- }
676
- if (!raw) {
677
- return [
678
- new CapxulError({
679
- code: "NOT_FOUND",
680
- message: "external_account creation returned no resource"
681
- }),
682
- null
683
- ];
684
- }
685
- return [
686
- null,
687
- brandExternalAccount(
688
- raw
689
- )
690
- ];
691
- },
692
- list: async (input) => {
693
- if (!config._data) {
694
- return stub(
695
- "accounts.externalAccounts.list"
696
- );
697
- }
698
- const [err, result] = await tryCatch(
699
- config._data.query(api.externalAccounts.queries.listPersonal, {
700
- limit: input.limit,
701
- cursor: input.cursor
702
- })
703
- );
704
- if (err) {
705
- return [fromConvexError(err), null];
706
- }
707
- const branded = result.data.map(
708
- (row) => brandExternalAccount(
709
- row
710
- )
711
- );
712
- return [
713
- null,
714
- {
715
- object: "list",
716
- data: branded,
717
- page: result.page
718
- }
719
- ];
720
- },
721
- retrieve: async (externalAccountId) => {
722
- if (!config._data) {
723
- return stub(
724
- "accounts.externalAccounts.retrieve"
725
- );
726
- }
727
- const [err, raw] = await tryCatch(
728
- config._data.query(api.externalAccounts.queries.retrievePersonal, {
729
- externalAccountId
730
- })
731
- );
732
- if (err) {
733
- return [
734
- fromConvexError(err),
735
- null
736
- ];
737
- }
738
- if (!raw) {
739
- return [
740
- new CapxulError({
741
- code: "NOT_FOUND",
742
- message: `external_account ${externalAccountId} not found`
743
- }),
744
- null
745
- ];
746
- }
747
- return [
748
- null,
749
- brandExternalAccount(
750
- raw
751
- )
752
- ];
753
- },
754
- remove: async (externalAccountId) => {
755
- if (!config._data) {
756
- return stub("accounts.externalAccounts.remove");
757
- }
758
- const [err] = await tryCatch(
759
- config._data.mutation(api.externalAccounts.mutations.removePersonal, {
760
- externalAccountId
761
- })
762
- );
763
- if (err) {
764
- return [
765
- fromConvexError(err),
766
- null
767
- ];
768
- }
769
- return [null, void 0];
770
- }
771
- };
772
- }
773
- function createAccountSubAccountsClient(config) {
774
- return {
775
- create: async (input) => {
776
- if (!config._data) {
777
- return stub(
778
- "accounts.subAccounts.create"
779
- );
780
- }
781
- const [err, raw] = await tryCatch(
782
- config._data.mutation(api.subAccounts.mutations.create, {
783
- parent: { kind: "account", id: input.accountId },
784
- name: input.name,
785
- purpose: input.purpose
786
- })
787
- );
788
- if (err) {
789
- return [
790
- fromConvexError(err),
791
- null
792
- ];
793
- }
794
- if (!raw) {
795
- return [
796
- new CapxulError({
797
- code: "NOT_FOUND",
798
- message: "sub_account creation returned no resource"
799
- }),
800
- null
801
- ];
802
- }
803
- const [brandErr, branded] = tryBrandSubAccount(raw);
804
- if (brandErr) {
805
- return [
806
- brandErr,
807
- null
808
- ];
809
- }
810
- return [null, branded];
811
- },
812
- list: async (input) => {
813
- if (!config._data) {
814
- return stub(
815
- "accounts.subAccounts.list"
816
- );
817
- }
818
- const [err, rows] = await tryCatch(
819
- config._data.query(api.subAccounts.queries.listByAccount, {
820
- accountId: input.accountId
821
- })
822
- );
823
- if (err) {
824
- return [
825
- fromConvexError(err),
826
- null
827
- ];
828
- }
829
- const branded = [];
830
- for (const row of rows) {
831
- const [brandErr, value] = tryBrandSubAccount(row);
832
- if (brandErr) {
833
- return [
834
- brandErr,
835
- null
836
- ];
837
- }
838
- branded.push(value);
839
- }
840
- return [
841
- null,
842
- {
843
- object: "list",
844
- data: branded,
845
- page: { hasMore: false }
846
- }
847
- ];
848
- },
849
- retrieve: async (subAccountId) => {
850
- if (!config._data) {
851
- return stub(
852
- "accounts.subAccounts.retrieve"
853
- );
854
- }
855
- const [err, raw] = await tryCatch(
856
- config._data.query(api.subAccounts.queries.retrieve, {
857
- subAccountId
858
- })
859
- );
860
- if (err) {
861
- return [
862
- fromConvexError(err),
863
- null
864
- ];
865
- }
866
- if (!raw) {
867
- return [
868
- new CapxulError({
869
- code: "NOT_FOUND",
870
- message: `sub_account ${subAccountId} not found`
871
- }),
872
- null
873
- ];
874
- }
875
- const [brandErr, branded] = tryBrandSubAccount(raw);
876
- if (brandErr) {
877
- return [
878
- brandErr,
879
- null
880
- ];
881
- }
882
- return [null, branded];
883
- },
884
- remove: async (subAccountId) => {
885
- if (!config._data) {
886
- return stub(
887
- "accounts.subAccounts.remove"
888
- );
889
- }
890
- const [err, raw] = await tryCatch(
891
- config._data.mutation(api.subAccounts.mutations.archive, {
892
- subAccountId
893
- })
894
- );
895
- if (err) {
896
- return [
897
- fromConvexError(err),
898
- null
899
- ];
900
- }
901
- if (!raw) {
902
- return [
903
- new CapxulError({
904
- code: "NOT_FOUND",
905
- message: `sub_account ${subAccountId} not found`
906
- }),
907
- null
908
- ];
909
- }
910
- const [brandErr, branded] = tryBrandSubAccount(raw);
911
- if (brandErr) {
912
- return [
913
- brandErr,
914
- null
915
- ];
916
- }
917
- return [null, branded];
918
- }
919
- };
920
- }
921
- function createAccountsClient(config = {}) {
922
- return {
923
- retrieve: async (accountId) => {
924
- if (!config._data) {
925
- return stub("accounts.retrieve");
926
- }
927
- try {
928
- const account = await config._data.query(
929
- api.openfort.queries.getMyAccount,
930
- {}
931
- );
932
- if (account.id !== accountId) {
933
- return [
934
- new CapxulError({
935
- code: "PERMISSION_DENIED",
936
- message: "accounts.retrieve currently supports the authenticated caller's own account only.",
937
- details: {
938
- requestedAccountId: accountId,
939
- authenticatedAccountId: account.id
940
- }
941
- }),
942
- null
943
- ];
944
- }
945
- return [null, account];
946
- } catch (cause) {
947
- return [fromConvexError(cause), null];
948
- }
949
- },
950
- lookup: async () => stub("accounts.lookup"),
951
- update: async (input) => {
952
- if (!config._data) {
953
- return stub("accounts.update");
954
- }
955
- if (input.countryCode !== void 0) {
956
- return [
957
- new CapxulError({
958
- code: "INVALID_INPUT",
959
- message: "accounts.update does not support countryCode yet \u2014 backend mutation only patches displayName and username.",
960
- details: { field: "countryCode" }
961
- }),
962
- null
963
- ];
964
- }
965
- try {
966
- const current = await config._data.query(
967
- api.openfort.queries.getMyAccount,
968
- {}
969
- );
970
- if (current.id !== input.accountId) {
971
- return [
972
- new CapxulError({
973
- code: "PERMISSION_DENIED",
974
- message: "accounts.update currently supports the authenticated caller's own account only.",
975
- details: {
976
- requestedAccountId: input.accountId,
977
- authenticatedAccountId: current.id
978
- }
979
- }),
980
- null
981
- ];
982
- }
983
- await config._data.mutation(api.openfort.mutations.updateProfile, {
984
- displayName: input.name,
985
- username: input.username
986
- });
987
- const updated = await config._data.query(
988
- api.openfort.queries.getMyAccount,
989
- {}
990
- );
991
- return [null, updated];
992
- } catch (cause) {
993
- return [fromConvexError(cause), null];
994
- }
995
- },
996
- provisionPersonal: async (input) => {
997
- if (!config._data) {
998
- return stub(
999
- "accounts.provisionPersonal"
1000
- );
1001
- }
1002
- if (input.signerProvider.kind !== "local-private-key") {
1003
- return [
1004
- new CapxulError({
1005
- code: "INVALID_INPUT",
1006
- message: "accounts.provisionPersonal currently supports local-private-key signer providers only."
1007
- }),
1008
- null
1009
- ];
1010
- }
1011
- try {
1012
- await config._data.mutation(
1013
- api.safe.mutations.provisionLocalPersonalAccount,
1014
- {
1015
- displayName: input.displayName,
1016
- username: input.username,
1017
- countryCode: input.countryCode,
1018
- eoaAddress: input.signerProvider.signerAddress,
1019
- safeAddress: deriveSafeAddress(input.signerProvider.signerAddress)
1020
- }
1021
- );
1022
- const account = await config._data.query(
1023
- api.openfort.queries.getMyAccount,
1024
- {}
1025
- );
1026
- if (!account) {
1027
- return [
1028
- new CapxulError({
1029
- code: "NOT_FOUND",
1030
- message: "accounts.provisionPersonal completed but no account resource was readable."
1031
- }),
1032
- null
1033
- ];
1034
- }
1035
- return [null, account];
1036
- } catch (cause) {
1037
- return [
1038
- fromConvexError(cause),
1039
- null
1040
- ];
1041
- }
1042
- },
1043
- safes: {
1044
- retrieve: async (safeId) => {
1045
- if (!config._data) {
1046
- return stub("accounts.safes.retrieve");
1047
- }
1048
- try {
1049
- const safe = await config._data.query(
1050
- api.safe.queries.retrieveAccountSafe,
1051
- { safeId }
1052
- );
1053
- if (!safe) {
1054
- return [
1055
- new CapxulError({
1056
- code: "NOT_FOUND",
1057
- message: `safe ${safeId} not found`
1058
- }),
1059
- null
1060
- ];
1061
- }
1062
- return [null, safe];
1063
- } catch (cause) {
1064
- return [
1065
- fromConvexError(cause),
1066
- null
1067
- ];
1068
- }
1069
- }
1070
- },
1071
- kycProfiles: {
1072
- create: async () => stub("accounts.kycProfiles.create"),
1073
- retrieve: async () => stub("accounts.kycProfiles.retrieve")
1074
- },
1075
- externalAccounts: createAccountExternalAccountsClient(config),
1076
- subAccounts: createAccountSubAccountsClient(config),
1077
- balanceLedger: {
1078
- list: async (input) => {
1079
- if (!config._data) {
1080
- return stub(
1081
- "accounts.balanceLedger.list"
1082
- );
1083
- }
1084
- try {
1085
- const accountId = input.accountId.replace(/^acct_/, "");
1086
- const page = await config._data.query(
1087
- api.balanceLedger.queries.listForAccount,
1088
- { accountId, limit: input.limit, cursor: input.cursor }
1089
- );
1090
- return [null, page];
1091
- } catch (cause) {
1092
- return [fromConvexError(cause), null];
1093
- }
1094
- },
1095
- retrieve: async (entryId) => {
1096
- if (!config._data) {
1097
- return stub(
1098
- "accounts.balanceLedger.retrieve"
1099
- );
1100
- }
1101
- try {
1102
- const entry = await config._data.query(
1103
- api.balanceLedger.queries.retrieve,
1104
- { entryId }
1105
- );
1106
- if (!entry) {
1107
- return [
1108
- new CapxulError({
1109
- code: "NOT_FOUND",
1110
- message: `balance_ledger_entry ${entryId} not found`
1111
- }),
1112
- null
1113
- ];
1114
- }
1115
- return [null, entry];
1116
- } catch (cause) {
1117
- return [fromConvexError(cause), null];
1118
- }
1119
- }
1120
- }
1121
- };
1122
- }
1123
-
1124
- // src/core/api-keys.ts
1125
- function createApiKeysClient() {
1126
- return {
1127
- create: async () => stub("apiKeys.create"),
1128
- retrieve: async () => stub("apiKeys.retrieve"),
1129
- list: async () => stub("apiKeys.list"),
1130
- revoke: async () => stub("apiKeys.revoke")
1131
- };
1132
- }
1133
- function createDefaultDataClient(convexUrl, jwt) {
1134
- const client = new ConvexHttpClient(convexUrl);
1135
- client.setAuth(jwt);
1136
- return client;
1137
- }
1138
-
1139
- // src/transport.ts
1140
- function makeHttpTransport(config) {
1141
- switch (config.mode) {
1142
- case "build-time-urls":
1143
- return makeBuildTimeUrlsTransport(config);
1144
- case "publishable-key":
1145
- return makePublishableKeyTransport(config);
1146
- default:
1147
- return assertNever(config);
1148
- }
1149
- }
1150
- function createLifecycle(initial) {
1151
- let state = initial;
1152
- const listeners = /* @__PURE__ */ new Set();
1153
- return {
1154
- getState: () => state,
1155
- setState: (next) => {
1156
- if (Object.is(state, next)) return;
1157
- state = next;
1158
- for (const listener of listeners) listener();
1159
- },
1160
- subscribe: (listener) => {
1161
- listeners.add(listener);
1162
- return () => {
1163
- listeners.delete(listener);
1164
- };
1165
- }
1166
- };
1167
- }
1168
- function makeBuildTimeUrlsTransport(config) {
1169
- if (!config.authBaseUrl || config.authBaseUrl.trim().length === 0) {
1170
- throw invalidConfigError(
1171
- "authBaseUrl",
1172
- "build-time-urls transport requires a non-empty authBaseUrl."
1173
- );
1174
- }
1175
- if (!config.convexUrl || config.convexUrl.trim().length === 0) {
1176
- throw invalidConfigError(
1177
- "convexUrl",
1178
- "build-time-urls transport requires a non-empty convexUrl."
1179
- );
1180
- }
1181
- const authBaseUrl = stripTrailingSlash(config.authBaseUrl);
1182
- const convexUrl = config.convexUrl;
1183
- const fetchImpl = config.fetchImpl ?? globalThis.fetch;
1184
- const runtime = { authBaseUrl, convexUrl };
1185
- const lifecycle = createLifecycle({ status: "ready", runtime });
1186
- let dataClient = null;
1187
- return {
1188
- authBaseUrl,
1189
- convexUrl,
1190
- ensureRuntime: async () => runtime,
1191
- fetch: (path, init) => fetchImpl(resolveUrl(authBaseUrl, path), init),
1192
- getState: lifecycle.getState,
1193
- subscribe: lifecycle.subscribe,
1194
- getDataClient: () => dataClient,
1195
- markAuthenticated: ({ dataClient: nextDataClient }) => {
1196
- if (nextDataClient !== void 0) dataClient = nextDataClient;
1197
- lifecycle.setState({ status: "authenticated", runtime });
1198
- },
1199
- clearAuth: () => {
1200
- dataClient = null;
1201
- lifecycle.setState({ status: "ready", runtime });
1202
- }
1203
- };
1204
- }
1205
- function makePublishableKeyTransport(config) {
1206
- const publishableKey = config.publishableKey?.trim();
1207
- if (!publishableKey) {
1208
- throw invalidConfigError(
1209
- "publishableKey",
1210
- "publishable-key transport requires a non-empty publishableKey."
1211
- );
1212
- }
1213
- const fetchImpl = config.fetchImpl ?? globalThis.fetch;
1214
- const bootstrapUrl = normalizeBootstrapUrl(
1215
- config.bootstrapUrl ?? `${CAPXUL_API_BASE_URL}/v1/client/bootstrap`
1216
- );
1217
- let authBaseUrl = "";
1218
- let convexUrl = "";
1219
- let bootstrapPromise = null;
1220
- let dataClient = null;
1221
- const lifecycle = createLifecycle({ status: "idle" });
1222
- async function ensureBootstrap() {
1223
- if (bootstrapPromise) return await bootstrapPromise;
1224
- lifecycle.setState({ status: "bootstrapping" });
1225
- const attempt = (async () => {
1226
- const response = await fetchImpl(bootstrapUrl, {
1227
- method: "POST",
1228
- headers: { "content-type": "application/json" },
1229
- body: JSON.stringify({ publishableKey })
1230
- });
1231
- if (!response.ok) {
1232
- throw await bootstrapResponseError(response, bootstrapUrl);
1233
- }
1234
- const body = await readBootstrapSuccessBody(response);
1235
- if (typeof body.authBaseUrl !== "string" || body.authBaseUrl.trim().length === 0) {
1236
- throw bootstrapContractError(
1237
- "authBaseUrl",
1238
- "/v1/client/bootstrap returned no authBaseUrl."
1239
- );
1240
- }
1241
- if (typeof body.convexUrl !== "string" || body.convexUrl.trim().length === 0) {
1242
- throw bootstrapContractError(
1243
- "convexUrl",
1244
- "/v1/client/bootstrap returned no convexUrl."
1245
- );
1246
- }
1247
- authBaseUrl = stripTrailingSlash(body.authBaseUrl);
1248
- convexUrl = body.convexUrl;
1249
- const runtime = { authBaseUrl, convexUrl };
1250
- lifecycle.setState({ status: "ready", runtime });
1251
- return runtime;
1252
- })();
1253
- bootstrapPromise = attempt.catch((err) => {
1254
- const error = normalizeBootstrapThrownError(err);
1255
- bootstrapPromise = null;
1256
- lifecycle.setState({
1257
- status: "error",
1258
- error
1259
- });
1260
- throw error;
1261
- });
1262
- return await bootstrapPromise;
1263
- }
1264
- return {
1265
- get authBaseUrl() {
1266
- return authBaseUrl;
1267
- },
1268
- get convexUrl() {
1269
- return convexUrl;
1270
- },
1271
- ensureRuntime: ensureBootstrap,
1272
- fetch: async (path, init) => {
1273
- const resolved = await ensureBootstrap();
1274
- return await fetchImpl(resolveUrl(resolved.authBaseUrl, path), init);
1275
- },
1276
- getState: lifecycle.getState,
1277
- subscribe: lifecycle.subscribe,
1278
- getDataClient: () => dataClient,
1279
- markAuthenticated: ({ dataClient: nextDataClient }) => {
1280
- const current = lifecycle.getState();
1281
- if (current.status !== "ready" && current.status !== "authenticated") {
1282
- throw internalTransportError(
1283
- `markAuthenticated() called from status="${current.status}". Expected "ready" or "authenticated".`
1284
- );
1285
- }
1286
- if (nextDataClient !== void 0) dataClient = nextDataClient;
1287
- lifecycle.setState({
1288
- status: "authenticated",
1289
- runtime: current.runtime
1290
- });
1291
- },
1292
- clearAuth: () => {
1293
- const current = lifecycle.getState();
1294
- dataClient = null;
1295
- if (current.status === "authenticated") {
1296
- lifecycle.setState({ status: "ready", runtime: current.runtime });
1297
- }
1298
- }
1299
- };
1300
- }
1301
- function stripTrailingSlash(url) {
1302
- return url.replace(/\/+$/, "");
1303
- }
1304
- function normalizeBootstrapUrl(url) {
1305
- const normalized = stripTrailingSlash(url.trim());
1306
- if (!isAbsoluteHttpUrl(normalized)) {
1307
- throw invalidConfigError(
1308
- "bootstrapUrl",
1309
- "publishable-key transport requires an absolute http(s) bootstrapUrl."
1310
- );
1311
- }
1312
- return normalized;
1313
- }
1314
- function isAbsoluteHttpUrl(url) {
1315
- try {
1316
- const parsed = new URL(url);
1317
- return parsed.protocol === "http:" || parsed.protocol === "https:";
1318
- } catch {
1319
- return false;
1320
- }
1321
- }
1322
- function resolveUrl(authBaseUrl, path) {
1323
- if (path.startsWith("http://") || path.startsWith("https://")) {
1324
- return path;
1325
- }
1326
- return `${authBaseUrl}${path}`;
1327
- }
1328
- function assertNever(value) {
1329
- throw internalTransportError(
1330
- `Unhandled BrowserCapxulConfig.mode: ${String(value.mode)}.`
1331
- );
1332
- }
1333
- function invalidConfigError(field, reason) {
1334
- return new CapxulError({
1335
- code: "INVALID_INPUT",
1336
- message: `Invalid ${field}: ${reason}`,
1337
- details: { source: "sdk-config", field, reason }
1338
- });
1339
- }
1340
- function bootstrapContractError(field, message) {
1341
- return new CapxulError({
1342
- code: "INVALID_INPUT",
1343
- message,
1344
- details: {
1345
- source: "backend-bootstrap",
1346
- phase: "publishable-key-bootstrap",
1347
- field,
1348
- reason: message
1349
- }
1350
- });
1351
- }
1352
- function internalTransportError(reason) {
1353
- return new CapxulError({
1354
- code: "INTERNAL_ERROR",
1355
- message: `Internal error: ${reason}`,
1356
- details: { source: "sdk-transport", reason }
1357
- });
1358
- }
1359
- async function bootstrapResponseError(response, bootstrapUrl) {
1360
- const envelope = await readBootstrapErrorEnvelope(response);
1361
- const wireCode = readNonEmptyString(envelope?.error?.code);
1362
- const normalized = normalizeBootstrapErrorCode(wireCode);
1363
- const message = readNonEmptyString(envelope?.error?.message) ?? `${bootstrapUrl} failed with HTTP ${response.status}.`;
1364
- const backendDetails = readRecord(envelope?.error?.details);
1365
- return new CapxulError({
1366
- code: normalized.code,
1367
- message,
1368
- details: {
1369
- ...backendDetails,
1370
- source: "backend-bootstrap",
1371
- phase: "publishable-key-bootstrap",
1372
- httpStatus: response.status,
1373
- ...normalized.wireCode ? { wireCode: normalized.wireCode } : {}
1374
- },
1375
- operationId: readNonEmptyString(envelope?.error?.operationId),
1376
- correlationId: readNonEmptyString(envelope?.error?.correlationId),
1377
- retryable: typeof envelope?.error?.retryable === "boolean" ? envelope.error.retryable : void 0
1378
- });
1379
- }
1380
- async function readBootstrapErrorEnvelope(response) {
1381
- try {
1382
- const parsed = await response.json();
1383
- return typeof parsed === "object" && parsed !== null ? parsed : null;
1384
- } catch {
1385
- return null;
1386
- }
1387
- }
1388
- async function readBootstrapSuccessBody(response) {
1389
- try {
1390
- const parsed = await response.json();
1391
- return typeof parsed === "object" && parsed !== null ? parsed : {};
1392
- } catch {
1393
- throw bootstrapContractError(
1394
- "body",
1395
- "/v1/client/bootstrap returned invalid JSON."
1396
- );
1397
- }
1398
- }
1399
- function normalizeBootstrapThrownError(error) {
1400
- if (error instanceof CapxulError) return error;
1401
- return new CapxulError({
1402
- code: "NETWORK_ERROR",
1403
- message: "Publishable-key bootstrap network failure.",
1404
- cause: error,
1405
- details: {
1406
- source: "bootstrap-network",
1407
- phase: "publishable-key-bootstrap"
1408
- }
1409
- });
1410
- }
1411
- function normalizeBootstrapErrorCode(wireCode) {
1412
- if (wireCode === "INTERNAL_SERVER_ERROR") {
1413
- return { code: "INTERNAL_ERROR", wireCode };
1414
- }
1415
- if (wireCode && isCapxulErrorCode(wireCode)) {
1416
- return { code: wireCode };
1417
- }
1418
- return wireCode ? { code: "UNKNOWN", wireCode } : { code: "UNKNOWN" };
1419
- }
1420
- var CAPXUL_ERROR_CODES = /* @__PURE__ */ new Set([
1421
- "NOT_AUTHENTICATED",
1422
- "EMAIL_DELIVERY_FAILED",
1423
- "PROFILE_NOT_FOUND",
1424
- "SMART_ACCOUNT_MISSING",
1425
- "PLAYER_NOT_FOUND",
1426
- "ACCOUNT_NOT_FOUND",
1427
- "PROVIDER_ERROR",
1428
- "INVALID_INPUT",
1429
- "ENV_MISSING",
1430
- "NOT_IMPLEMENTED",
1431
- "VERIFICATION_REQUIRED",
1432
- "INSUFFICIENT_BALANCE",
1433
- "INVALID_RECIPIENT",
1434
- "TRANSACTION_FAILED",
1435
- "RATE_LIMITED",
1436
- "NETWORK_ERROR",
1437
- "UNKNOWN",
1438
- "PERMISSION_DENIED",
1439
- "API_KEY_INVALID",
1440
- "API_KEY_EXPIRED",
1441
- "IDEMPOTENCY_CONFLICT",
1442
- "NOT_FOUND",
1443
- "OPERATION_CANCELED",
1444
- "OPERATION_TIMEOUT",
1445
- "ACTION_REQUIRED",
1446
- "KYC_REQUIRED",
1447
- "POLICY_DENIED",
1448
- "SAFE_NOT_READY",
1449
- "PROVIDER_UNAVAILABLE",
1450
- "PROVIDER_REJECTED",
1451
- "RECONCILIATION_FAILED",
1452
- "INTERNAL_ERROR",
1453
- "QUOTE_EXPIRED",
1454
- "QUOTE_NOT_FOUND"
1455
- ]);
1456
- function isCapxulErrorCode(value) {
1457
- return CAPXUL_ERROR_CODES.has(value);
1458
- }
1459
- function readRecord(value) {
1460
- return typeof value === "object" && value !== null ? value : null;
1461
- }
1462
- function readNonEmptyString(value) {
1463
- return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
1464
- }
1465
-
1466
- // src/core/auth.ts
1467
- function createAuthClient(config = {}) {
1468
- let dataClient = config._data ?? null;
1469
- const sessionStore = config.auth?.sessionStore ?? createMemorySessionStore();
1470
- const getTransport = createTransportProvider(config);
1471
- return {
1472
- sendOtp: async (input, options) => {
1473
- const transport = getTransport();
1474
- if (!transport) {
1475
- return stub("auth.sendOtp");
1476
- }
1477
- return await postBetterAuth(
1478
- transport,
1479
- "/email-otp/send-verification-otp",
1480
- { email: input.email, type: "sign-in" },
1481
- "EMAIL_DELIVERY_FAILED",
1482
- options?.signal
1483
- );
1484
- },
1485
- verifyOtp: async (input, options) => {
1486
- const transport = getTransport();
1487
- if (!transport) {
1488
- return stub("auth.verifyOtp");
1489
- }
1490
- const [signInError, signIn] = await postBetterAuth(
1491
- transport,
1492
- "/sign-in/email-otp",
1493
- { email: input.email, otp: input.otp },
1494
- "NOT_AUTHENTICATED",
1495
- options?.signal
1496
- );
1497
- if (signInError) return [signInError, null];
1498
- if (!signIn?.token || !signIn.user?.id) {
1499
- return [
1500
- new CapxulError({
1501
- code: "NOT_AUTHENTICATED",
1502
- message: "BetterAuth did not return a usable session."
1503
- }),
1504
- null
1505
- ];
1506
- }
1507
- const [convexError, convexJwt] = await exchangeConvexToken(
1508
- transport,
1509
- config,
1510
- signIn.token,
1511
- options?.signal
1512
- );
1513
- if (convexError) return [convexError, null];
1514
- const session = {
1515
- authUserId: signIn.user.id,
1516
- email: signIn.user.email,
1517
- token: signIn.token,
1518
- convexJwt,
1519
- expiresAt: new Date(
1520
- Date.now() + 30 * 24 * 60 * 60 * 1e3
1521
- ).toISOString()
1522
- };
1523
- sessionStore.set(session);
1524
- if (!dataClient) {
1525
- try {
1526
- const convexUrl = transport.convexUrl;
1527
- if (!convexUrl || !session.convexJwt) {
1528
- return [
1529
- new CapxulError({
1530
- code: "NETWORK_ERROR",
1531
- message: "Cannot create data client: missing convex URL or JWT."
1532
- }),
1533
- null
1534
- ];
1535
- }
1536
- dataClient = createDefaultDataClient(convexUrl, session.convexJwt);
1537
- mutableConfig(config)._data = dataClient;
1538
- } catch (cause) {
1539
- return [
1540
- new CapxulError({
1541
- code: "NETWORK_ERROR",
1542
- message: "Authenticated data client creation failed.",
1543
- cause
1544
- }),
1545
- null
1546
- ];
1547
- }
1548
- } else {
1549
- const injected = dataClient;
1550
- if (typeof injected.refreshAuth === "function") {
1551
- injected.refreshAuth();
1552
- } else if (typeof injected.setAuth === "function" && session.convexJwt) {
1553
- injected.setAuth(session.convexJwt);
1554
- }
1555
- }
1556
- transport.markAuthenticated({ dataClient });
1557
- if (!dataClient) {
1558
- return [
1559
- new CapxulError({
1560
- code: "NOT_AUTHENTICATED",
1561
- message: "Auth bootstrap requires an authenticated Convex data client."
1562
- }),
1563
- null
1564
- ];
1565
- }
1566
- try {
1567
- const resolution = await dataClient.mutation(
1568
- api.authBootstrap.resolveAfterOtp,
1569
- {
1570
- email: session.email,
1571
- sessionToken: session.token
1572
- }
1573
- );
1574
- if (resolution.kind === "existing_member") {
1575
- return [null, { ...resolution, session }];
1576
- }
1577
- return [null, { ...resolution, session }];
1578
- } catch (cause) {
1579
- return [fromConvexError(cause), null];
1580
- }
1581
- },
1582
- completeBootstrap: async (input) => {
1583
- const session = sessionStore.get();
1584
- const data = dataClient ?? config._data;
1585
- if (!session || !data) {
1586
- return [
1587
- new CapxulError({
1588
- code: "INVALID_INPUT",
1589
- message: "completeBootstrap requires the OTP-verified session that issued the bootstrap token."
1590
- }),
1591
- null
1592
- ];
1593
- }
1594
- const signerAddress = config.signer?.address;
1595
- if (!signerAddress) {
1596
- return [
1597
- new CapxulError({
1598
- code: "INVALID_INPUT",
1599
- message: "completeBootstrap requires a signer to be configured on the client."
1600
- }),
1601
- null
1602
- ];
1603
- }
1604
- try {
1605
- const safeAddress = deriveSafeAddress(signerAddress);
1606
- const result = await data.mutation(api.authBootstrap.completeBootstrap, {
1607
- bootstrapToken: input.bootstrapToken,
1608
- sessionToken: session.token,
1609
- username: input.username,
1610
- displayName: input.displayName,
1611
- countryCode: input.countryCode,
1612
- signerProvider: {
1613
- kind: "local-private-key",
1614
- signerAddress,
1615
- safeAddress
1616
- }
1617
- });
1618
- return [null, { kind: "authenticated", session, ...result }];
1619
- } catch (cause) {
1620
- return [
1621
- fromConvexError(cause),
1622
- null
1623
- ];
1624
- }
1625
- },
1626
- getSession: async () => [null, sessionStore.get()],
1627
- signOut: async () => {
1628
- sessionStore.clear();
1629
- dataClient = null;
1630
- mutableConfig(config)._data = void 0;
1631
- const transport = getTransport();
1632
- transport?.clearAuth();
1633
- return [null, void 0];
1634
- },
1635
- serviceTokenMint: async () => stub("auth.serviceTokenMint"),
1636
- getDataClient: () => dataClient
1637
- };
1638
- }
1639
- function createMemorySessionStore() {
1640
- let current = null;
1641
- return {
1642
- get: () => current,
1643
- set: (session) => {
1644
- current = session;
1645
- },
1646
- clear: () => {
1647
- current = null;
1648
- }
1649
- };
1650
- }
1651
- function createTransportProvider(config) {
1652
- let cached = config._transport ?? null;
1653
- return () => {
1654
- if (cached) return cached;
1655
- const baseUrl = config.auth?.baseUrl;
1656
- if (baseUrl) {
1657
- cached = makeHttpTransport({
1658
- mode: "build-time-urls",
1659
- authBaseUrl: betterAuthRoot(baseUrl),
1660
- convexUrl: baseUrl,
1661
- fetchImpl: config.fetch
1662
- });
1663
- return cached;
1664
- }
1665
- if (!config.publishableKey) return null;
1666
- cached = makeHttpTransport({
1667
- mode: "publishable-key",
1668
- publishableKey: config.publishableKey,
1669
- fetchImpl: config.fetch
1670
- });
1671
- return cached;
1672
- };
1673
- }
1674
- function betterAuthRoot(rawBaseUrl) {
1675
- const trimmed = rawBaseUrl.replace(/\/+$/, "");
1676
- return trimmed.endsWith("/api/auth") ? trimmed : `${trimmed}/api/auth`;
1677
- }
1678
- async function postBetterAuth(transport, path, body, code, signal) {
1679
- try {
1680
- const response = await transport.fetch(path, {
1681
- method: "POST",
1682
- headers: { "content-type": "application/json" },
1683
- body: JSON.stringify(body),
1684
- signal
1685
- });
1686
- const text = await response.text();
1687
- if (!response.ok) {
1688
- const parsedError = parseBetterAuthError(text);
1689
- return [
1690
- new CapxulError({
1691
- code: parsedError.code ?? code,
1692
- message: parsedError.message ?? `BetterAuth ${path} failed with HTTP ${response.status}.`,
1693
- details: parsedError.details,
1694
- retryable: parsedError.retryable
1695
- }),
1696
- null
1697
- ];
1698
- }
1699
- return [null, text ? JSON.parse(text) : void 0];
1700
- } catch (cause) {
1701
- if (cause instanceof CapxulError) {
1702
- return [cause, null];
1703
- }
1704
- return [
1705
- new CapxulError({
1706
- code: "NETWORK_ERROR",
1707
- message: `BetterAuth ${path} network failure.`,
1708
- cause
1709
- }),
1710
- null
1711
- ];
1712
- }
1713
- }
1714
- function parseBetterAuthError(text) {
1715
- if (!text.trim()) {
1716
- return {};
1717
- }
1718
- try {
1719
- const body = JSON.parse(text);
1720
- if (!body || typeof body !== "object") {
1721
- return {};
1722
- }
1723
- const record = body;
1724
- const nested = record.error && typeof record.error === "object" ? record.error : record;
1725
- const code = typeof nested.code === "string" ? nested.code : void 0;
1726
- const message = typeof nested.message === "string" ? nested.message : void 0;
1727
- const details = nested.details && typeof nested.details === "object" ? nested.details : void 0;
1728
- const correlationId = typeof nested.correlationId === "string" ? nested.correlationId : void 0;
1729
- const retryable = typeof nested.retryable === "boolean" ? nested.retryable : void 0;
1730
- return {
1731
- code: isCapxulErrorCode2(code) ? code : void 0,
1732
- message,
1733
- details,
1734
- correlationId,
1735
- retryable
1736
- };
1737
- } catch {
1738
- return {};
1739
- }
1740
- }
1741
- function isCapxulErrorCode2(code) {
1742
- return code === "NOT_AUTHENTICATED" || code === "EMAIL_DELIVERY_FAILED" || code === "INVALID_INPUT" || code === "RATE_LIMITED" || code === "NETWORK_ERROR" || code === "API_KEY_INVALID" || code === "API_KEY_EXPIRED" || code === "INTERNAL_ERROR" || code === "ENV_MISSING" || code === "UNKNOWN" || code === "PROVIDER_ERROR";
1743
- }
1744
- async function exchangeConvexToken(transport, config, token, signal) {
1745
- const path = config.auth?.convexTokenUrl ?? "/convex/token";
1746
- try {
1747
- const response = await transport.fetch(path, {
1748
- headers: { authorization: `Bearer ${token}` },
1749
- signal
1750
- });
1751
- if (!response.ok) {
1752
- return [
1753
- new CapxulError({
1754
- code: "NOT_AUTHENTICATED",
1755
- message: `Convex token exchange failed with HTTP ${response.status}.`
1756
- }),
1757
- null
1758
- ];
1759
- }
1760
- const body = await response.json();
1761
- if (typeof body.token !== "string") {
1762
- return [
1763
- new CapxulError({
1764
- code: "NOT_AUTHENTICATED",
1765
- message: "Convex token exchange returned no token."
1766
- }),
1767
- null
1768
- ];
1769
- }
1770
- return [null, body.token];
1771
- } catch (cause) {
1772
- if (cause instanceof CapxulError) {
1773
- return [cause, null];
1774
- }
1775
- return [
1776
- new CapxulError({
1777
- code: "NETWORK_ERROR",
1778
- message: "Convex token exchange network failure.",
1779
- cause
1780
- }),
1781
- null
1782
- ];
1783
- }
1784
- }
1785
- function mutableConfig(config) {
1786
- return config;
1787
- }
1788
-
1789
- // src/core/documents.ts
1790
- function createDocumentsClient() {
1791
- return {
1792
- create: async () => stub("documents.create"),
1793
- retrieve: async () => stub("documents.retrieve"),
1794
- list: async () => stub("documents.list"),
1795
- cancel: async () => stub("documents.cancel")
1796
- };
1797
- }
1798
- function createOrgDocumentsClient() {
1799
- return {
1800
- create: async () => stub("organizations.documents.create"),
1801
- retrieve: async () => stub("organizations.documents.retrieve"),
1802
- list: async () => stub("organizations.documents.list"),
1803
- cancel: async () => stub("organizations.documents.cancel")
1804
- };
1805
- }
1806
-
1807
- // src/core/me.ts
1808
- function createMeClient(config = {}) {
1809
- return {
1810
- get: async () => {
1811
- if (!config._data) {
1812
- return stub("me.get");
1813
- }
1814
- try {
1815
- const account = await config._data.query(
1816
- api.openfort.queries.getMyAccount,
1817
- {}
1818
- );
1819
- return [null, account];
1820
- } catch (cause) {
1821
- return [fromConvexError(cause), null];
1822
- }
1823
- },
1824
- update: async (input) => {
1825
- if (!config._data) {
1826
- return stub("me.update");
1827
- }
1828
- if (input.countryCode !== void 0) {
1829
- return [
1830
- new CapxulError({
1831
- code: "INVALID_INPUT",
1832
- message: "me.update does not support countryCode yet \u2014 backend mutation only patches displayName and username.",
1833
- details: { field: "countryCode" }
1834
- }),
1835
- null
1836
- ];
1837
- }
1838
- try {
1839
- await config._data.mutation(api.openfort.mutations.updateProfile, {
1840
- displayName: input.name,
1841
- username: input.username
1842
- });
1843
- const account = await config._data.query(
1844
- api.openfort.queries.getMyAccount,
1845
- {}
1846
- );
1847
- return [null, account];
1848
- } catch (cause) {
1849
- return [fromConvexError(cause), null];
1850
- }
1851
- }
1852
- };
1853
- }
1854
-
1855
- // src/core/operations.ts
1856
- function createOperationsClient(config = {}) {
1857
- const retrieve = async (operationId) => {
1858
- if (!config._data) {
1859
- return stub("operations.retrieve");
1860
- }
1861
- try {
1862
- const operation = await config._data.query(api.operations.queries.retrieve, {
1863
- operationId
1864
- });
1865
- if (!operation) {
1866
- return [new CapxulError({
1867
- code: "NOT_FOUND",
1868
- message: `operation ${operationId} not found`
1869
- }), null];
1870
- }
1871
- return [null, operation];
1872
- } catch (cause) {
1873
- return [fromConvexError(cause), null];
1874
- }
1875
- };
1876
- return {
1877
- retrieve,
1878
- wait: async (operationId, input = {}) => {
1879
- if (!config._data) {
1880
- return stub("operations.wait");
1881
- }
1882
- const until = new Set(
1883
- input.until ?? ["succeeded", "failed", "canceled", "indexed"]
1884
- );
1885
- const timeoutMs = (input.timeoutSeconds ?? 60) * 1e3;
1886
- const pollIntervalMs = input.pollIntervalMs ?? 1e3;
1887
- const deadline = Date.now() + timeoutMs;
1888
- while (Date.now() <= deadline) {
1889
- const [error, operation] = await retrieve(operationId);
1890
- if (error) {
1891
- return [error, null];
1892
- }
1893
- if (until.has(operation.status)) {
1894
- return [null, operation];
1895
- }
1896
- await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
1897
- }
1898
- return [new CapxulError({
1899
- code: "OPERATION_TIMEOUT",
1900
- message: `operation ${operationId} did not reach a terminal state before the timeout`,
1901
- details: {
1902
- operationId,
1903
- timeoutSeconds: input.timeoutSeconds ?? 60,
1904
- pollIntervalMs
1905
- }
1906
- }), null];
1907
- }
1908
- };
1909
- }
1910
- function toTokenUnits(value, decimals = 6) {
1911
- return parseUnits(value, decimals);
1912
- }
1913
-
1914
- // src/core/token-registry.ts
1915
- function resolvePaymentToken(currency) {
1916
- const normalized = currency.trim().toUpperCase();
1917
- if (normalized === "USD" || normalized === "USDC") {
1918
- return {
1919
- address: TEST_USDC_ADDRESS.toLowerCase(),
1920
- decimals: 6,
1921
- symbol: "USDC"
1922
- };
1923
- }
1924
- throw new CapxulError({
1925
- code: "NOT_IMPLEMENTED",
1926
- message: `Currency ${currency} is not yet supported by the token registry.`,
1927
- details: { currency: normalized }
1928
- });
1929
- }
1930
- function createCapxulBundler(config) {
1931
- const paymaster = createPaymasterClient({
1932
- transport: http(config.rpcUrl)
1933
- });
1934
- return createBundlerClient({
1935
- chain: baseSepolia,
1936
- transport: http(config.rpcUrl),
1937
- paymaster,
1938
- paymasterContext: { policyId: config.gasPolicyId }
1939
- });
1940
- }
1941
- var CAPXUL_PAYMENTS_SEND_ABI = [
1942
- {
1943
- name: "send",
1944
- type: "function",
1945
- stateMutability: "nonpayable",
1946
- inputs: [
1947
- { name: "token", type: "address" },
1948
- { name: "recipient", type: "address" },
1949
- { name: "amount", type: "uint256" },
1950
- { name: "documentHash", type: "bytes32" },
1951
- { name: "paymentType", type: "uint8" }
1952
- ],
1953
- outputs: []
1954
- }
1955
- ];
1956
- var ERC20_APPROVE_ABI = [
1957
- {
1958
- name: "approve",
1959
- type: "function",
1960
- stateMutability: "nonpayable",
1961
- inputs: [
1962
- { name: "spender", type: "address" },
1963
- { name: "amount", type: "uint256" }
1964
- ],
1965
- outputs: [{ name: "", type: "bool" }]
1966
- }
1967
- ];
1968
- function encodeOwnerTransferCalls(params) {
1969
- const documentHash = params.documentHash ?? "0x" + "0".repeat(64);
1970
- const paymentType = params.paymentType ?? 0;
1971
- const approve = encodeFunctionData({
1972
- abi: ERC20_APPROVE_ABI,
1973
- functionName: "approve",
1974
- args: [CAPXUL_PAYMENTS_ADDRESS, params.amount]
1975
- });
1976
- const send = encodeFunctionData({
1977
- abi: CAPXUL_PAYMENTS_SEND_ABI,
1978
- functionName: "send",
1979
- args: [
1980
- params.tokenAddress,
1981
- params.recipientAddress,
1982
- params.amount,
1983
- documentHash,
1984
- paymentType
1985
- ]
1986
- });
1987
- return [
1988
- {
1989
- to: params.tokenAddress.toLowerCase(),
1990
- data: approve,
1991
- value: 0n
1992
- },
1993
- {
1994
- to: CAPXUL_PAYMENTS_ADDRESS,
1995
- data: send,
1996
- value: 0n
1997
- }
1998
- ];
1999
- }
2000
-
2001
- // src/internal/safe/operations.ts
2002
- var USER_OP_RECEIPT_TIMEOUT_MS = 12e4;
2003
- async function transferAsOwner(config, params) {
2004
- try {
2005
- const safeAccount = await buildSafeAccount(config.signer, config.signing);
2006
- const bundler = createCapxulBundler(config.signing);
2007
- const calls = encodeOwnerTransferCalls(params);
2008
- const userOpHash = await bundler.sendUserOperation({
2009
- account: safeAccount,
2010
- calls
2011
- });
2012
- const receipt = await bundler.waitForUserOperationReceipt({
2013
- hash: userOpHash,
2014
- timeout: USER_OP_RECEIPT_TIMEOUT_MS
2015
- });
2016
- return {
2017
- txHash: receipt.receipt.transactionHash,
2018
- userOpHash,
2019
- blockNumber: Number(receipt.receipt.blockNumber),
2020
- success: receipt.success,
2021
- logs: receipt.receipt.logs
2022
- };
2023
- } catch (cause) {
2024
- throw new CapxulError({
2025
- code: "NETWORK_ERROR",
2026
- message: cause instanceof Error ? cause.message : String(cause),
2027
- cause
2028
- });
2029
- }
2030
- }
2031
-
2032
- // src/core/payments.ts
2033
- function createPaymentsClient(config = {}) {
2034
- return {
2035
- create: async (input) => {
2036
- if (!config._data || !config.signer || !config.signing) {
2037
- return stub("payments.create");
2038
- }
2039
- let created = null;
2040
- let submitted = null;
2041
- try {
2042
- created = await config._data.mutation(api.payments.mutations.create, {
2043
- to: input.to,
2044
- amount: input.amount,
2045
- reference: input.reference,
2046
- idempotencyKey: input.idempotencyKey,
2047
- source: input.source
2048
- });
2049
- if (!created) {
2050
- return [
2051
- new CapxulError({
2052
- code: "NETWORK_ERROR",
2053
- message: "payments.create returned no payment resource"
2054
- }),
2055
- null
2056
- ];
2057
- }
2058
- if (created.status !== "processing" || created.operation.status !== "processing") {
2059
- return [null, created];
2060
- }
2061
- const currentSigner = await config._data.query(
2062
- api.safe.queries.getMySignerAddress,
2063
- {}
2064
- );
2065
- if (!currentSigner?.address) {
2066
- throw new CapxulError({
2067
- code: "PERMISSION_DENIED",
2068
- message: "No signer is registered for the authenticated account.",
2069
- details: { paymentId: created.id }
2070
- });
2071
- }
2072
- if (getAddress(currentSigner.address) !== getAddress(config.signer.address)) {
2073
- throw new CapxulError({
2074
- code: "PERMISSION_DENIED",
2075
- message: "Configured signer does not match the authenticated account signer.",
2076
- details: {
2077
- paymentId: created.id,
2078
- expectedSignerAddress: currentSigner.address,
2079
- actualSignerAddress: config.signer.address
2080
- }
2081
- });
2082
- }
2083
- const submission = await config._data.query(
2084
- api.payments.queries.prepareSubmission,
2085
- {
2086
- paymentId: created.id
2087
- }
2088
- );
2089
- if (!submission?.recipientAddress) {
2090
- throw new CapxulError({
2091
- code: "NETWORK_ERROR",
2092
- message: "payments.prepareSubmission returned no recipient address.",
2093
- details: { paymentId: created.id }
2094
- });
2095
- }
2096
- const token = resolvePaymentToken(submission.amount.currency);
2097
- const transfer = await transferAsOwner(
2098
- {
2099
- signer: config.signer,
2100
- signing: config.signing
2101
- },
2102
- {
2103
- tokenAddress: token.address,
2104
- recipientAddress: submission.recipientAddress,
2105
- amount: toTokenUnits(submission.amount.value, token.decimals)
2106
- }
2107
- );
2108
- if (!transfer.success) {
2109
- throw new CapxulError({
2110
- code: "NETWORK_ERROR",
2111
- message: "Bundler submission did not succeed.",
2112
- details: {
2113
- paymentId: created.id,
2114
- txHash: transfer.txHash,
2115
- userOpHash: transfer.userOpHash
2116
- }
2117
- });
2118
- }
2119
- submitted = {
2120
- txHash: transfer.txHash,
2121
- userOpHash: transfer.userOpHash
2122
- };
2123
- await config._data.mutation(api.payments.mutations.recordSubmitted, {
2124
- paymentId: created.id,
2125
- txHash: transfer.txHash,
2126
- userOpHash: transfer.userOpHash,
2127
- source: "sdk"
2128
- });
2129
- return [null, created];
2130
- } catch (cause) {
2131
- const error = mapCreateError(fromConvexError(cause));
2132
- if (created?.id && created.status === "processing" && !submitted) {
2133
- await bestEffortMarkFailed({ _data: config._data }, created.id, error);
2134
- }
2135
- if (submitted && created?.id) {
2136
- return [
2137
- new CapxulError({
2138
- code: "NETWORK_ERROR",
2139
- message: "Payment was submitted on-chain, but backend submission tracking failed.",
2140
- cause,
2141
- details: {
2142
- paymentId: created.id,
2143
- txHash: submitted.txHash,
2144
- userOpHash: submitted.userOpHash
2145
- }
2146
- }),
2147
- null
2148
- ];
2149
- }
2150
- return [error, null];
2151
- }
2152
- },
2153
- retrieve: async (paymentId) => {
2154
- if (!config._data) {
2155
- return stub("payments.retrieve");
2156
- }
2157
- try {
2158
- const payment = await config._data.query(
2159
- api.payments.queries.retrieve,
2160
- {
2161
- paymentId
2162
- }
2163
- );
2164
- if (!payment) {
2165
- return [
2166
- new CapxulError({
2167
- code: "NOT_FOUND",
2168
- message: `payment ${paymentId} not found`
2169
- }),
2170
- null
2171
- ];
2172
- }
2173
- return [null, payment];
2174
- } catch (cause) {
2175
- return [fromConvexError(cause), null];
2176
- }
2177
- },
2178
- list: async (input) => {
2179
- if (!config._data) {
2180
- return stub("payments.list");
2181
- }
2182
- try {
2183
- const page = await config._data.query(api.payments.queries.list, {
2184
- limit: input?.limit,
2185
- cursor: input?.cursor
2186
- });
2187
- return [null, page];
2188
- } catch (cause) {
2189
- return [fromConvexError(cause), null];
2190
- }
2191
- }
2192
- };
2193
- }
2194
- function createOrgPaymentsClient() {
2195
- return {
2196
- create: async () => stub(
2197
- "organizations.payments.create"
2198
- ),
2199
- retrieve: async () => stub("organizations.payments.retrieve"),
2200
- list: async () => stub("organizations.payments.list")
2201
- };
2202
- }
2203
- async function bestEffortMarkFailed(config, paymentId, error) {
2204
- try {
2205
- await config._data.mutation(api.payments.mutations.markFailed, {
2206
- paymentId,
2207
- errorCode: error.code,
2208
- errorMessage: error.message,
2209
- source: "sdk"
2210
- });
2211
- } catch {
2212
- }
2213
- }
2214
- function mapCreateError(error) {
2215
- switch (error.code) {
2216
- case "NOT_AUTHENTICATED":
2217
- case "PERMISSION_DENIED":
2218
- case "INVALID_INPUT":
2219
- case "INVALID_RECIPIENT":
2220
- case "INSUFFICIENT_BALANCE":
2221
- case "IDEMPOTENCY_CONFLICT":
2222
- case "RATE_LIMITED":
2223
- case "NETWORK_ERROR":
2224
- return error;
2225
- default:
2226
- return new CapxulError({
2227
- code: "NETWORK_ERROR",
2228
- message: error.message,
2229
- cause: error,
2230
- details: error.details,
2231
- operationId: error.operationId,
2232
- correlationId: error.correlationId,
2233
- retryable: error.retryable
2234
- });
2235
- }
2236
- }
2237
-
2238
- // src/core/transfers.ts
2239
- function createTransfersClient() {
2240
- return {
2241
- create: async () => stub("transfers.create"),
2242
- retrieve: async () => stub("transfers.retrieve"),
2243
- list: async () => stub("transfers.list"),
2244
- confirm: async () => stub("transfers.confirm"),
2245
- cancel: async () => stub("transfers.cancel")
2246
- };
2247
- }
2248
- function createOrgTransfersClient() {
2249
- return {
2250
- create: async () => stub(
2251
- "organizations.transfers.create"
2252
- ),
2253
- retrieve: async () => stub("organizations.transfers.retrieve"),
2254
- list: async () => stub("organizations.transfers.list"),
2255
- confirm: async () => stub("organizations.transfers.confirm"),
2256
- cancel: async () => stub("organizations.transfers.cancel")
2257
- };
2258
- }
2259
- function createWithdrawalsClient(config = {}) {
2260
- return {
2261
- create: async (input) => {
2262
- if (!config._data) {
2263
- return stub("withdrawals.create");
2264
- }
2265
- const [createErr, createdRaw] = await tryCatch(
2266
- config._data.mutation(api.withdrawals.mutations.create, {
2267
- amount: input.amount,
2268
- destination: {
2269
- externalAccountId: input.destination.externalAccountId
2270
- },
2271
- source: input.source,
2272
- reference: input.reference,
2273
- idempotencyKey: input.idempotencyKey
2274
- })
2275
- );
2276
- if (createErr) {
2277
- return [mapCreateError2(fromConvexError(createErr)), null];
2278
- }
2279
- const created = createdRaw;
2280
- if (!created) {
2281
- return [
2282
- new CapxulError({
2283
- code: "NETWORK_ERROR",
2284
- message: "withdrawals.create returned no withdrawal resource"
2285
- }),
2286
- null
2287
- ];
2288
- }
2289
- if (created.status !== "processing" || created.operation.status !== "processing") {
2290
- return [null, created];
2291
- }
2292
- if (!config.signer || !config.signing) {
2293
- return [null, created];
2294
- }
2295
- const [signerErr, currentSigner] = await tryCatch(
2296
- config._data.query(api.safe.queries.getMySignerAddress, {})
2297
- );
2298
- if (signerErr) {
2299
- return await handleSubmissionFailure(
2300
- { _data: config._data },
2301
- created.id,
2302
- mapCreateError2(fromConvexError(signerErr))
2303
- );
2304
- }
2305
- if (!currentSigner?.address) {
2306
- return await handleSubmissionFailure(
2307
- { _data: config._data },
2308
- created.id,
2309
- new CapxulError({
2310
- code: "PERMISSION_DENIED",
2311
- message: "No signer is registered for the authenticated account.",
2312
- details: { withdrawalId: created.id }
2313
- })
2314
- );
2315
- }
2316
- if (getAddress(currentSigner.address) !== getAddress(config.signer.address)) {
2317
- return await handleSubmissionFailure(
2318
- { _data: config._data },
2319
- created.id,
2320
- new CapxulError({
2321
- code: "PERMISSION_DENIED",
2322
- message: "Configured signer does not match the authenticated account signer.",
2323
- details: {
2324
- withdrawalId: created.id,
2325
- expectedSignerAddress: currentSigner.address,
2326
- actualSignerAddress: config.signer.address
2327
- }
2328
- })
2329
- );
2330
- }
2331
- const [prepErr, submission] = await tryCatch(
2332
- config._data.query(api.withdrawals.queries.prepareSubmission, {
2333
- withdrawalId: created.id
2334
- })
2335
- );
2336
- if (prepErr) {
2337
- return await handleSubmissionFailure(
2338
- { _data: config._data },
2339
- created.id,
2340
- mapCreateError2(fromConvexError(prepErr))
2341
- );
2342
- }
2343
- const destinationAddress = submission?.destinationAddress;
2344
- if (!submission || !destinationAddress) {
2345
- return await handleSubmissionFailure(
2346
- { _data: config._data },
2347
- created.id,
2348
- new CapxulError({
2349
- code: "NETWORK_ERROR",
2350
- message: "withdrawals.prepareSubmission returned no destination.",
2351
- details: { withdrawalId: created.id }
2352
- })
2353
- );
2354
- }
2355
- const token = resolvePaymentToken(submission.amount.currency);
2356
- const [transferErr, transferOk] = await tryCatch(
2357
- transferAsOwner(
2358
- {
2359
- signer: config.signer,
2360
- signing: config.signing
2361
- },
2362
- {
2363
- tokenAddress: token.address,
2364
- recipientAddress: destinationAddress,
2365
- amount: toTokenUnits(submission.amount.value, token.decimals)
2366
- }
2367
- )
2368
- );
2369
- if (transferErr) {
2370
- return await handleSubmissionFailure(
2371
- { _data: config._data },
2372
- created.id,
2373
- mapCreateError2(fromConvexError(transferErr))
2374
- );
2375
- }
2376
- if (!transferOk.success) {
2377
- return await handleSubmissionFailure(
2378
- { _data: config._data },
2379
- created.id,
2380
- new CapxulError({
2381
- code: "NETWORK_ERROR",
2382
- message: "Bundler submission did not succeed.",
2383
- details: {
2384
- withdrawalId: created.id,
2385
- txHash: transferOk.txHash,
2386
- userOpHash: transferOk.userOpHash
2387
- }
2388
- })
2389
- );
2390
- }
2391
- const [recordErr] = await tryCatch(
2392
- config._data.mutation(api.withdrawals.mutations.recordSubmitted, {
2393
- withdrawalId: created.id,
2394
- txHash: transferOk.txHash,
2395
- userOpHash: transferOk.userOpHash
2396
- })
2397
- );
2398
- if (recordErr) {
2399
- return [
2400
- new CapxulError({
2401
- code: "NETWORK_ERROR",
2402
- message: "Withdrawal was submitted on-chain, but backend submission tracking failed.",
2403
- cause: recordErr,
2404
- details: {
2405
- withdrawalId: created.id,
2406
- txHash: transferOk.txHash,
2407
- userOpHash: transferOk.userOpHash
2408
- }
2409
- }),
2410
- null
2411
- ];
2412
- }
2413
- return [null, created];
2414
- },
2415
- retrieve: async (withdrawalId) => {
2416
- if (!config._data) {
2417
- return stub("withdrawals.retrieve");
2418
- }
2419
- const [err, raw] = await tryCatch(
2420
- config._data.query(api.withdrawals.queries.retrieve, { withdrawalId })
2421
- );
2422
- if (err) {
2423
- return [fromConvexError(err), null];
2424
- }
2425
- const withdrawal = raw;
2426
- if (!withdrawal) {
2427
- return [
2428
- new CapxulError({
2429
- code: "NOT_FOUND",
2430
- message: `withdrawal ${withdrawalId} not found`
2431
- }),
2432
- null
2433
- ];
2434
- }
2435
- return [null, withdrawal];
2436
- },
2437
- list: async (input) => {
2438
- if (!config._data) {
2439
- return stub("withdrawals.list");
2440
- }
2441
- const [err, raw] = await tryCatch(
2442
- config._data.query(api.withdrawals.queries.list, {
2443
- limit: input?.limit,
2444
- cursor: input?.cursor
2445
- })
2446
- );
2447
- if (err) {
2448
- return [fromConvexError(err), null];
2449
- }
2450
- return [null, raw];
2451
- },
2452
- recordCompleted: async (input) => {
2453
- if (!config._data) {
2454
- return stub(
2455
- "withdrawals.recordCompleted"
2456
- );
2457
- }
2458
- const [err] = await tryCatch(
2459
- config._data.mutation(api.withdrawals.mutations.recordCompleted, {
2460
- withdrawalId: input.withdrawalId,
2461
- txHash: input.txHash
2462
- })
2463
- );
2464
- if (err) {
2465
- return [
2466
- mapRecordCompletedError(fromConvexError(err)),
2467
- null
2468
- ];
2469
- }
2470
- return [null, null];
2471
- }
2472
- };
2473
- }
2474
- function createOrgWithdrawalsClient(config = {}) {
2475
- return {
2476
- /**
2477
- * Org-scope create (Withdrawals v1 W2, #465).
2478
- *
2479
- * D6 — returns the `processing` row only. No `transferAsOwner`
2480
- * tail, no `recordSubmitted` call. Org Safe + Zodiac submission
2481
- * orchestration ships in W3+.
2482
- */
2483
- create: async (input) => {
2484
- if (!config._data) {
2485
- return stub(
2486
- "organizations.withdrawals.create"
2487
- );
2488
- }
2489
- const [err, raw] = await tryCatch(
2490
- config._data.mutation(api.withdrawals.mutations.createOrg, {
2491
- organizationId: input.organizationId,
2492
- amount: input.amount,
2493
- destination: {
2494
- externalAccountId: input.destination.externalAccountId
2495
- },
2496
- source: input.source,
2497
- reference: input.reference,
2498
- idempotencyKey: input.idempotencyKey
2499
- })
2500
- );
2501
- if (err) {
2502
- return [mapCreateError2(fromConvexError(err)), null];
2503
- }
2504
- const created = raw;
2505
- if (!created) {
2506
- return [
2507
- new CapxulError({
2508
- code: "NETWORK_ERROR",
2509
- message: "organizations.withdrawals.create returned no withdrawal resource"
2510
- }),
2511
- null
2512
- ];
2513
- }
2514
- return [null, created];
2515
- },
2516
- retrieve: async (input) => {
2517
- if (!config._data) {
2518
- return stub(
2519
- "organizations.withdrawals.retrieve"
2520
- );
2521
- }
2522
- const [err, raw] = await tryCatch(
2523
- config._data.query(api.withdrawals.queries.retrieve, {
2524
- withdrawalId: input.withdrawalId
2525
- })
2526
- );
2527
- if (err) {
2528
- return [fromConvexError(err), null];
2529
- }
2530
- const withdrawal = raw;
2531
- if (!withdrawal) {
2532
- return [
2533
- new CapxulError({
2534
- code: "NOT_FOUND",
2535
- message: `withdrawal ${input.withdrawalId} not found`
2536
- }),
2537
- null
2538
- ];
2539
- }
2540
- const ownerCheck = withdrawal.owner;
2541
- if (ownerCheck?.type !== "organization" || ownerCheck.id !== input.organizationId) {
2542
- return [
2543
- new CapxulError({
2544
- code: "NOT_FOUND",
2545
- message: `withdrawal ${input.withdrawalId} does not belong to organization ${input.organizationId}`
2546
- }),
2547
- null
2548
- ];
2549
- }
2550
- return [null, withdrawal];
2551
- },
2552
- list: async (input) => {
2553
- if (!config._data) {
2554
- return stub(
2555
- "organizations.withdrawals.list"
2556
- );
2557
- }
2558
- const [err, raw] = await tryCatch(
2559
- config._data.query(api.withdrawals.queries.listOrg, {
2560
- organizationId: input.organizationId,
2561
- limit: input.limit,
2562
- cursor: input.cursor
2563
- })
2564
- );
2565
- if (err) {
2566
- return [fromConvexError(err), null];
2567
- }
2568
- return [null, raw];
2569
- }
2570
- };
2571
- }
2572
- async function handleSubmissionFailure(config, withdrawalId, error) {
2573
- await bestEffortMarkFailed2(config, withdrawalId, error);
2574
- return [error, null];
2575
- }
2576
- async function bestEffortMarkFailed2(config, withdrawalId, error) {
2577
- await tryCatch(
2578
- config._data.mutation(api.withdrawals.mutations.markFailed, {
2579
- withdrawalId,
2580
- errorCode: error.code,
2581
- errorMessage: error.message
2582
- })
2583
- );
2584
- }
2585
- function mapCreateError2(error) {
2586
- switch (error.code) {
2587
- case "NOT_AUTHENTICATED":
2588
- case "PERMISSION_DENIED":
2589
- case "INVALID_INPUT":
2590
- case "INSUFFICIENT_BALANCE":
2591
- case "IDEMPOTENCY_CONFLICT":
2592
- case "KYC_REQUIRED":
2593
- case "POLICY_DENIED":
2594
- case "RATE_LIMITED":
2595
- case "NETWORK_ERROR":
2596
- case "NOT_FOUND":
2597
- case "VERIFICATION_REQUIRED":
2598
- return error;
2599
- default:
2600
- return new CapxulError({
2601
- code: "NETWORK_ERROR",
2602
- message: error.message,
2603
- cause: error,
2604
- details: error.details,
2605
- operationId: error.operationId,
2606
- correlationId: error.correlationId,
2607
- retryable: error.retryable
2608
- });
2609
- }
2610
- }
2611
- function mapRecordCompletedError(error) {
2612
- switch (error.code) {
2613
- case "NOT_AUTHENTICATED":
2614
- case "PERMISSION_DENIED":
2615
- case "INVALID_INPUT":
2616
- case "NOT_FOUND":
2617
- case "NETWORK_ERROR":
2618
- case "INTERNAL_ERROR":
2619
- return error;
2620
- default:
2621
- return new CapxulError({
2622
- code: "NETWORK_ERROR",
2623
- message: error.message,
2624
- cause: error,
2625
- details: error.details,
2626
- operationId: error.operationId,
2627
- correlationId: error.correlationId,
2628
- retryable: error.retryable
2629
- });
2630
- }
2631
- }
2632
-
2633
- // src/core/webhook-endpoints.ts
2634
- function createWebhookEndpointsClient() {
2635
- return {
2636
- create: async () => stub(
2637
- "webhookEndpoints.create"
2638
- ),
2639
- retrieve: async () => stub("webhookEndpoints.retrieve"),
2640
- list: async () => stub("webhookEndpoints.list"),
2641
- remove: async () => stub("webhookEndpoints.remove")
2642
- };
2643
- }
2644
-
2645
- // src/core/webhook-events.ts
2646
- function createWebhookEventsClient() {
2647
- return {
2648
- retrieve: async () => stub("webhookEvents.retrieve"),
2649
- list: async () => stub("webhookEvents.list")
2650
- };
2651
- }
2652
-
2653
- // src/core/organizations.ts
2654
- function createOrgExternalAccountsClient(config) {
2655
- return {
2656
- create: async (input) => {
2657
- if (!config._data) {
2658
- return stub(
2659
- "organizations.externalAccounts.create"
2660
- );
2661
- }
2662
- const [err, raw] = await tryCatch(
2663
- config._data.mutation(api.externalAccounts.mutations.createOrg, {
2664
- organizationId: input.organizationId,
2665
- kind: input.kind,
2666
- label: input.label,
2667
- address: input.address,
2668
- iban: input.iban,
2669
- bic: input.bic,
2670
- accountHolder: input.accountHolder,
2671
- network: input.network,
2672
- panToken: input.panToken,
2673
- last4: input.last4
2674
- })
2675
- );
2676
- if (err) {
2677
- return [fromConvexError(err), null];
2678
- }
2679
- if (!raw) {
2680
- return [
2681
- new CapxulError({
2682
- code: "NOT_FOUND",
2683
- message: "external_account creation returned no resource"
2684
- }),
2685
- null
2686
- ];
2687
- }
2688
- return [null, brandExternalAccount(raw)];
2689
- },
2690
- list: async (input) => {
2691
- if (!config._data) {
2692
- return stub(
2693
- "organizations.externalAccounts.list"
2694
- );
2695
- }
2696
- const [err, result] = await tryCatch(
2697
- config._data.query(api.externalAccounts.queries.listOrg, {
2698
- organizationId: input.organizationId,
2699
- limit: input.limit,
2700
- cursor: input.cursor
2701
- })
2702
- );
2703
- if (err) {
2704
- return [fromConvexError(err), null];
2705
- }
2706
- const branded = result.data.map(
2707
- (row) => brandExternalAccount(row)
2708
- );
2709
- return [
2710
- null,
2711
- {
2712
- object: "list",
2713
- data: branded,
2714
- page: result.page
2715
- }
2716
- ];
2717
- },
2718
- retrieve: async (input) => {
2719
- if (!config._data) {
2720
- return stub(
2721
- "organizations.externalAccounts.retrieve"
2722
- );
2723
- }
2724
- const [err, raw] = await tryCatch(
2725
- config._data.query(api.externalAccounts.queries.retrieveOrg, {
2726
- organizationId: input.organizationId,
2727
- externalAccountId: input.externalAccountId
2728
- })
2729
- );
2730
- if (err) {
2731
- return [fromConvexError(err), null];
2732
- }
2733
- if (!raw) {
2734
- return [
2735
- new CapxulError({
2736
- code: "NOT_FOUND",
2737
- message: `external_account ${input.externalAccountId} not found`
2738
- }),
2739
- null
2740
- ];
2741
- }
2742
- return [null, brandExternalAccount(raw)];
2743
- },
2744
- remove: async (input) => {
2745
- if (!config._data) {
2746
- return stub("organizations.externalAccounts.remove");
2747
- }
2748
- const [err] = await tryCatch(
2749
- config._data.mutation(api.externalAccounts.mutations.removeOrg, {
2750
- organizationId: input.organizationId,
2751
- externalAccountId: input.externalAccountId
2752
- })
2753
- );
2754
- if (err) {
2755
- return [fromConvexError(err), null];
2756
- }
2757
- return [null, void 0];
2758
- }
2759
- };
2760
- }
2761
- function createOrgSubAccountsClient(config) {
2762
- return {
2763
- create: async (input) => {
2764
- if (!config._data) {
2765
- return stub(
2766
- "organizations.subAccounts.create"
2767
- );
2768
- }
2769
- const [err, raw] = await tryCatch(
2770
- config._data.mutation(api.subAccounts.mutations.create, {
2771
- parent: {
2772
- kind: "organization",
2773
- id: input.organizationId
2774
- },
2775
- name: input.name,
2776
- purpose: input.purpose
2777
- })
2778
- );
2779
- if (err) {
2780
- return [
2781
- fromConvexError(err),
2782
- null
2783
- ];
2784
- }
2785
- if (!raw) {
2786
- return [
2787
- new CapxulError({
2788
- code: "NOT_FOUND",
2789
- message: "sub_account creation returned no resource"
2790
- }),
2791
- null
2792
- ];
2793
- }
2794
- const [brandErr, branded] = tryBrandSubAccount(raw);
2795
- if (brandErr) {
2796
- return [brandErr, null];
2797
- }
2798
- return [null, branded];
2799
- },
2800
- list: async (input) => {
2801
- if (!config._data) {
2802
- return stub(
2803
- "organizations.subAccounts.list"
2804
- );
2805
- }
2806
- const [err, rows] = await tryCatch(
2807
- config._data.query(api.subAccounts.queries.listByOrganization, {
2808
- organizationId: input.organizationId
2809
- })
2810
- );
2811
- if (err) {
2812
- return [
2813
- fromConvexError(err),
2814
- null
2815
- ];
2816
- }
2817
- const branded = [];
2818
- for (const row of rows) {
2819
- const [brandErr, value] = tryBrandSubAccount(row);
2820
- if (brandErr) {
2821
- return [brandErr, null];
2822
- }
2823
- branded.push(value);
2824
- }
2825
- return [
2826
- null,
2827
- {
2828
- object: "list",
2829
- data: branded,
2830
- page: { hasMore: false }
2831
- }
2832
- ];
2833
- },
2834
- retrieve: async (input) => {
2835
- if (!config._data) {
2836
- return stub(
2837
- "organizations.subAccounts.retrieve"
2838
- );
2839
- }
2840
- const [err, raw] = await tryCatch(
2841
- config._data.query(api.subAccounts.queries.retrieve, {
2842
- subAccountId: input.subAccountId
2843
- })
2844
- );
2845
- if (err) {
2846
- return [
2847
- fromConvexError(err),
2848
- null
2849
- ];
2850
- }
2851
- if (!raw) {
2852
- return [
2853
- new CapxulError({
2854
- code: "NOT_FOUND",
2855
- message: `sub_account ${input.subAccountId} not found`
2856
- }),
2857
- null
2858
- ];
2859
- }
2860
- const [brandErr, branded] = tryBrandSubAccount(raw);
2861
- if (brandErr) {
2862
- return [
2863
- brandErr,
2864
- null
2865
- ];
2866
- }
2867
- return [null, branded];
2868
- },
2869
- remove: async (input) => {
2870
- if (!config._data) {
2871
- return stub(
2872
- "organizations.subAccounts.remove"
2873
- );
2874
- }
2875
- const [err, raw] = await tryCatch(
2876
- config._data.mutation(api.subAccounts.mutations.archive, {
2877
- subAccountId: input.subAccountId
2878
- })
2879
- );
2880
- if (err) {
2881
- return [
2882
- fromConvexError(err),
2883
- null
2884
- ];
2885
- }
2886
- if (!raw) {
2887
- return [
2888
- new CapxulError({
2889
- code: "NOT_FOUND",
2890
- message: `sub_account ${input.subAccountId} not found`
2891
- }),
2892
- null
2893
- ];
2894
- }
2895
- const [brandErr, branded] = tryBrandSubAccount(raw);
2896
- if (brandErr) {
2897
- return [
2898
- brandErr,
2899
- null
2900
- ];
2901
- }
2902
- return [null, branded];
2903
- }
2904
- };
2905
- }
2906
- function createOrganizationsClient(config = {}) {
2907
- return {
2908
- create: async (input) => {
2909
- if (!config._data) {
2910
- return stub("organizations.create");
2911
- }
2912
- if (input.country !== void 0) {
2913
- return [
2914
- new CapxulError({
2915
- code: "INVALID_INPUT",
2916
- message: "organizations.create does not support country yet \u2014 backend mutation only accepts name.",
2917
- details: { field: "country" }
2918
- }),
2919
- null
2920
- ];
2921
- }
2922
- try {
2923
- const orgId = await config._data.mutation(api.org.mutations.create, {
2924
- name: input.name
2925
- });
2926
- const org = await config._data.query(api.org.queries.retrieve, {
2927
- orgId
2928
- });
2929
- if (!org) {
2930
- return [
2931
- new CapxulError({
2932
- code: "NETWORK_ERROR",
2933
- message: "organization created but could not be retrieved"
2934
- }),
2935
- null
2936
- ];
2937
- }
2938
- return [null, org];
2939
- } catch (cause) {
2940
- return [fromConvexError(cause), null];
2941
- }
2942
- },
2943
- retrieve: async (organizationId) => {
2944
- if (!config._data) {
2945
- return stub("organizations.retrieve");
2946
- }
2947
- try {
2948
- const orgId = organizationId.replace(/^org_/, "");
2949
- const org = await config._data.query(api.org.queries.retrieve, {
2950
- orgId
2951
- });
2952
- if (!org) {
2953
- return [
2954
- new CapxulError({
2955
- code: "NOT_FOUND",
2956
- message: `organization ${organizationId} not found`
2957
- }),
2958
- null
2959
- ];
2960
- }
2961
- return [null, org];
2962
- } catch (cause) {
2963
- return [fromConvexError(cause), null];
2964
- }
2965
- },
2966
- list: async (input) => {
2967
- if (!config._data) {
2968
- return stub("organizations.list");
2969
- }
2970
- try {
2971
- const page = await config._data.query(api.org.queries.list, {
2972
- limit: input?.limit,
2973
- cursor: input?.cursor
2974
- });
2975
- const result = {
2976
- object: "list",
2977
- data: page.data,
2978
- page: {
2979
- hasMore: page.hasMore,
2980
- cursor: page.nextCursor
2981
- }
2982
- };
2983
- return [null, result];
2984
- } catch (cause) {
2985
- return [fromConvexError(cause), null];
2986
- }
2987
- },
2988
- update: async (input) => {
2989
- if (!config._data) {
2990
- return stub("organizations.update");
2991
- }
2992
- try {
2993
- const orgId = input.organizationId.replace(/^org_/, "");
2994
- const org = await config._data.mutation(api.org.mutations.update, {
2995
- orgId,
2996
- name: input.name
2997
- });
2998
- if (!org) {
2999
- return [
3000
- new CapxulError({
3001
- code: "NOT_FOUND",
3002
- message: `organization ${input.organizationId} not found`
3003
- }),
3004
- null
3005
- ];
3006
- }
3007
- return [null, org];
3008
- } catch (cause) {
3009
- return [fromConvexError(cause), null];
3010
- }
3011
- },
3012
- safes: {
3013
- retrieve: async (input) => {
3014
- if (!config._data) {
3015
- return stub("organizations.safes.retrieve");
3016
- }
3017
- try {
3018
- const safe = await config._data.query(
3019
- api.safe.queries.retrieveOrganizationSafe,
3020
- input
3021
- );
3022
- if (!safe) {
3023
- return [
3024
- new CapxulError({
3025
- code: "NOT_FOUND",
3026
- message: `safe ${input.safeId} not found`
3027
- }),
3028
- null
3029
- ];
3030
- }
3031
- return [null, safe];
3032
- } catch (cause) {
3033
- return [
3034
- fromConvexError(cause),
3035
- null
3036
- ];
3037
- }
3038
- }
3039
- },
3040
- treasury: {
3041
- retrieve: async (organizationId) => {
3042
- if (!config._data) {
3043
- return stub(
3044
- "organizations.treasury.retrieve"
3045
- );
3046
- }
3047
- try {
3048
- const orgId = organizationId.replace(/^org_/, "");
3049
- const raw = await config._data.query(
3050
- api.safe.queries.getOrgTreasuryBalance,
3051
- { orgId }
3052
- );
3053
- if (!raw) {
3054
- return [
3055
- new CapxulError({
3056
- code: "NOT_FOUND",
3057
- message: `treasury for organization ${organizationId} not found`
3058
- }),
3059
- null
3060
- ];
3061
- }
3062
- const treasury = {
3063
- object: "treasury",
3064
- id: toTreasuryId(`try_${orgId}`),
3065
- organizationId,
3066
- status: "active",
3067
- safeId: toSafeId(
3068
- `safe_${raw.safeAddress.replace(/^0x/, "").toLowerCase()}`
3069
- ),
3070
- totalBalance: { value: "0", currency: "USD" },
3071
- positions: raw.tokens.map((t) => ({
3072
- symbol: t.symbol,
3073
- contractAddress: t.tokenAddress,
3074
- amount: t.balance
3075
- })),
3076
- asOf: raw.lastUpdatedAt ? new Date(raw.lastUpdatedAt).toISOString() : (/* @__PURE__ */ new Date()).toISOString()
3077
- };
3078
- return [null, treasury];
3079
- } catch (cause) {
3080
- return [
3081
- fromConvexError(cause),
3082
- null
3083
- ];
3084
- }
3085
- }
3086
- },
3087
- members: {
3088
- list: async (input) => {
3089
- if (!config._data?.action) {
3090
- return stub("organizations.members.list");
3091
- }
3092
- try {
3093
- const orgId = input.organizationId.replace(/^org_/, "");
3094
- const page = await config._data.action(api.org.actions.membersList, {
3095
- organizationId: orgId,
3096
- status: input.status,
3097
- limit: input.limit,
3098
- cursor: input.cursor
3099
- });
3100
- return [null, page];
3101
- } catch (cause) {
3102
- return [fromConvexError(cause), null];
3103
- }
3104
- },
3105
- retrieve: async (input) => {
3106
- if (!config._data?.action) {
3107
- return stub("organizations.members.retrieve");
3108
- }
3109
- try {
3110
- const orgId = input.organizationId.replace(/^org_/, "");
3111
- const memberId = input.memberId.replace(/^mb_/, "");
3112
- const member = await config._data.action(
3113
- api.org.actions.retrieveMember,
3114
- {
3115
- organizationId: orgId,
3116
- memberId
3117
- }
3118
- );
3119
- return [null, member];
3120
- } catch (cause) {
3121
- return [fromConvexError(cause), null];
3122
- }
3123
- },
3124
- invite: async (input) => {
3125
- if (!config._data?.action) {
3126
- return stub("organizations.members.invite");
3127
- }
3128
- try {
3129
- const orgId = input.organizationId.replace(/^org_/, "");
3130
- const result = await config._data.action(
3131
- api.org.actions.inviteMember,
3132
- {
3133
- organizationId: orgId,
3134
- email: input.email,
3135
- role: input.role
3136
- }
3137
- );
3138
- return [null, result];
3139
- } catch (cause) {
3140
- return [fromConvexError(cause), null];
3141
- }
3142
- },
3143
- accept: async (input) => {
3144
- if (!config._data?.action) {
3145
- return stub("organizations.members.accept");
3146
- }
3147
- try {
3148
- const member = await config._data.action(
3149
- api.org.actions.acceptInvitation,
3150
- { token: input.token }
3151
- );
3152
- return [null, member];
3153
- } catch (cause) {
3154
- return [fromConvexError(cause), null];
3155
- }
3156
- },
3157
- updateRole: async (input) => {
3158
- if (!config._data?.action) {
3159
- return stub("organizations.members.updateRole");
3160
- }
3161
- try {
3162
- const orgId = input.organizationId.replace(/^org_/, "");
3163
- const memberId = input.memberId.replace(/^mb_/, "");
3164
- const member = await config._data.action(
3165
- api.org.actions.updateMemberRole,
3166
- {
3167
- organizationId: orgId,
3168
- memberId,
3169
- role: input.role
3170
- }
3171
- );
3172
- return [null, member];
3173
- } catch (cause) {
3174
- return [fromConvexError(cause), null];
3175
- }
3176
- },
3177
- revoke: async (input) => {
3178
- if (!config._data?.action) {
3179
- return stub("organizations.members.revoke");
3180
- }
3181
- try {
3182
- const orgId = input.organizationId.replace(/^org_/, "");
3183
- const memberId = input.memberId.replace(/^mb_/, "");
3184
- const member = await config._data.action(
3185
- api.org.actions.revokeMember,
3186
- {
3187
- organizationId: orgId,
3188
- memberId
3189
- }
3190
- );
3191
- return [null, member];
3192
- } catch (cause) {
3193
- return [fromConvexError(cause), null];
3194
- }
3195
- },
3196
- remove: async (input) => {
3197
- if (!config._data?.action) {
3198
- return stub("organizations.members.remove");
3199
- }
3200
- try {
3201
- const orgId = input.organizationId.replace(/^org_/, "");
3202
- const memberId = input.memberId.replace(/^mb_/, "");
3203
- await config._data.action(api.org.actions.removeMember, {
3204
- organizationId: orgId,
3205
- memberId
3206
- });
3207
- return [null, void 0];
3208
- } catch (cause) {
3209
- return [fromConvexError(cause), null];
3210
- }
3211
- },
3212
- resend: async (input) => {
3213
- if (!config._data?.action) {
3214
- return stub("organizations.members.resend");
3215
- }
3216
- try {
3217
- const orgId = input.organizationId.replace(/^org_/, "");
3218
- const memberId = input.memberId.replace(/^mb_/, "");
3219
- const result = await config._data.action(
3220
- api.org.actions.resendInvitation,
3221
- {
3222
- organizationId: orgId,
3223
- memberId
3224
- }
3225
- );
3226
- return [null, result];
3227
- } catch (cause) {
3228
- return [fromConvexError(cause), null];
3229
- }
3230
- }
3231
- },
3232
- apiKeys: createApiKeysClient(),
3233
- subAccounts: createOrgSubAccountsClient(config),
3234
- externalAccounts: createOrgExternalAccountsClient(config),
3235
- balanceLedger: {
3236
- list: async (input) => {
3237
- if (!config._data) {
3238
- return stub(
3239
- "organizations.balanceLedger.list"
3240
- );
3241
- }
3242
- try {
3243
- const orgId = input.organizationId.replace(/^org_/, "");
3244
- const page = await config._data.query(
3245
- api.balanceLedger.queries.listForOrg,
3246
- { orgId, limit: input.limit, cursor: input.cursor }
3247
- );
3248
- return [null, page];
3249
- } catch (cause) {
3250
- return [fromConvexError(cause), null];
3251
- }
3252
- },
3253
- retrieve: async (input) => {
3254
- if (!config._data) {
3255
- return stub(
3256
- "organizations.balanceLedger.retrieve"
3257
- );
3258
- }
3259
- try {
3260
- const entry = await config._data.query(
3261
- api.balanceLedger.queries.retrieve,
3262
- { entryId: input.entryId }
3263
- );
3264
- if (!entry) {
3265
- return [
3266
- new CapxulError({
3267
- code: "NOT_FOUND",
3268
- message: `balance_ledger_entry ${input.entryId} not found`
3269
- }),
3270
- null
3271
- ];
3272
- }
3273
- return [null, entry];
3274
- } catch (cause) {
3275
- return [fromConvexError(cause), null];
3276
- }
3277
- }
3278
- },
3279
- payments: createOrgPaymentsClient(),
3280
- transfers: createOrgTransfersClient(),
3281
- withdrawals: createOrgWithdrawalsClient(config),
3282
- documents: createOrgDocumentsClient(),
3283
- webhookEndpoints: createWebhookEndpointsClient(),
3284
- webhookEvents: createWebhookEventsClient()
3285
- };
3286
- }
3287
-
3288
- // src/core/token-transfers.ts
3289
- var toTokenTransferId = (raw) => {
3290
- if (typeof raw !== "string" || raw.length === 0) {
3291
- throw new Error(
3292
- `Invalid tokenTransferId: expected non-empty string, got ${String(raw)}`
3293
- );
3294
- }
3295
- return raw;
3296
- };
3297
- function brandRow(row) {
3298
- return {
3299
- ...row,
3300
- id: toTokenTransferId(row.id)
3301
- };
3302
- }
3303
- function createTokenTransfersClient(config = {}) {
3304
- return {
3305
- list: async (input) => {
3306
- if (!config._data) {
3307
- return stub("tokenTransfers.list");
3308
- }
3309
- try {
3310
- const raw = await config._data.query(
3311
- api.tokenTransfers.queries.list,
3312
- {
3313
- limit: input?.limit,
3314
- cursor: input?.cursor,
3315
- direction: input?.direction
3316
- }
3317
- );
3318
- if (!raw) {
3319
- return [
3320
- new CapxulError({
3321
- code: "NOT_AUTHENTICATED",
3322
- message: "tokenTransfers.list requires an authenticated session."
3323
- }),
3324
- null
3325
- ];
3326
- }
3327
- return [
3328
- null,
3329
- {
3330
- object: "list",
3331
- data: raw.items.map(brandRow),
3332
- page: {
3333
- hasMore: raw.hasMore,
3334
- nextCursor: raw.nextCursor
3335
- },
3336
- displayCurrency: raw.displayCurrency
3337
- }
3338
- ];
3339
- } catch (cause) {
3340
- return [fromConvexError(cause), null];
3341
- }
3342
- },
3343
- retrieve: async (input) => {
3344
- if (!config._data) {
3345
- return stub("tokenTransfers.retrieve");
3346
- }
3347
- try {
3348
- const raw = await config._data.query(
3349
- api.tokenTransfers.queries.getByTxLogIndex,
3350
- {
3351
- txHash: input.txHash,
3352
- logIndex: input.logIndex,
3353
- chainId: input.chainId
3354
- }
3355
- );
3356
- if (!raw) {
3357
- return [
3358
- new CapxulError({
3359
- code: "NOT_FOUND",
3360
- message: `tokenTransfer (txHash=${input.txHash}, logIndex=${input.logIndex}) not found or not visible to caller.`,
3361
- details: {
3362
- txHash: input.txHash,
3363
- logIndex: input.logIndex,
3364
- chainId: input.chainId
3365
- }
3366
- }),
3367
- null
3368
- ];
3369
- }
3370
- return [null, brandRow(raw)];
3371
- } catch (cause) {
3372
- return [fromConvexError(cause), null];
3373
- }
3374
- }
3375
- };
3376
- }
3377
-
3378
- // src/core/virtual-accounts.ts
3379
- function createVirtualAccountsClient() {
3380
- return {
3381
- create: async () => stub("virtualAccounts.create"),
3382
- retrieve: async () => stub("virtualAccounts.retrieve"),
3383
- list: async () => stub("virtualAccounts.list"),
3384
- remove: async () => stub("virtualAccounts.remove")
3385
- };
3386
- }
3387
-
3388
- // src/core/virtual-cards.ts
3389
- function createVirtualCardsClient() {
3390
- return {
3391
- create: async () => stub("virtualCards.create"),
3392
- retrieve: async () => stub("virtualCards.retrieve"),
3393
- list: async () => stub("virtualCards.list"),
3394
- freeze: async () => stub("virtualCards.freeze"),
3395
- unfreeze: async () => stub("virtualCards.unfreeze"),
3396
- cancel: async () => stub("virtualCards.cancel")
3397
- };
3398
- }
3399
- function createAuthFlowMachine(client) {
3400
- return setup({
3401
- types: {},
3402
- actors: {
3403
- // XState v5's `fromPromise` injects an `AbortSignal` that aborts
3404
- // when the actor is stopped (parent transition fires, machine is
3405
- // disposed, etc.). Plumbing it through `client.auth.sendOtp` /
3406
- // `client.auth.verifyOtp` makes the in-flight HTTP request
3407
- // cancellable: stale responses can't race a state machine
3408
- // that's already moved on. See PR #406 S5.
3409
- sendOtp: fromPromise(async ({ input, signal }) => {
3410
- const [error] = await client.auth.sendOtp(
3411
- { email: input.email },
3412
- { signal }
3413
- );
3414
- if (error) throw error;
3415
- }),
3416
- verifyOtp: fromPromise(
3417
- async ({ input, signal }) => {
3418
- const [error, result] = await client.auth.verifyOtp(
3419
- {
3420
- email: input.email,
3421
- otp: input.code
3422
- },
3423
- { signal }
3424
- );
3425
- if (error) throw error;
3426
- if (result.kind === "bootstrap_required") {
3427
- throw new CapxulError({
3428
- code: "ACTION_REQUIRED",
3429
- message: "OTP verified but auth bootstrap is required. Use createAuthBootstrapFlowMachine for product sign-up.",
3430
- details: { reason: result.reason }
3431
- });
3432
- }
3433
- return result.session;
3434
- }
3435
- ),
3436
- signOut: fromPromise(async () => {
3437
- const [error] = await client.auth.signOut();
3438
- if (error) throw error;
3439
- })
3440
- },
3441
- actions: {
3442
- trackOtpRequested: ({ context }) => {
3443
- if (!context.email) return;
3444
- track("auth_otp_requested", {
3445
- email_domain: emailDomain(context.email)
3446
- });
3447
- },
3448
- trackOtpFailed: ({ event }) => {
3449
- const error = errorFromEvent(event);
3450
- track("auth_failed", {
3451
- auth_type: "email_otp",
3452
- reason: error.code
3453
- });
3454
- },
3455
- trackTimeoutFailed: () => {
3456
- track("auth_failed", {
3457
- auth_type: "email_otp",
3458
- reason: "timeout"
3459
- });
3460
- },
3461
- trackVerified: () => {
3462
- track("auth_verified", { auth_type: "email_otp" });
3463
- },
3464
- identifyAndTrack: ({ context }) => {
3465
- if (!context.session) return;
3466
- identify(context.session.authUserId, {
3467
- email_domain: emailDomain(context.session.email)
3468
- });
3469
- track("auth_identified", {
3470
- email_domain: emailDomain(context.session.email)
3471
- });
3472
- },
3473
- trackSignedOut: () => {
3474
- track("auth_signed_out");
3475
- }
3476
- }
3477
- }).createMachine({
3478
- id: "auth",
3479
- initial: "idle",
3480
- context: { email: null, session: null, error: null },
3481
- states: {
3482
- idle: {
3483
- on: {
3484
- REQUEST_OTP: {
3485
- target: "sending_otp",
3486
- actions: assign({
3487
- email: ({ event }) => event.email,
3488
- error: () => null
3489
- })
3490
- }
3491
- }
3492
- },
3493
- sending_otp: {
3494
- invoke: {
3495
- src: "sendOtp",
3496
- input: ({ context }) => ({ email: requireEmail(context) }),
3497
- onDone: {
3498
- target: "otp_requested",
3499
- actions: ["trackOtpRequested"]
3500
- },
3501
- onError: {
3502
- target: "error",
3503
- actions: [
3504
- assign({ error: ({ event }) => errorFromEvent(event) }),
3505
- "trackOtpFailed"
3506
- ]
3507
- }
3508
- },
3509
- after: {
3510
- [FLOW_INVOKE_TIMEOUT_MS]: {
3511
- target: "error",
3512
- actions: [
3513
- assign({
3514
- error: () => timeoutError("sending_otp")
3515
- }),
3516
- "trackTimeoutFailed"
3517
- ]
3518
- }
3519
- }
3520
- },
3521
- otp_requested: {
3522
- on: {
3523
- VERIFY: { target: "verifying" },
3524
- RESET: {
3525
- target: "idle",
3526
- actions: assign({ email: () => null, error: () => null })
3527
- }
3528
- }
3529
- },
3530
- verifying: {
3531
- invoke: {
3532
- src: "verifyOtp",
3533
- input: ({ context, event }) => ({
3534
- email: requireEmail(context),
3535
- code: requireCodeFromEvent(event)
3536
- }),
3537
- onDone: {
3538
- target: "authenticated",
3539
- actions: [
3540
- // Scrub the duplicate `context.email` (input value
3541
- // captured during sendOtp) since the verified
3542
- // `session.email` is now the canonical source
3543
- // post-authentication. The session's email is
3544
- // intentionally retained — it's the auth result, not
3545
- // lingering input. See PR #406 S2.
3546
- assign({
3547
- session: ({ event }) => event.output,
3548
- email: () => null
3549
- }),
3550
- "trackVerified",
3551
- "identifyAndTrack"
3552
- ]
3553
- },
3554
- onError: {
3555
- target: "error",
3556
- actions: [
3557
- assign({ error: ({ event }) => errorFromEvent(event) }),
3558
- "trackOtpFailed"
3559
- ]
3560
- }
3561
- },
3562
- after: {
3563
- [FLOW_INVOKE_TIMEOUT_MS]: {
3564
- target: "error",
3565
- actions: [
3566
- assign({
3567
- error: () => timeoutError("verifying")
3568
- }),
3569
- "trackTimeoutFailed"
3570
- ]
3571
- }
3572
- }
3573
- },
3574
- authenticated: {
3575
- on: {
3576
- SIGN_OUT: { target: "signing_out" }
3577
- }
3578
- },
3579
- signing_out: {
3580
- invoke: {
3581
- src: "signOut",
3582
- onDone: {
3583
- target: "idle",
3584
- actions: [
3585
- assign({
3586
- session: () => null,
3587
- email: () => null,
3588
- error: () => null
3589
- }),
3590
- "trackSignedOut"
3591
- ]
3592
- },
3593
- onError: {
3594
- target: "error",
3595
- actions: assign({ error: ({ event }) => errorFromEvent(event) })
3596
- }
3597
- }
3598
- },
3599
- error: {
3600
- on: {
3601
- RESET: {
3602
- target: "idle",
3603
- actions: assign({ error: () => null })
3604
- }
3605
- }
3606
- }
3607
- }
3608
- });
3609
- }
3610
- function requireEmail(context) {
3611
- if (!context.email) {
3612
- throw Errors.invalidInput(
3613
- "email",
3614
- "Auth flow advanced without an email captured in context."
3615
- );
3616
- }
3617
- return context.email;
3618
- }
3619
- function requireCodeFromEvent(event) {
3620
- if (event.type !== "VERIFY") {
3621
- throw Errors.invalidInput(
3622
- "code",
3623
- `Auth flow's verifying state requires a VERIFY event, got ${event.type}.`
3624
- );
3625
- }
3626
- return event.code;
3627
- }
3628
- function errorFromEvent(event) {
3629
- const cause = typeof event === "object" && event !== null && "error" in event ? event.error : event;
3630
- if (cause instanceof CapxulError) {
3631
- if (!EMAIL_MATCH_PATTERN.test(cause.message)) return cause;
3632
- return new CapxulError({
3633
- code: cause.code,
3634
- message: redactEmail(cause.message),
3635
- cause,
3636
- details: cause.details,
3637
- operationId: cause.operationId,
3638
- correlationId: cause.correlationId,
3639
- retryable: cause.retryable
3640
- });
3641
- }
3642
- if (cause instanceof CapxulError2) {
3643
- if (!EMAIL_MATCH_PATTERN.test(cause.message)) return cause;
3644
- return new CapxulError2(cause.code, redactEmail(cause.message), {
3645
- cause,
3646
- details: cause.details,
3647
- correlationId: cause.correlationId,
3648
- layer: cause.layer
3649
- });
3650
- }
3651
- return Errors.providerError("auth", "flow", redactCauseEmail(cause));
3652
- }
3653
- var EMAIL_MATCH_PATTERN = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/;
3654
- var EMAIL_REDACT_PATTERN = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
3655
- function redactEmail(message) {
3656
- return message.replace(EMAIL_REDACT_PATTERN, "<redacted>");
3657
- }
3658
- function redactCauseEmail(cause) {
3659
- if (cause instanceof Error) {
3660
- if (!EMAIL_MATCH_PATTERN.test(cause.message)) return cause;
3661
- const redacted = new Error(redactEmail(cause.message));
3662
- redacted.cause = cause;
3663
- return redacted;
3664
- }
3665
- if (typeof cause === "string") {
3666
- return redactEmail(cause);
3667
- }
3668
- return cause;
3669
- }
3670
- function timeoutError(state) {
3671
- return Errors.providerError(
3672
- "auth",
3673
- "flow",
3674
- new Error(`timeout: ${state} exceeded ${FLOW_INVOKE_TIMEOUT_MS}ms`)
3675
- );
3676
- }
3677
- function emailDomain(email) {
3678
- const domain = email.split("@")[1]?.trim().toLowerCase();
3679
- return domain || "unknown";
3680
- }
3681
- var initialContext = {
3682
- email: null,
3683
- code: null,
3684
- username: null,
3685
- bootstrapToken: null,
3686
- bootstrapReason: null,
3687
- session: null,
3688
- account: null,
3689
- safe: null,
3690
- error: null
3691
- };
3692
- function createAuthBootstrapFlowMachine(client) {
3693
- return setup({
3694
- types: {},
3695
- actors: {
3696
- sendOtp: fromPromise(async ({ input, signal }) => {
3697
- const [error] = await client.auth.sendOtp(
3698
- { email: input.email },
3699
- { signal }
3700
- );
3701
- if (error) throw error;
3702
- }),
3703
- verifyOtp: fromPromise(
3704
- async ({ input, signal }) => {
3705
- const [error, result] = await client.auth.verifyOtp(
3706
- { email: input.email, otp: input.code },
3707
- { signal }
3708
- );
3709
- if (error) throw error;
3710
- return result;
3711
- }
3712
- ),
3713
- completeBootstrap: fromPromise(async ({ input }) => {
3714
- const [error, result] = await client.auth.completeBootstrap(input);
3715
- if (error) throw error;
3716
- return result;
3717
- }),
3718
- signOut: fromPromise(async () => {
3719
- const [error] = await client.auth.signOut();
3720
- if (error) throw error;
3721
- })
3722
- },
3723
- actions: {
3724
- trackOtpRequested: ({ context }) => {
3725
- if (!context.email) return;
3726
- track("auth_otp_requested", {
3727
- email_domain: emailDomain2(context.email)
3728
- });
3729
- },
3730
- trackFailed: ({ event }) => {
3731
- track("auth_failed", {
3732
- auth_type: "email_otp",
3733
- reason: errorFromEvent2(event).code
3734
- });
3735
- },
3736
- trackTimeoutFailed: () => {
3737
- track("auth_failed", {
3738
- auth_type: "email_otp",
3739
- reason: "timeout"
3740
- });
3741
- },
3742
- trackVerified: () => {
3743
- track("auth_verified", { auth_type: "email_otp" });
3744
- },
3745
- trackBootstrapRequired: ({ context }) => {
3746
- track("auth_verified", {
3747
- auth_type: "email_otp",
3748
- auth_mode: context.bootstrapReason ?? "bootstrap_required"
3749
- });
3750
- },
3751
- identifyAndTrack: ({ context }) => {
3752
- if (!context.session) return;
3753
- identify(context.session.authUserId, {
3754
- email_domain: emailDomain2(context.session.email)
3755
- });
3756
- track("auth_identified", {
3757
- email_domain: emailDomain2(context.session.email)
3758
- });
3759
- },
3760
- trackSignedOut: () => {
3761
- track("auth_signed_out");
3762
- }
3763
- }
3764
- }).createMachine({
3765
- id: "authBootstrap",
3766
- initial: "email",
3767
- context: initialContext,
3768
- states: {
3769
- email: {
3770
- on: {
3771
- ENTER_EMAIL: {
3772
- actions: assign({
3773
- email: ({ event }) => event.email,
3774
- error: () => null
3775
- })
3776
- },
3777
- REQUEST_OTP: { target: "sending_otp" }
3778
- }
3779
- },
3780
- sending_otp: {
3781
- invoke: {
3782
- src: "sendOtp",
3783
- input: ({ context }) => ({ email: requireEmail2(context) }),
3784
- onDone: { target: "otp_requested", actions: "trackOtpRequested" },
3785
- onError: {
3786
- target: "otp_requested",
3787
- actions: [
3788
- assign({ error: ({ event }) => errorFromEvent2(event) }),
3789
- "trackFailed"
3790
- ]
3791
- }
3792
- },
3793
- after: {
3794
- [FLOW_INVOKE_TIMEOUT_MS]: {
3795
- target: "otp_requested",
3796
- actions: [
3797
- assign({ error: () => timeoutError2("sending_otp") }),
3798
- "trackTimeoutFailed"
3799
- ]
3800
- }
3801
- }
3802
- },
3803
- otp_requested: {
3804
- on: {
3805
- ENTER_OTP: {
3806
- actions: assign({
3807
- code: ({ event }) => event.code,
3808
- error: () => null
3809
- })
3810
- },
3811
- VERIFY_OTP: { target: "verifying_otp" },
3812
- BACK: { target: "email" },
3813
- RESET: { target: "email", actions: assign(() => initialContext) }
3814
- }
3815
- },
3816
- verifying_otp: {
3817
- invoke: {
3818
- src: "verifyOtp",
3819
- input: ({ context }) => ({
3820
- email: requireEmail2(context),
3821
- code: requireCode(context)
3822
- }),
3823
- onDone: [
3824
- {
3825
- guard: ({ event }) => event.output.kind === "existing_member",
3826
- target: "authenticated",
3827
- actions: [
3828
- assign({
3829
- session: ({ event }) => event.output.session,
3830
- account: ({ event }) => event.output.kind === "existing_member" ? event.output.account : null,
3831
- username: ({ event }) => event.output.kind === "existing_member" ? event.output.username : null,
3832
- safe: ({ event }) => event.output.kind === "existing_member" ? event.output.safe : null,
3833
- email: () => null,
3834
- error: () => null
3835
- }),
3836
- "trackVerified",
3837
- "identifyAndTrack"
3838
- ]
3839
- },
3840
- {
3841
- target: "bootstrap_required",
3842
- actions: [
3843
- assign({
3844
- session: ({ event }) => event.output.session,
3845
- bootstrapToken: ({ event }) => event.output.kind === "bootstrap_required" ? event.output.bootstrapToken : null,
3846
- bootstrapReason: ({ event }) => event.output.kind === "bootstrap_required" ? event.output.reason : null,
3847
- username: ({ event }) => event.output.kind === "bootstrap_required" ? event.output.username ?? null : null,
3848
- email: ({ event }) => event.output.kind === "bootstrap_required" ? event.output.email : null,
3849
- error: () => null
3850
- }),
3851
- "trackVerified",
3852
- "trackBootstrapRequired"
3853
- ]
3854
- }
3855
- ],
3856
- onError: {
3857
- target: "otp_requested",
3858
- actions: [
3859
- assign({ error: ({ event }) => errorFromEvent2(event) }),
3860
- "trackFailed"
3861
- ]
3862
- }
3863
- },
3864
- after: {
3865
- [FLOW_INVOKE_TIMEOUT_MS]: {
3866
- target: "otp_requested",
3867
- actions: [
3868
- assign({ error: () => timeoutError2("verifying_otp") }),
3869
- "trackTimeoutFailed"
3870
- ]
3871
- }
3872
- }
3873
- },
3874
- bootstrap_required: {
3875
- on: {
3876
- ENTER_USERNAME: {
3877
- actions: assign({
3878
- username: ({ event }) => event.username,
3879
- error: () => null
3880
- })
3881
- },
3882
- COMPLETE_BOOTSTRAP: { target: "completing_bootstrap" },
3883
- BACK: { target: "otp_requested" },
3884
- RESET: { target: "email", actions: assign(() => initialContext) }
3885
- }
3886
- },
3887
- completing_bootstrap: {
3888
- invoke: {
3889
- src: "completeBootstrap",
3890
- input: ({ context }) => ({
3891
- bootstrapToken: requireBootstrapToken(context),
3892
- username: requireUsername(context)
3893
- }),
3894
- onDone: {
3895
- target: "authenticated",
3896
- actions: [
3897
- assign({
3898
- session: ({ event }) => event.output.session,
3899
- account: ({ event }) => event.output.account,
3900
- username: ({ event }) => event.output.username,
3901
- safe: ({ event }) => event.output.safe,
3902
- bootstrapToken: () => null,
3903
- bootstrapReason: () => null,
3904
- email: () => null,
3905
- error: () => null
3906
- }),
3907
- "identifyAndTrack"
3908
- ]
3909
- },
3910
- onError: {
3911
- target: "bootstrap_required",
3912
- actions: [
3913
- assign({ error: ({ event }) => errorFromEvent2(event) }),
3914
- "trackFailed"
3915
- ]
3916
- }
3917
- },
3918
- after: {
3919
- [FLOW_INVOKE_TIMEOUT_MS]: {
3920
- target: "bootstrap_required",
3921
- actions: [
3922
- assign({ error: () => timeoutError2("completing_bootstrap") }),
3923
- "trackTimeoutFailed"
3924
- ]
3925
- }
3926
- }
3927
- },
3928
- authenticated: {
3929
- on: {
3930
- SIGN_OUT: { target: "signing_out" }
3931
- }
3932
- },
3933
- signing_out: {
3934
- invoke: {
3935
- src: "signOut",
3936
- onDone: {
3937
- target: "email",
3938
- actions: [
3939
- assign(() => initialContext),
3940
- "trackSignedOut"
3941
- ]
3942
- },
3943
- onError: {
3944
- target: "error",
3945
- actions: assign({ error: ({ event }) => errorFromEvent2(event) })
3946
- }
3947
- }
3948
- },
3949
- error: {
3950
- on: {
3951
- RESET: { target: "email", actions: assign(() => initialContext) }
3952
- }
3953
- }
3954
- }
3955
- });
3956
- }
3957
- function requireEmail2(context) {
3958
- if (!context.email) {
3959
- throw Errors.invalidInput("email", "Auth bootstrap requires an email.");
3960
- }
3961
- return context.email;
3962
- }
3963
- function requireCode(context) {
3964
- if (!context.code) {
3965
- throw Errors.invalidInput("code", "Auth bootstrap requires an OTP code.");
3966
- }
3967
- return context.code;
3968
- }
3969
- function requireBootstrapToken(context) {
3970
- if (!context.bootstrapToken) {
3971
- throw Errors.invalidInput(
3972
- "bootstrapToken",
3973
- "Auth bootstrap requires a continuation token."
3974
- );
3975
- }
3976
- return context.bootstrapToken;
3977
- }
3978
- function requireUsername(context) {
3979
- if (!context.username) {
3980
- throw Errors.invalidInput("username", "Auth bootstrap requires a username.");
3981
- }
3982
- return context.username;
3983
- }
3984
- function errorFromEvent2(event) {
3985
- const cause = typeof event === "object" && event !== null && "error" in event ? event.error : event;
3986
- if (cause instanceof CapxulError || cause instanceof CapxulError2) {
3987
- return cause;
3988
- }
3989
- return Errors.providerError("auth", "bootstrap", cause);
3990
- }
3991
- function timeoutError2(state) {
3992
- return Errors.providerError(
3993
- "auth",
3994
- "bootstrap",
3995
- new Error(`timeout: ${state} exceeded ${FLOW_INVOKE_TIMEOUT_MS}ms`)
3996
- );
3997
- }
3998
- function emailDomain2(email) {
3999
- const domain = email.split("@")[1]?.trim().toLowerCase();
4000
- return domain || "unknown";
4001
- }
4002
- function createProvisioningMachine(client) {
4003
- return setup({
4004
- types: {},
4005
- actors: {
4006
- provisionPersonal: fromPromise(async ({ input }) => {
4007
- const [error, account] = await client.accounts.provisionPersonal(
4008
- input.input
4009
- );
4010
- if (error) throw error;
4011
- return account;
4012
- })
4013
- },
4014
- guards: {
4015
- hasInput: ({ context }) => context.input !== null
4016
- },
4017
- actions: {
4018
- trackWalletCreated: ({ context }) => {
4019
- const provider = context.input?.signerProvider;
4020
- if (!provider) return;
4021
- track("provisioning_wallet_created", {
4022
- eoa_address: provider.signerAddress
4023
- });
4024
- },
4025
- trackSafeCreated: ({ context }) => {
4026
- const provider = context.input?.signerProvider;
4027
- if (!provider) return;
4028
- track("provisioning_safe_created", {
4029
- safe_address: deriveSafeAddress(provider.signerAddress)
4030
- });
4031
- }
4032
- }
4033
- }).createMachine({
4034
- id: "provisioning",
4035
- initial: "starting",
4036
- context: ({ input }) => ({
4037
- input: input?.input ?? null,
4038
- account: null,
4039
- error: null
4040
- }),
4041
- states: {
4042
- // Transient routing state: skip `idle` when input was provided
4043
- // at creation time (the invoked-by-parent path).
4044
- starting: {
4045
- always: [
4046
- { guard: "hasInput", target: "running" },
4047
- { target: "idle" }
4048
- ]
4049
- },
4050
- idle: {
4051
- on: {
4052
- START: {
4053
- target: "running",
4054
- actions: assign({
4055
- input: ({ event }) => event.input,
4056
- account: () => null,
4057
- error: () => null
4058
- })
4059
- }
4060
- }
4061
- },
4062
- running: {
4063
- invoke: {
4064
- src: "provisionPersonal",
4065
- input: ({ context }) => ({
4066
- input: requireProvisionInput(context)
4067
- }),
4068
- onDone: {
4069
- target: "done",
4070
- actions: assign({ account: ({ event }) => event.output })
4071
- },
4072
- onError: {
4073
- target: "error",
4074
- actions: assign({ error: ({ event }) => errorFromEvent3(event) })
4075
- }
4076
- },
4077
- after: {
4078
- [FLOW_INVOKE_TIMEOUT_MS]: {
4079
- target: "error",
4080
- actions: assign({ error: () => timeoutError3() })
4081
- }
4082
- }
4083
- },
4084
- done: {
4085
- type: "final",
4086
- entry: ["trackWalletCreated", "trackSafeCreated"]
4087
- },
4088
- error: {
4089
- type: "final"
4090
- }
4091
- },
4092
- /**
4093
- * Root-level output mapper — fires when the machine reaches any
4094
- * top-level `final` state (`done` or `error`). The parent receives
4095
- * this payload on its `onDone` transition and branches via guards
4096
- * on `event.output.error`.
4097
- */
4098
- output: ({ context }) => context.error ? { error: context.error } : context.account ? { account: context.account } : { error: timeoutError3() }
4099
- });
4100
- }
4101
- function requireProvisionInput(context) {
4102
- if (!context.input) {
4103
- throw Errors.invalidInput(
4104
- "input",
4105
- "Provisioning flow advanced to running without input captured in context."
4106
- );
4107
- }
4108
- return context.input;
4109
- }
4110
- function errorFromEvent3(event) {
4111
- const cause = typeof event === "object" && event !== null && "error" in event ? event.error : event;
4112
- if (cause instanceof CapxulError) return cause;
4113
- if (cause instanceof CapxulError2) return cause;
4114
- return Errors.providerError("provisioning", "flow", cause);
4115
- }
4116
- function timeoutError3() {
4117
- return Errors.providerError(
4118
- "provisioning",
4119
- "flow",
4120
- new Error(`timeout: running exceeded ${FLOW_INVOKE_TIMEOUT_MS}ms`)
4121
- );
4122
- }
4123
-
4124
- // src/flows/onboarding.ts
4125
- function createOnboardingFlowMachine(client) {
4126
- const provisioningMachine = createProvisioningMachine(client);
4127
- return setup({
4128
- types: {},
4129
- actors: {
4130
- provisioningMachine
4131
- },
4132
- guards: {
4133
- isOrg: ({ event }) => event.type === "START_PROVISIONING" && event.input.kind !== "account",
4134
- missingSigner: ({ event }) => event.type === "START_PROVISIONING" && event.input.kind === "account" && !event.input.signerProvider,
4135
- childReportedError: ({ event }) => {
4136
- if (typeof event !== "object" || event === null || !("output" in event)) {
4137
- return false;
4138
- }
4139
- const output = event.output;
4140
- return typeof output === "object" && output !== null && "error" in output && output.error != null;
4141
- }
4142
- },
4143
- actions: {
4144
- // Always-on for any START_PROVISIONING transition.
4145
- assignOperationIdAndInput: assign({
4146
- operationId: () => generateOperationId(),
4147
- input: ({ event }) => event.type === "START_PROVISIONING" ? event.input : null,
4148
- error: () => null,
4149
- account: () => null
4150
- }),
4151
- // Pre-actor rejection branches stamp the synchronous error.
4152
- assignOrgNotImplemented: assign({
4153
- error: () => new CapxulError({
4154
- code: "NOT_IMPLEMENTED",
4155
- message: "useOnboardingFlow organization onboarding is not implemented in this local-private-key slice."
4156
- })
4157
- }),
4158
- assignMissingSigner: assign({
4159
- error: () => new CapxulError({
4160
- code: "INVALID_INPUT",
4161
- message: "useOnboardingFlow requires a signerProvider for account onboarding."
4162
- })
4163
- }),
4164
- // Telemetry actions — order matters; the source fires the
4165
- // "submitted" track BEFORE the rejection track on validation
4166
- // errors, and the happy path follows the documented sequence.
4167
- trackOrgSubmitted: ({ event }) => {
4168
- if (event.type !== "START_PROVISIONING") return;
4169
- track("onboarding_org_submitted", {
4170
- country: event.input.country ?? "unknown"
4171
- });
4172
- },
4173
- trackPersonalSubmitted: ({ event }) => {
4174
- if (event.type !== "START_PROVISIONING") return;
4175
- track("onboarding_personal_submitted", {
4176
- country: event.input.country ?? "unknown",
4177
- wallet_count: event.input.signerProvider ? 1 : 0
4178
- });
4179
- },
4180
- trackOrgNotImplementedError: () => {
4181
- track("onboarding_wallet_error", {
4182
- step: "profile",
4183
- reason: "organization_not_implemented"
4184
- });
4185
- },
4186
- trackMissingSignerError: () => {
4187
- track("onboarding_wallet_error", {
4188
- step: "profile",
4189
- reason: "missing_signer_provider"
4190
- });
4191
- },
4192
- trackWalletCreating: () => {
4193
- track("onboarding_wallet_creating");
4194
- },
4195
- trackOnboardingCompleted: () => {
4196
- track("onboarding_completed", { account_type: "personal" });
4197
- },
4198
- trackProvisioningFailed: ({ context }) => {
4199
- const code = context.error?.code ?? "UNKNOWN";
4200
- track("onboarding_wallet_error", {
4201
- step: "provision_personal",
4202
- reason: code
4203
- });
4204
- },
4205
- assignChildReportedError: assign({
4206
- error: ({ event }) => extractChildErrorOrFallback(event)
4207
- }),
4208
- assignChildThrown: assign({
4209
- error: ({ event }) => errorFromEvent4(event)
4210
- }),
4211
- assignAccountFromChild: assign({
4212
- account: ({ event }) => extractChildAccountOrNull(event)
4213
- }),
4214
- resetContext: assign({
4215
- input: () => null,
4216
- operationId: () => null,
4217
- account: () => null,
4218
- error: () => null
4219
- })
4220
- }
4221
- }).createMachine({
4222
- id: "onboarding",
4223
- initial: "profile",
4224
- context: {
4225
- input: null,
4226
- operationId: null,
4227
- account: null,
4228
- error: null
4229
- },
4230
- states: {
4231
- profile: {
4232
- on: {
4233
- START_PROVISIONING: [
4234
- {
4235
- guard: "isOrg",
4236
- target: "error",
4237
- actions: [
4238
- "assignOperationIdAndInput",
4239
- "trackOrgSubmitted",
4240
- "assignOrgNotImplemented",
4241
- "trackOrgNotImplementedError"
4242
- ]
4243
- },
4244
- {
4245
- guard: "missingSigner",
4246
- target: "error",
4247
- actions: [
4248
- "assignOperationIdAndInput",
4249
- "trackPersonalSubmitted",
4250
- "assignMissingSigner",
4251
- "trackMissingSignerError"
4252
- ]
4253
- },
4254
- {
4255
- target: "provisioning",
4256
- actions: [
4257
- "assignOperationIdAndInput",
4258
- "trackPersonalSubmitted"
4259
- ]
4260
- }
4261
- ]
4262
- }
4263
- },
4264
- provisioning: {
4265
- entry: ["trackWalletCreating"],
4266
- invoke: {
4267
- src: "provisioningMachine",
4268
- input: ({ context }) => ({
4269
- input: requireProvisionInput2(context)
4270
- }),
4271
- // The child machine reaches a top-level `final` state for
4272
- // both success and failure, so the parent's `onDone` fires
4273
- // in both cases. We branch via a guard on
4274
- // `event.output.error`. The child machine has its own
4275
- // `FLOW_INVOKE_TIMEOUT_MS` timer that ends in a final
4276
- // `error` state on timeout — that signal flows back through
4277
- // `onDone` + the `childReportedError` guard. The previous
4278
- // duplicate parent `after: FLOW_INVOKE_TIMEOUT_MS` was
4279
- // removed in PR #406 (X1+G3) so the child's `output.error`
4280
- // is the single source of provisioning failure.
4281
- onDone: [
4282
- {
4283
- guard: "childReportedError",
4284
- target: "error",
4285
- actions: [
4286
- "assignChildReportedError",
4287
- "trackProvisioningFailed"
4288
- ]
4289
- },
4290
- {
4291
- target: "complete",
4292
- actions: [
4293
- "assignAccountFromChild",
4294
- "trackOnboardingCompleted"
4295
- ]
4296
- }
4297
- ],
4298
- // `onError` is the safety net for an unexpected throw from
4299
- // inside the child machine itself (not the spawned actor's
4300
- // `error` final state, which goes through `onDone`). In
4301
- // normal flow this never fires.
4302
- onError: {
4303
- target: "error",
4304
- actions: ["assignChildThrown", "trackProvisioningFailed"]
4305
- }
4306
- }
4307
- },
4308
- // TODO(stack-1): wire `action_required` once the KYC gate /
4309
- // async-resume `NextAction` path is lifted from
4310
- // `useOperation(operationId)`. PROCEED → provisioning re-enters
4311
- // the actor with the resumed input. Currently unreachable from
4312
- // any transition; declared for parity with the public type.
4313
- action_required: {
4314
- on: {
4315
- PROCEED: { target: "provisioning" },
4316
- RESET: { target: "profile", actions: "resetContext" }
4317
- }
4318
- },
4319
- complete: {
4320
- on: {
4321
- RESET: { target: "profile", actions: "resetContext" }
4322
- }
4323
- },
4324
- error: {
4325
- on: {
4326
- RESET: { target: "profile", actions: "resetContext" }
4327
- }
4328
- }
4329
- }
4330
- });
4331
- }
4332
- function generateOperationId() {
4333
- return toOperationId(`op_onboarding_local_${Date.now().toString(36)}`);
4334
- }
4335
- function requireProvisionInput2(context) {
4336
- if (!context.input || !context.input.signerProvider) {
4337
- throw Errors.invalidInput(
4338
- "signerProvider",
4339
- "Onboarding flow advanced to provisioning without a signerProvider in context."
4340
- );
4341
- }
4342
- return {
4343
- displayName: context.input.displayName,
4344
- username: context.input.username,
4345
- countryCode: context.input.country,
4346
- signerProvider: context.input.signerProvider
4347
- };
4348
- }
4349
- function extractChildOutput(event) {
4350
- if (typeof event !== "object" || event === null || !("output" in event)) {
4351
- return null;
4352
- }
4353
- const output = event.output;
4354
- if (typeof output !== "object" || output === null) return null;
4355
- return output;
4356
- }
4357
- function extractChildErrorOrFallback(event) {
4358
- const output = extractChildOutput(event);
4359
- if (output && "error" in output && output.error) return output.error;
4360
- return Errors.providerError(
4361
- "onboarding",
4362
- "flow",
4363
- new Error("provisioning child reported error without payload")
4364
- );
4365
- }
4366
- function extractChildAccountOrNull(event) {
4367
- const output = extractChildOutput(event);
4368
- if (output && "account" in output && output.account) return output.account;
4369
- return null;
4370
- }
4371
- function errorFromEvent4(event) {
4372
- const cause = typeof event === "object" && event !== null && "error" in event ? event.error : event;
4373
- if (cause instanceof CapxulError) return cause;
4374
- if (cause instanceof CapxulError2) return cause;
4375
- return Errors.providerError("onboarding", "flow", cause);
4376
- }
4377
-
4378
- // src/client.ts
4379
- function createCapxulClient(config = {}) {
4380
- const clientWithoutFlows = {
4381
- id: crypto.randomUUID(),
4382
- auth: createAuthClient(config),
4383
- me: createMeClient(config),
4384
- accounts: createAccountsClient(config),
4385
- organizations: createOrganizationsClient(config),
4386
- payments: createPaymentsClient(config),
4387
- transfers: createTransfersClient(),
4388
- tokenTransfers: createTokenTransfersClient(config),
4389
- withdrawals: createWithdrawalsClient(config),
4390
- documents: createDocumentsClient(),
4391
- subAccounts: createSubAccountsClient(config),
4392
- virtualAccounts: createVirtualAccountsClient(),
4393
- virtualCards: createVirtualCardsClient(),
4394
- externalAccounts: createExternalAccountsClient(config),
4395
- operations: createOperationsClient(config),
4396
- webhookEndpoints: createWebhookEndpointsClient(),
4397
- webhookEvents: createWebhookEventsClient(),
4398
- apiKeys: createApiKeysClient()
4399
- };
4400
- const client = clientWithoutFlows;
4401
- client.flows = {
4402
- auth: () => createAuthFlowMachine(client),
4403
- authBootstrap: () => createAuthBootstrapFlowMachine(client),
4404
- onboarding: () => createOnboardingFlowMachine(client),
4405
- provisioning: () => createProvisioningMachine(client)
4406
- };
4407
- return client;
4408
- }
4409
-
4410
- // src/match.ts
4411
- function matchError(err, handlers) {
4412
- const handler = handlers[err.code];
4413
- return handler(err);
4414
- }
4415
- function matchStatus(value, handlers) {
4416
- const handler = handlers[value.status];
4417
- return handler(value);
4418
- }
4419
- function matchAction(action, handlers) {
4420
- const handler = handlers[action.kind];
4421
- return handler(action);
4422
- }
4423
- function createLocalSigner(privateKey) {
4424
- return privateKeyToAccount(privateKey);
4425
- }
4426
-
4427
- // src/webhooks.ts
4428
- async function verifyWebhook(request, secret, options) {
4429
- if (!secret) {
4430
- throw new CapxulError({
4431
- code: "INVALID_INPUT",
4432
- message: "A webhook signing secret is required."
4433
- });
4434
- }
4435
- const timestamp = request.headers.get("x-capxul-timestamp");
4436
- const signature = request.headers.get("x-capxul-signature");
4437
- if (!timestamp || !signature) {
4438
- return { valid: false, reason: "invalid_signature" };
4439
- }
4440
- const timestampMs = Number(timestamp);
4441
- if (!Number.isFinite(timestampMs)) {
4442
- return { valid: false, reason: "malformed" };
4443
- }
4444
- const freshnessWindowMs = options?.freshnessWindowMs ?? WEBHOOK_FRESHNESS_WINDOW_MS;
4445
- if (Math.abs(Date.now() - timestampMs) > freshnessWindowMs) {
4446
- return { valid: false, reason: "replay" };
4447
- }
4448
- const body = await request.text();
4449
- const signatureHex = signature.startsWith("sha256=") ? signature.slice("sha256=".length) : signature;
4450
- if (!/^[a-f0-9]{64}$/i.test(signatureHex)) {
4451
- return { valid: false, reason: "invalid_signature" };
4452
- }
4453
- const validSignature = await verifyHmacSha256(
4454
- secret,
4455
- `${timestamp}.${body}`,
4456
- signatureHex
4457
- );
4458
- if (!validSignature) {
4459
- return { valid: false, reason: "invalid_signature" };
4460
- }
4461
- const parsed = parseWebhookEvent(body);
4462
- if (!parsed) {
4463
- return { valid: false, reason: "malformed" };
4464
- }
4465
- return { valid: true, event: parsed };
4466
- }
4467
- async function verifyHmacSha256(secret, message, signatureHex) {
4468
- const encoder = new TextEncoder();
4469
- const key = await crypto.subtle.importKey(
4470
- "raw",
4471
- encoder.encode(secret),
4472
- { name: "HMAC", hash: "SHA-256" },
4473
- false,
4474
- ["verify"]
4475
- );
4476
- return await crypto.subtle.verify(
4477
- "HMAC",
4478
- key,
4479
- hexToArrayBuffer(signatureHex),
4480
- encoder.encode(message)
4481
- );
4482
- }
4483
- function hexToArrayBuffer(hex) {
4484
- const buffer = new ArrayBuffer(hex.length / 2);
4485
- const bytes = new Uint8Array(buffer);
4486
- for (let i = 0; i < bytes.length; i++) {
4487
- bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
4488
- }
4489
- return buffer;
4490
- }
4491
- function parseWebhookEvent(body) {
4492
- try {
4493
- const parsed = JSON.parse(body);
4494
- if (!isWebhookEvent(parsed)) return null;
4495
- return parsed;
4496
- } catch {
4497
- return null;
4498
- }
4499
- }
4500
- function isWebhookEvent(value) {
4501
- if (!value || typeof value !== "object" || Array.isArray(value)) {
4502
- return false;
4503
- }
4504
- const candidate = value;
4505
- return typeof candidate.id === "string" && typeof candidate.type === "string" && typeof candidate.createdAt === "string" && (candidate.operationId === void 0 || typeof candidate.operationId === "string") && (candidate.correlationId === void 0 || typeof candidate.correlationId === "string") && !!candidate.data && typeof candidate.data === "object" && !Array.isArray(candidate.data);
4506
- }
4507
-
4508
- // src/core/auth-service.ts
4509
- var AuthService = class {
4510
- authClient;
4511
- sessionStore;
4512
- config;
4513
- constructor(config = {}) {
4514
- this.config = config;
4515
- this.sessionStore = config.auth?.sessionStore ?? createMemorySessionStore2();
4516
- this.authClient = createAuthClient({
4517
- ...config,
4518
- auth: { ...config.auth, sessionStore: this.sessionStore }
4519
- });
4520
- }
4521
- async sendOtp(email) {
4522
- const [err] = await this.authClient.sendOtp({ email });
4523
- if (err) throw err;
4524
- }
4525
- async verifyOtp(email, otp) {
4526
- const [err, result] = await this.authClient.verifyOtp({ email, otp });
4527
- if (err) throw err;
4528
- return result;
4529
- }
4530
- async completeBootstrap(params, signer) {
4531
- if (signer) {
4532
- const tempClient = createAuthClient({
4533
- ...this.config,
4534
- signer
4535
- });
4536
- const [err2, result2] = await tempClient.completeBootstrap(params);
4537
- if (err2) throw err2;
4538
- return result2;
4539
- }
4540
- const [err, result] = await this.authClient.completeBootstrap(params);
4541
- if (err) throw err;
4542
- return result;
4543
- }
4544
- /**
4545
- * Clears the persisted session and, when a transport was pre-injected,
4546
- * drops the cached auth header.
4547
- *
4548
- * **Transport safety note:** `clearAuth()` is only invoked when
4549
- * `config._transport` was supplied at construction (e.g. by the React
4550
- * provider). If `AuthService` is instantiated directly in a Node/CLI
4551
- * context without an injected transport, the transport-side auth cache
4552
- * is the caller's responsibility.
4553
- */
4554
- async signOut() {
4555
- this.sessionStore.clear();
4556
- this.config._transport?.clearAuth();
4557
- }
4558
- async getSession() {
4559
- const [err, session] = await this.authClient.getSession();
4560
- if (err) throw err;
4561
- return session;
4562
- }
4563
- };
4564
- function createMemorySessionStore2() {
4565
- let current = null;
4566
- return {
4567
- get: () => current,
4568
- set: (session) => {
4569
- current = session;
4570
- },
4571
- clear: () => {
4572
- current = null;
4573
- }
4574
- };
4575
- }
4576
- var SignerProvisioner = class {
4577
- provision() {
4578
- const privateKey = generatePrivateKey();
4579
- const signer = privateKeyToAccount(privateKey);
4580
- const safeAddress = deriveSafeAddress(signer.address);
4581
- return { signer, safeAddress };
4582
- }
4583
- };
4584
-
4585
- export { AuthService, CapxulError, SignerProvisioner, createAuthBootstrapFlowMachine, createAuthFlowMachine, createCapxulClient, createLocalSigner, createOnboardingFlowMachine, createProvisioningMachine as createProvisioningFlowMachine, makeHttpTransport, matchAction, matchError, matchStatus, resolvePaymentToken, toAccountId, toApiKeyId, toBalanceLedgerEntryId, toDocumentId, toEmail, toExternalAccountId, toKybProfileId, toKycProfileId, toMemberId, toOperationId, toOrganizationId, toPaymentId, toPhoneNumber, toSafeId, toSubAccountId, toTokenTransferId, toTransferId, toTreasuryId, toUsername, toVirtualAccountId, toVirtualCardId, toWebhookEndpointId, toWebhookEventId, toWithdrawalId, tryCatch, verifyWebhook };