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