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