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