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