@caypo/canton-sdk 0.1.0

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 (44) hide show
  1. package/.turbo/turbo-build.log +26 -0
  2. package/.turbo/turbo-test.log +23 -0
  3. package/README.md +120 -0
  4. package/SPEC.md +223 -0
  5. package/dist/amount-L2SDLRZT.js +15 -0
  6. package/dist/amount-L2SDLRZT.js.map +1 -0
  7. package/dist/chunk-GSDB5FKZ.js +110 -0
  8. package/dist/chunk-GSDB5FKZ.js.map +1 -0
  9. package/dist/index.cjs +1158 -0
  10. package/dist/index.cjs.map +1 -0
  11. package/dist/index.d.cts +673 -0
  12. package/dist/index.d.ts +673 -0
  13. package/dist/index.js +986 -0
  14. package/dist/index.js.map +1 -0
  15. package/package.json +50 -0
  16. package/src/__tests__/agent.test.ts +217 -0
  17. package/src/__tests__/amount.test.ts +202 -0
  18. package/src/__tests__/client.test.ts +516 -0
  19. package/src/__tests__/e2e/canton-client.e2e.test.ts +190 -0
  20. package/src/__tests__/e2e/mpp-flow.e2e.test.ts +346 -0
  21. package/src/__tests__/e2e/setup.ts +112 -0
  22. package/src/__tests__/e2e/usdcx.e2e.test.ts +114 -0
  23. package/src/__tests__/keystore.test.ts +197 -0
  24. package/src/__tests__/pay-client.test.ts +257 -0
  25. package/src/__tests__/safeguards.test.ts +333 -0
  26. package/src/__tests__/usdcx.test.ts +374 -0
  27. package/src/accounts/checking.ts +118 -0
  28. package/src/agent.ts +132 -0
  29. package/src/canton/amount.ts +167 -0
  30. package/src/canton/client.ts +218 -0
  31. package/src/canton/errors.ts +45 -0
  32. package/src/canton/holdings.ts +90 -0
  33. package/src/canton/index.ts +51 -0
  34. package/src/canton/types.ts +214 -0
  35. package/src/canton/usdcx.ts +166 -0
  36. package/src/index.ts +97 -0
  37. package/src/mpp/pay-client.ts +170 -0
  38. package/src/safeguards/manager.ts +183 -0
  39. package/src/traffic/manager.ts +95 -0
  40. package/src/wallet/config.ts +88 -0
  41. package/src/wallet/keystore.ts +164 -0
  42. package/tsconfig.json +8 -0
  43. package/tsup.config.ts +9 -0
  44. package/vitest.config.ts +7 -0
@@ -0,0 +1,673 @@
1
+ export { MPP_CANTON_VERSION } from '@caypo/mpp-canton';
2
+
3
+ /**
4
+ * Canton JSON Ledger API v2 — Type Definitions
5
+ *
6
+ * Verified against: docs.digitalasset.com/build/3.5, Canton OpenAPI spec v3.3.0
7
+ * Default port: 7575
8
+ */
9
+ interface PartyLocalMetadata {
10
+ resourceVersion: string;
11
+ annotations: Record<string, string>;
12
+ }
13
+ interface PartyDetails {
14
+ party: string;
15
+ isLocal: boolean;
16
+ localMetadata: PartyLocalMetadata;
17
+ identityProviderId: string;
18
+ }
19
+ interface CreateCommand {
20
+ CreateCommand: {
21
+ templateId: string;
22
+ createArguments: Record<string, unknown>;
23
+ };
24
+ }
25
+ interface ExerciseCommand {
26
+ ExerciseCommand: {
27
+ templateId: string;
28
+ contractId: string;
29
+ choice: string;
30
+ choiceArgument: Record<string, unknown>;
31
+ };
32
+ }
33
+ type Command = CreateCommand | ExerciseCommand;
34
+ interface SubmitAndWaitRequest {
35
+ commands: Command[];
36
+ userId: string;
37
+ commandId: string;
38
+ actAs: string[];
39
+ readAs?: string[];
40
+ }
41
+ interface SubmitAndWaitResponse {
42
+ updateId: string;
43
+ completionOffset: number;
44
+ }
45
+ interface CreatedEvent {
46
+ contractId: string;
47
+ templateId: string;
48
+ createArgument: Record<string, unknown>;
49
+ witnessParties: string[];
50
+ signatories: string[];
51
+ observers: string[];
52
+ }
53
+ interface ArchivedEvent {
54
+ contractId: string;
55
+ templateId: string;
56
+ witnessParties: string[];
57
+ }
58
+ interface ExercisedEvent {
59
+ contractId: string;
60
+ templateId: string;
61
+ choice: string;
62
+ choiceArgument: Record<string, unknown>;
63
+ exerciseResult: unknown;
64
+ actingParties: string[];
65
+ childEvents: TransactionTreeEvent[];
66
+ }
67
+ type TransactionTreeEvent = {
68
+ createdEvent: CreatedEvent;
69
+ } | {
70
+ exercisedEvent: ExercisedEvent;
71
+ };
72
+ interface TransactionTree {
73
+ updateId: string;
74
+ commandId: string;
75
+ effectiveAt: string;
76
+ offset: number;
77
+ eventsById: Record<string, TransactionTreeEvent>;
78
+ rootEventIds: string[];
79
+ }
80
+ interface FlatTransaction {
81
+ updateId: string;
82
+ commandId: string;
83
+ effectiveAt: string;
84
+ offset: number;
85
+ events: Array<{
86
+ createdEvent?: CreatedEvent;
87
+ archivedEvent?: ArchivedEvent;
88
+ }>;
89
+ }
90
+ interface TransactionResponse {
91
+ transaction: FlatTransaction;
92
+ }
93
+ interface IdentifierFilter {
94
+ identifierFilter: {
95
+ TemplateFilter: {
96
+ value: {
97
+ templateId: string;
98
+ };
99
+ };
100
+ } | {
101
+ WildcardFilter: {
102
+ value: {
103
+ includeCreatedEventBlob?: boolean;
104
+ };
105
+ };
106
+ };
107
+ }
108
+ interface PartyFilter {
109
+ cumulative: IdentifierFilter[];
110
+ }
111
+ interface AnyPartyFilter {
112
+ cumulative: IdentifierFilter[];
113
+ }
114
+ interface EventFormat {
115
+ filtersByParty?: Record<string, PartyFilter>;
116
+ filtersForAnyParty?: AnyPartyFilter;
117
+ verbose?: boolean;
118
+ }
119
+ interface ActiveContractsRequest {
120
+ eventFormat: EventFormat;
121
+ activeAtOffset: number;
122
+ }
123
+ interface ActiveContract {
124
+ contractId: string;
125
+ templateId: string;
126
+ createArgument: Record<string, unknown>;
127
+ createdAt: string;
128
+ signatories: string[];
129
+ observers: string[];
130
+ }
131
+ interface LedgerEndResponse {
132
+ offset: number;
133
+ }
134
+ type CantonErrorCode = "INVALID_ARGUMENT" | "NOT_FOUND" | "PERMISSION_DENIED" | "ALREADY_EXISTS" | "FAILED_PRECONDITION" | "UNAVAILABLE" | string;
135
+ interface LedgerError {
136
+ cause: string;
137
+ code: CantonErrorCode;
138
+ context: Record<string, string>;
139
+ errorCategory: number;
140
+ grpcCodeValue: number;
141
+ }
142
+ interface CantonClientConfig {
143
+ ledgerUrl: string;
144
+ token: string;
145
+ userId: string;
146
+ timeout?: number;
147
+ }
148
+ interface SubmitParams {
149
+ commands: Command[];
150
+ commandId: string;
151
+ actAs: string[];
152
+ readAs?: string[];
153
+ }
154
+ interface QueryActiveContractsParams {
155
+ filtersByParty?: Record<string, PartyFilter>;
156
+ filtersForAnyParty?: AnyPartyFilter;
157
+ activeAtOffset: number;
158
+ }
159
+
160
+ /**
161
+ * Canton JSON Ledger API v2 — Client
162
+ *
163
+ * All requests target config.ledgerUrl + path.
164
+ * All requests include Authorization: Bearer <token>.
165
+ * Errors are parsed into typed CantonApiError / CantonAuthError / CantonTimeoutError.
166
+ */
167
+
168
+ declare class CantonClient {
169
+ private readonly ledgerUrl;
170
+ private readonly token;
171
+ private readonly userId;
172
+ private readonly timeout;
173
+ constructor(config: CantonClientConfig);
174
+ submitAndWait(params: SubmitParams): Promise<SubmitAndWaitResponse>;
175
+ submitAndWaitForTransaction(params: SubmitParams): Promise<TransactionResponse>;
176
+ queryActiveContracts(params: QueryActiveContractsParams): Promise<ActiveContract[]>;
177
+ getTransactionById(updateId: string): Promise<TransactionTree | null>;
178
+ getLedgerEnd(): Promise<number>;
179
+ allocateParty(hint: string): Promise<PartyDetails>;
180
+ listParties(): Promise<PartyDetails[]>;
181
+ isHealthy(): Promise<boolean>;
182
+ private request;
183
+ }
184
+
185
+ /**
186
+ * Canton SDK — Custom Error Classes
187
+ */
188
+
189
+ declare class CantonApiError extends Error {
190
+ readonly code: CantonErrorCode;
191
+ readonly ledgerCause: string;
192
+ readonly grpcCodeValue: number;
193
+ readonly errorCategory: number;
194
+ readonly context: Record<string, string>;
195
+ constructor(ledgerError: LedgerError);
196
+ }
197
+ declare class CantonTimeoutError extends Error {
198
+ readonly timeoutMs: number;
199
+ readonly path: string;
200
+ constructor(path: string, timeoutMs: number);
201
+ }
202
+ declare class CantonAuthError extends Error {
203
+ readonly statusCode: number;
204
+ constructor(statusCode: number, message?: string);
205
+ }
206
+
207
+ /**
208
+ * Holding selection algorithm for USDCx transfers.
209
+ *
210
+ * Canton uses a UTXO-like model: a party can have multiple Holding contracts.
211
+ * When transferring, we need to select holdings that cover the required amount.
212
+ */
213
+ interface USDCxHolding {
214
+ contractId: string;
215
+ owner: string;
216
+ amount: string;
217
+ templateId: string;
218
+ }
219
+ interface HoldingSelection {
220
+ type: "single" | "merge-then-transfer";
221
+ contractIds: string[];
222
+ }
223
+ declare class InsufficientBalanceError extends Error {
224
+ readonly available: string;
225
+ readonly required: string;
226
+ constructor(available: string, required: string);
227
+ }
228
+ /**
229
+ * Select holdings that cover the required amount.
230
+ *
231
+ * Strategy:
232
+ * 1. Sort holdings by amount descending.
233
+ * 2. Look for a single holding >= required (prefer smallest sufficient one).
234
+ * 3. If none, accumulate multiple holdings until we cover the amount.
235
+ * 4. Throw InsufficientBalanceError if total < required.
236
+ */
237
+ declare function selectHoldings(holdings: USDCxHolding[], requiredAmount: string): HoldingSelection;
238
+
239
+ /**
240
+ * USDCx Operations — Query holdings, transfer, merge.
241
+ *
242
+ * Uses CIP-56 token standard:
243
+ * - Splice.Api.Token.HoldingV1:Holding for balance queries
244
+ * - TransferFactory_Transfer for 1-step transfers (requires TransferPreapproval)
245
+ */
246
+
247
+ /** CIP-56 Holding template ID — used for active contract queries */
248
+ declare const USDCX_HOLDING_TEMPLATE_ID = "Splice.Api.Token.HoldingV1:Holding";
249
+ /** TransferFactory template ID for 1-step transfers */
250
+ declare const TRANSFER_FACTORY_TEMPLATE_ID = "Splice.Api.Token.TransferFactoryV1:TransferFactory";
251
+ /** USDCx instrument identifier */
252
+ declare const USDCX_INSTRUMENT_ID = "USDCx";
253
+ interface TransferResult {
254
+ updateId: string;
255
+ completionOffset: number;
256
+ commandId: string;
257
+ }
258
+ interface TransferParams {
259
+ recipient: string;
260
+ amount: string;
261
+ commandId?: string;
262
+ }
263
+ declare class USDCxService {
264
+ private readonly client;
265
+ private readonly partyId;
266
+ constructor(client: CantonClient, partyId: string);
267
+ /**
268
+ * Query all USDCx Holding contracts for this party.
269
+ */
270
+ getHoldings(): Promise<USDCxHolding[]>;
271
+ /**
272
+ * Calculate total USDCx balance by summing all holding amounts.
273
+ * Returns a string with up to 10 decimal places.
274
+ */
275
+ getBalance(): Promise<string>;
276
+ /**
277
+ * Transfer USDCx using TransferFactory_Transfer (1-step).
278
+ * Requires the recipient to have an active TransferPreapproval.
279
+ */
280
+ transfer(params: TransferParams): Promise<TransferResult>;
281
+ /**
282
+ * Merge multiple holdings into fewer UTXOs.
283
+ * Returns the commandId of the merge transaction.
284
+ */
285
+ mergeHoldings(holdingCids: string[]): Promise<string>;
286
+ }
287
+
288
+ /**
289
+ * String-based decimal arithmetic for Canton amounts.
290
+ *
291
+ * Canton uses Numeric 10 (up to 10 decimal places). USDCx has 6 meaningful decimals.
292
+ * ALL arithmetic is pure string manipulation — NO floating point.
293
+ */
294
+ /**
295
+ * Validate that a string is a valid non-negative decimal amount.
296
+ */
297
+ declare function isValidAmount(s: string): boolean;
298
+ /**
299
+ * Compare two decimal amount strings.
300
+ * Returns -1 if a < b, 0 if a === b, 1 if a > b.
301
+ */
302
+ declare function compareAmounts(a: string, b: string): -1 | 0 | 1;
303
+ /**
304
+ * Add two decimal amount strings. Returns the sum as a string.
305
+ */
306
+ declare function addAmounts(a: string, b: string): string;
307
+ /**
308
+ * Subtract b from a. Both must be valid amounts and a >= b.
309
+ * Throws if a < b.
310
+ */
311
+ declare function subtractAmounts(a: string, b: string): string;
312
+ /**
313
+ * Pad (or truncate) a decimal string to exactly N decimal places.
314
+ * Default: 10 (Canton Numeric 10).
315
+ */
316
+ declare function toCantonAmount(s: string, decimals?: number): string;
317
+
318
+ /**
319
+ * Wallet keystore — AES-256-GCM encrypted storage for Canton agent credentials.
320
+ *
321
+ * Storage format (JSON, base64-encoded fields):
322
+ * { iv, salt, encrypted, tag }
323
+ *
324
+ * Key derivation: PIN → PBKDF2 (100k iterations, SHA-256) → 32-byte AES key.
325
+ * Uses Node.js built-in crypto module only.
326
+ */
327
+ interface WalletData {
328
+ partyId: string;
329
+ jwt: string;
330
+ userId: string;
331
+ privateKey: string;
332
+ }
333
+ declare class Keystore {
334
+ private data;
335
+ private filePath;
336
+ private constructor();
337
+ /** Party ID of this wallet. */
338
+ get address(): string;
339
+ /**
340
+ * Create a new encrypted wallet.
341
+ * Generates a random 32-byte private key and saves encrypted to disk.
342
+ */
343
+ static create(pin: string, params: {
344
+ partyId: string;
345
+ jwt: string;
346
+ userId: string;
347
+ }, path?: string): Promise<Keystore>;
348
+ /**
349
+ * Load and decrypt an existing wallet.
350
+ * Throws if the PIN is wrong or the file is corrupted.
351
+ */
352
+ static load(pin: string, path?: string): Promise<Keystore>;
353
+ /** Get credentials for Canton Ledger API access. */
354
+ getCredentials(): {
355
+ partyId: string;
356
+ jwt: string;
357
+ userId: string;
358
+ };
359
+ /** Change the encryption PIN. Re-encrypts wallet data with new PIN. */
360
+ changePin(oldPin: string, newPin: string): Promise<void>;
361
+ /** Export the raw private key. Dangerous — only call with explicit user consent. */
362
+ exportKey(pin: string): string;
363
+ }
364
+
365
+ /**
366
+ * Agent configuration — load/save ~/.caypo/config.json
367
+ */
368
+ interface TrafficConfig {
369
+ autoPurchase: boolean;
370
+ minBalance: number;
371
+ purchaseAmountCC: string;
372
+ }
373
+ interface SafeguardsConfig {
374
+ txLimit: string;
375
+ dailyLimit: string;
376
+ }
377
+ interface MppConfig {
378
+ gatewayUrl: string;
379
+ maxAutoPayPrice: string;
380
+ }
381
+ interface AgentConfig {
382
+ version: number;
383
+ network: "mainnet" | "testnet" | "devnet";
384
+ ledgerUrl: string;
385
+ partyId: string;
386
+ userId: string;
387
+ keystorePath: string;
388
+ traffic: TrafficConfig;
389
+ safeguards: SafeguardsConfig;
390
+ mpp: MppConfig;
391
+ }
392
+ declare const DEFAULT_CONFIG: AgentConfig;
393
+ /**
394
+ * Load agent configuration from disk.
395
+ * Returns DEFAULT_CONFIG merged with file contents.
396
+ */
397
+ declare function loadConfig(path?: string): Promise<AgentConfig>;
398
+ /**
399
+ * Save agent configuration to disk.
400
+ * Creates parent directory if it doesn't exist.
401
+ */
402
+ declare function saveConfig(config: AgentConfig, path?: string): Promise<void>;
403
+
404
+ /**
405
+ * SafeguardManager — pre-transaction checks: tx limit, daily limit, lock.
406
+ *
407
+ * Storage: ~/.caypo/safeguards.json
408
+ * All amounts are strings (no floating point).
409
+ */
410
+ interface SafeguardConfig {
411
+ txLimit: string;
412
+ dailyLimit: string;
413
+ locked: boolean;
414
+ lockedPinHash: string;
415
+ dailySpent: string;
416
+ lastResetDate: string;
417
+ }
418
+ interface CheckResult {
419
+ allowed: boolean;
420
+ reason?: string;
421
+ dailyRemaining: string;
422
+ }
423
+ declare class SafeguardManager {
424
+ private config;
425
+ private readonly filePath;
426
+ constructor(config?: SafeguardConfig, filePath?: string);
427
+ /**
428
+ * Load safeguards from disk. Returns a new SafeguardManager.
429
+ * If file doesn't exist, uses defaults.
430
+ */
431
+ static load(path?: string): Promise<SafeguardManager>;
432
+ /** Get current safeguard settings. */
433
+ settings(): SafeguardConfig;
434
+ /** Set per-transaction limit. */
435
+ setTxLimit(amount: string): void;
436
+ /** Set daily spending limit. */
437
+ setDailyLimit(amount: string): void;
438
+ /** Lock the wallet. All transactions will be rejected until unlocked. */
439
+ lock(pin?: string): void;
440
+ /** Unlock the wallet. Requires PIN if one was set during lock. */
441
+ unlock(pin: string): void;
442
+ /**
443
+ * Check if a transaction for the given amount is allowed.
444
+ * Auto-resets daily counter if the date has changed.
445
+ */
446
+ check(amount: string): CheckResult;
447
+ /** Record a completed spend. Call after successful transaction. */
448
+ recordSpend(amount: string): void;
449
+ /** Manually reset the daily counter. */
450
+ resetDaily(): void;
451
+ private autoResetDaily;
452
+ private save;
453
+ }
454
+
455
+ /**
456
+ * CheckingAccount — high-level USDCx checking account.
457
+ *
458
+ * Wraps USDCxService with safeguard checks and transaction history.
459
+ */
460
+
461
+ interface SendOptions {
462
+ memo?: string;
463
+ commandId?: string;
464
+ }
465
+ interface TransactionRecord {
466
+ updateId: string;
467
+ commandId: string;
468
+ effectiveAt: string;
469
+ offset: number;
470
+ type: "send" | "receive" | "unknown";
471
+ amount?: string;
472
+ counterparty?: string;
473
+ }
474
+ declare class CheckingAccount {
475
+ private readonly usdcx;
476
+ private readonly safeguards;
477
+ private readonly client;
478
+ private readonly partyId;
479
+ constructor(usdcx: USDCxService, safeguards: SafeguardManager, client: CantonClient, partyId: string);
480
+ /** Get USDCx balance: total available and number of UTXO holdings. */
481
+ balance(): Promise<{
482
+ available: string;
483
+ holdingCount: number;
484
+ }>;
485
+ /**
486
+ * Send USDCx to a recipient.
487
+ * Checks safeguards before executing the transfer.
488
+ */
489
+ send(recipient: string, amount: string, opts?: SendOptions): Promise<TransferResult>;
490
+ /** Party ID for receiving payments. */
491
+ address(): string;
492
+ /**
493
+ * Query transaction history via /v2/updates/flats.
494
+ * Returns recent flat transactions involving this party.
495
+ */
496
+ history(opts?: {
497
+ limit?: number;
498
+ }): Promise<TransactionRecord[]>;
499
+ }
500
+
501
+ /**
502
+ * MppPayClient — automatic HTTP 402 payment handling.
503
+ *
504
+ * Flow:
505
+ * 1. Fetch URL
506
+ * 2. If 402, parse WWW-Authenticate header for canton payment challenge
507
+ * 3. Check maxPrice against challenge amount
508
+ * 4. Check safeguards
509
+ * 5. Execute USDCx transfer via TransferFactory_Transfer
510
+ * 6. Build credential (base64-encoded payload)
511
+ * 7. Retry request with Authorization: Payment <credential>
512
+ * 8. Return { response, receipt?, paid }
513
+ */
514
+
515
+ interface PayOptions {
516
+ method?: string;
517
+ headers?: Record<string, string>;
518
+ body?: string;
519
+ maxPrice?: string;
520
+ }
521
+ interface PayResult {
522
+ response: Response;
523
+ paid: boolean;
524
+ receipt?: {
525
+ updateId: string;
526
+ completionOffset: number;
527
+ commandId: string;
528
+ amount: string;
529
+ };
530
+ }
531
+ interface PaymentChallenge {
532
+ amount: string;
533
+ currency: string;
534
+ recipient: string;
535
+ network: string;
536
+ description?: string;
537
+ }
538
+ /**
539
+ * Parse a WWW-Authenticate header for Canton payment parameters.
540
+ *
541
+ * Expected format:
542
+ * Payment method="canton", amount="0.01", currency="USDCx",
543
+ * recipient="Gateway::1220...", network="mainnet"
544
+ */
545
+ declare function parseWwwAuthenticate(header: string): PaymentChallenge | null;
546
+ declare class MppPayClient {
547
+ private readonly usdcx;
548
+ private readonly safeguards;
549
+ private readonly partyId;
550
+ private readonly network;
551
+ constructor(usdcx: USDCxService, safeguards: SafeguardManager, partyId: string, network: string);
552
+ /**
553
+ * Pay for an API call via MPP 402 flow.
554
+ * If the response is not 402, returns it as-is with paid=false.
555
+ */
556
+ pay(url: string, opts?: PayOptions): Promise<PayResult>;
557
+ }
558
+
559
+ /**
560
+ * TrafficManager — Canton traffic budget management.
561
+ *
562
+ * Canton does NOT have per-transaction gas fees. Instead, each validator
563
+ * has a traffic budget (bandwidth allocation). Additional traffic can be
564
+ * purchased by burning Canton Coin (CC).
565
+ *
566
+ * NOTE: The actual traffic API depends on the validator/participant setup.
567
+ * This provides the interface with a reasonable stub implementation.
568
+ * Real implementation requires validator admin API access.
569
+ */
570
+
571
+ interface TrafficBalance {
572
+ totalPurchased: number;
573
+ consumed: number;
574
+ remaining: number;
575
+ }
576
+ interface AutoPurchaseConfig {
577
+ enabled: boolean;
578
+ minBalance: number;
579
+ purchaseAmount: string;
580
+ }
581
+ declare class TrafficManager {
582
+ private readonly client;
583
+ private readonly partyId;
584
+ private autoPurchaseConfig;
585
+ constructor(client: CantonClient, partyId: string);
586
+ /**
587
+ * Check validator's traffic balance.
588
+ *
589
+ * TODO: Implement using actual validator admin API.
590
+ * The traffic balance is a validator-level concept, not per-party.
591
+ * For now, returns a stub indicating sufficient traffic.
592
+ */
593
+ trafficBalance(): Promise<TrafficBalance>;
594
+ /**
595
+ * Purchase additional traffic by burning Canton Coin (CC).
596
+ *
597
+ * TODO: Implement using actual CC burn mechanism.
598
+ */
599
+ purchaseTraffic(ccAmount: string): Promise<{
600
+ txId: string;
601
+ }>;
602
+ /**
603
+ * Check if there's sufficient traffic for a standard operation.
604
+ * Returns true if remaining traffic > minimum threshold.
605
+ */
606
+ hasSufficientTraffic(): Promise<boolean>;
607
+ /** Configure auto-purchase settings. */
608
+ setAutoPurchase(config: AutoPurchaseConfig): void;
609
+ /** Get current auto-purchase configuration. */
610
+ getAutoPurchaseConfig(): AutoPurchaseConfig;
611
+ }
612
+
613
+ /**
614
+ * CantonAgent — high-level entry point for the Canton SDK.
615
+ *
616
+ * Creates and wires together all sub-services:
617
+ * - CheckingAccount (USDCx balance, send, history)
618
+ * - SafeguardManager (tx limits, daily limits, lock)
619
+ * - TrafficManager (validator traffic budgets)
620
+ * - MppPayClient (HTTP 402 auto-pay)
621
+ */
622
+
623
+ interface WalletInfo {
624
+ address: string;
625
+ partyId: string;
626
+ network: string;
627
+ }
628
+ interface CantonAgentConfig {
629
+ ledgerUrl?: string;
630
+ token?: string;
631
+ userId?: string;
632
+ partyId?: string;
633
+ network?: "mainnet" | "testnet" | "devnet";
634
+ configPath?: string;
635
+ safeguardsPath?: string;
636
+ }
637
+ declare class CantonAgent {
638
+ readonly checking: CheckingAccount;
639
+ readonly safeguards: SafeguardManager;
640
+ readonly traffic: TrafficManager;
641
+ readonly mpp: MppPayClient;
642
+ readonly wallet: WalletInfo;
643
+ private readonly client;
644
+ private readonly usdcx;
645
+ private constructor();
646
+ /**
647
+ * Create a new CantonAgent from config.
648
+ *
649
+ * Loads configuration from ~/.caypo/config.json (or overrides),
650
+ * initializes all sub-services, and wires them together.
651
+ */
652
+ static create(config?: CantonAgentConfig): Promise<CantonAgent>;
653
+ /**
654
+ * Create a CantonAgent from explicit parameters (no file I/O).
655
+ * Useful for testing and programmatic setup.
656
+ */
657
+ static fromParams(params: {
658
+ client: CantonClient;
659
+ partyId: string;
660
+ network: string;
661
+ safeguards?: SafeguardManager;
662
+ }): CantonAgent;
663
+ }
664
+
665
+ /**
666
+ * @caypo/canton-sdk — Core SDK for Canton Network.
667
+ * JSON Ledger API v2 client, USDCx operations, agent accounts.
668
+ */
669
+
670
+ declare const CANTON_SDK_VERSION = "0.1.0";
671
+ declare const DEFAULT_LEDGER_PORT = 7575;
672
+
673
+ export { type ActiveContract, type ActiveContractsRequest, type AgentConfig, type AnyPartyFilter, type ArchivedEvent, type AutoPurchaseConfig, CANTON_SDK_VERSION, CantonAgent, type CantonAgentConfig, CantonApiError, CantonAuthError, CantonClient, type CantonClientConfig, type CantonErrorCode, CantonTimeoutError, type CheckResult, CheckingAccount, type Command, type CreateCommand, type CreatedEvent, DEFAULT_CONFIG, DEFAULT_LEDGER_PORT, type EventFormat, type ExerciseCommand, type ExercisedEvent, type FlatTransaction, type HoldingSelection, type IdentifierFilter, InsufficientBalanceError, Keystore, type LedgerEndResponse, type LedgerError, type MppConfig, MppPayClient, type PartyDetails, type PartyFilter, type PartyLocalMetadata, type PayOptions, type PayResult, type PaymentChallenge, type QueryActiveContractsParams, type SafeguardConfig, SafeguardManager, type SafeguardsConfig, type SendOptions, type SubmitAndWaitRequest, type SubmitAndWaitResponse, type SubmitParams, TRANSFER_FACTORY_TEMPLATE_ID, type TrafficBalance, type TrafficConfig, TrafficManager, type TransactionRecord, type TransactionResponse, type TransactionTree, type TransactionTreeEvent, type TransferParams, type TransferResult, USDCX_HOLDING_TEMPLATE_ID, USDCX_INSTRUMENT_ID, type USDCxHolding, USDCxService, type WalletData, type WalletInfo, addAmounts, compareAmounts, isValidAmount, loadConfig, parseWwwAuthenticate, saveConfig, selectHoldings, subtractAmounts, toCantonAmount };