forked from Lead-Studios/veritix-contract-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
875 lines (790 loc) · 30.7 KB
/
Copy pathclient.ts
File metadata and controls
875 lines (790 loc) · 30.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
/**
* @module client
* Entry point for the VeriTix Contract SDK.
*
* {@link VeriTixClient} is the single object consumers interact with.
* It owns the Soroban RPC connection and exposes namespaced module instances
* for every contract feature area.
*
* @example
* ```ts
* import { VeriTixClient, getTestnetConfig } from '@veritix/contract-sdk';
* import { Keypair } from '@stellar/stellar-sdk';
*
* const config = getTestnetConfig('CXXXXXXX…');
* const keypair = Keypair.fromSecret(process.env.STELLAR_SECRET_KEY!);
* const client = new VeriTixClient(config, keypair);
*
* await client.connect();
*
* const result = await client.escrow.createEscrow({
* beneficiary: 'GABC…',
* amount: 1_000_000n,
* expiryLedger: 1_000_000,
* });
* console.log('Escrow tx hash:', result.hash);
* ```
*/
import { SorobanRpc, Keypair, Contract, StrKey, xdr } from '@stellar/stellar-sdk';
declare const window: unknown;
declare const document: unknown;
import type {
NetworkConfig,
SimulationResult,
ContractMetadata,
TransactionResult,
StellarNetwork,
WatchOptions,
EscrowRecord,
AccountInfo,
VeriTixEvent,
StreamEventOptions,
} from './types/index';
import { buildContractCall, simulateTransaction } from './utils/transaction';
import { DUMMY_PUBLIC_KEY, getMainnetConfig, getTestnetConfig } from './utils/network';
import { EventEmitter } from 'events';
import { VeriTixError, VeriTixErrorCode } from './utils/errors';
import { TokenModule } from './modules/token';
import { EscrowModule } from './modules/escrow';
import { DisputeModule } from './modules/dispute';
import { SplitterModule } from './modules/splitter';
import { RecurringModule } from './modules/recurring';
import { AdminModule } from './modules/admin';
import { BatchModule } from './modules/batch';
import { createSafeToJSON, createSafeInspect } from './client-security';
/** Strongly-typed event map for VeriTixClient */
export interface VeriTixClientEvents {
connected: (data: { ledger: number }) => void;
disconnected: () => void;
error: (err: VeriTixError) => void;
retry: (data: { attempt: number; delayMs: number }) => void;
}
/**
* The primary SDK class. One instance per contract / network pair.
*
* Instantiate it, call {@link connect}, then access feature modules via the
* named properties.
*/
export class VeriTixClient extends EventEmitter {
/** Network + contract configuration supplied at construction time */
public readonly config: NetworkConfig;
/** Token operations: mint, burn, transfer, approve, balance */
public readonly token: TokenModule;
/** Escrow operations: create, release, refund, getEscrow */
public readonly escrow: EscrowModule;
/** Dispute operations: open, resolve, getDispute */
public readonly dispute: DisputeModule;
/** Payment splitter operations: createSplit, distribute, getSplit */
public readonly splitter: SplitterModule;
/** Recurring payment operations: setup, execute, cancel, getRecurring */
public readonly recurring: RecurringModule;
/** Admin operations: setAdmin, freeze, unfreeze, clawback, pause */
public readonly admin: AdminModule;
/** Batch operations: mintBatch, transferBatch, freezeBatch */
public readonly batch: BatchModule;
private server!: SorobanRpc.Server;
protected readonly keypair: Keypair | undefined;
private connected = false;
/** Cache for getCurrentLedger — { sequence, fetchedAt } */
private ledgerCache: { sequence: number; fetchedAt: number } | null = null;
private static readonly LEDGER_CACHE_TTL_MS = 5_000;
/**
* Creates a new `VeriTixClient`.
*
* @param config - Network and contract configuration.
* Use {@link getTestnetConfig} or {@link getMainnetConfig}
* to build this object conveniently.
* @param keypair - Optional Stellar `Keypair` used to sign write transactions.
* Omit for read-only usage.
*/
constructor(config: NetworkConfig, keypair?: Keypair) {
super();
if (!config || typeof config.contractId !== 'string' || !StrKey.isValidContract(config.contractId)) {
throw new VeriTixError(
VeriTixErrorCode.InvalidAddress,
'VeriTixClient: config.contractId must be a valid Soroban contract ID',
);
}
this.config = config;
this.keypair = keypair;
// Modules are created eagerly; they receive `this.server` by reference
// after connect() sets it up. Module methods must call connect() guard.
const lazyServer = this.getLazyServer();
this.token = new TokenModule(config, lazyServer, keypair);
this.escrow = new EscrowModule(config, lazyServer, keypair);
this.dispute = new DisputeModule(config, lazyServer, keypair);
this.splitter = new SplitterModule(config, lazyServer, keypair);
this.recurring = new RecurringModule(config, lazyServer, keypair);
this.admin = new AdminModule(config, lazyServer, keypair);
this.batch = new BatchModule(config, lazyServer, keypair);
}
/** Serialises the client without exposing the secret keypair. */
toJSON(): Record<string, unknown> {
return createSafeToJSON(this)();
}
/** Redacts the keypair when the client is logged via console/util.inspect. */
[Symbol.for('nodejs.util.inspect.custom')](): (depth: number, opts: object) => string {
return createSafeInspect();
}
// -------------------------------------------------------------------------
// Static factories
// -------------------------------------------------------------------------
/**
* Builds a {@link VeriTixClient} from environment variables. Intended for
* server-side / worker use where {@link NetworkConfig} values are loaded
* from `process.env` rather than constructed in code.
*
* Recognised variables (case-sensitive, all optional except as noted):
* - `VERITIX_CONTRACT_ID` (required) — Soroban contract ID.
* - `STELLAR_NETWORK` (default `'testnet'`) — `'testnet'` | `'mainnet'`.
* - `VERITIX_RPC_URL` (optional) — overrides the network default.
* - `VERITIX_NETWORK_PASSPHRASE` (optional) — overrides the network default.
* - `VERITIX_SECRET_KEY` (optional) — Stellar secret key. When
* present the returned client can sign write transactions; otherwise it
* is read-only.
*
* Accepts an env-shaped object so callers can inject test values without
* mutating global `process.env`.
*
* @param env - Optional env-like object. Defaults to `process.env`.
* @returns A new `VeriTixClient` (caller must still call `connect()`).
* @throws {VeriTixError} `InvalidAddress` if `VERITIX_CONTRACT_ID` is missing
* or if `STELLAR_NETWORK` / `VERITIX_SECRET_KEY` are present but malformed.
*
* @example
* ```ts
* // Server entry-point
* const client = VeriTixClient.fromEnvironment();
* await client.connect();
* ```
*/
static fromEnvironment(env: NodeJS.ProcessEnv = process.env): VeriTixClient {
// Guard against browser bundles: a statically-inlined secret key would
// end up shipped to every client. Require an explicit client in browsers.
const globals = globalThis as { window?: unknown; document?: unknown };
if (globals.window !== undefined || globals.document !== undefined) {
if (typeof globalThis !== 'undefined' &&
(globalThis as unknown as { window?: unknown }).window !== undefined) {
if (
typeof (globalThis as { window?: unknown }).window !== 'undefined' ||
typeof (globalThis as { document?: unknown }).document !== 'undefined'
) {
throw new VeriTixError(
VeriTixErrorCode.ReadOnlyClient,
'VeriTixClient.fromEnvironment is not available in browser contexts; construct a VeriTixClient explicitly and never inline a secret key',
);
}
const source: NodeJS.ProcessEnv = env ?? {};
// VERITIX_CONTRACT_ID — required.
const rawContractId = source.VERITIX_CONTRACT_ID;
if (typeof rawContractId !== 'string' || rawContractId.trim().length === 0) {
throw new VeriTixError(
VeriTixErrorCode.InvalidAddress,
'VeriTixClient.fromEnvironment: VERITIX_CONTRACT_ID is required and must be a non-empty string',
);
}
const contractId = rawContractId.trim();
// STELLAR_NETWORK — default 'testnet'; must be 'testnet' or 'mainnet'.
const networkRaw = (source.STELLAR_NETWORK ?? 'testnet').toString().trim().toLowerCase();
if (networkRaw !== 'testnet' && networkRaw !== 'mainnet') {
throw new VeriTixError(
VeriTixErrorCode.InvalidAddress,
`VeriTixClient.fromEnvironment: STELLAR_NETWORK must be 'testnet' or 'mainnet', got ${JSON.stringify(
source.STELLAR_NETWORK,
)}`,
);
}
const network: StellarNetwork = networkRaw;
// Build base config from the network helper, then layer optional overrides.
const baseConfig: NetworkConfig =
network === 'mainnet' ? getMainnetConfig(contractId) : getTestnetConfig(contractId);
const rpcOverride = source.VERITIX_RPC_URL;
const passphraseOverride = source.VERITIX_NETWORK_PASSPHRASE;
const config: NetworkConfig = {
...baseConfig,
rpcUrl:
typeof rpcOverride === 'string' && rpcOverride.length > 0 ? rpcOverride : baseConfig.rpcUrl,
networkPassphrase:
typeof passphraseOverride === 'string' && passphraseOverride.length > 0
? passphraseOverride
: baseConfig.networkPassphrase,
};
// VERITIX_SECRET_KEY — optional; attaches a Keypair for write operations.
let keypair: Keypair | undefined;
const secret = source.VERITIX_SECRET_KEY;
if (typeof secret === 'string' && secret.length > 0) {
try {
keypair = Keypair.fromSecret(secret);
} catch (err) {
const reason = err instanceof Error ? err.message : String(err);
throw new VeriTixError(
VeriTixErrorCode.InvalidAddress,
`VeriTixClient.fromEnvironment: VERITIX_SECRET_KEY is malformed: ${reason}`,
);
}
}
return new VeriTixClient(config, keypair);
}
// -------------------------------------------------------------------------
// Typed event emitter overloads
// -------------------------------------------------------------------------
on<K extends keyof VeriTixClientEvents>(event: K, listener: VeriTixClientEvents[K]): this {
return super.on(event, listener as (...args: unknown[]) => void);
}
emit<K extends keyof VeriTixClientEvents>(
event: K,
...args: Parameters<VeriTixClientEvents[K]>
): boolean {
return super.emit(event, ...args);
}
// -------------------------------------------------------------------------
// Connection
// -------------------------------------------------------------------------
/**
* Initialises the Soroban RPC server connection and verifies it is reachable
* by fetching the current ledger sequence.
*
* Retries with exponential backoff up to `config.retries` times (default 3).
*
* @returns The current Stellar ledger sequence number.
* @throws {VeriTixError} With code `CONNECTION_FAILED` if unreachable after all retries.
*
* @example
* ```ts
* const ledger = await client.connect();
* console.log('Connected — current ledger:', ledger);
* ```
*/
async connect(): Promise<number> {
const retries = this.config.retries ?? 3;
const retryDelayMs = this.config.retryDelayMs ?? 1_000;
this.server = new SorobanRpc.Server(this.config.rpcUrl, { allowHttp: false });
let lastError: unknown;
for (let attempt = 0; attempt <= retries; attempt++) {
try {
const latestLedger = await this.server.getLatestLedger();
this.connected = true;
this.ledgerCache = { sequence: latestLedger.sequence, fetchedAt: Date.now() };
this.emit('connected', { ledger: latestLedger.sequence });
return latestLedger.sequence;
} catch (err) {
lastError = err;
if (attempt < retries) {
const delayMs = retryDelayMs * Math.pow(2, attempt);
this.emit('retry', { attempt: attempt + 1, delayMs });
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
}
}
const error = new VeriTixError(
VeriTixErrorCode.ConnectionFailed,
`Failed to connect to RPC at ${this.config.rpcUrl}: ${String(lastError)}`,
);
this.emit('error', error);
throw error;
}
/**
* Performs a lightweight health check of the RPC endpoint and contract.
*
* @returns Whether the RPC is reachable, whether the contract was found on
* the network, and the measured latency of the RPC call in ms.
*
* @example
* const { rpcReachable, contractFound, latencyMs } = await client.healthCheck();
*/
async healthCheck(): Promise<{ rpcReachable: boolean; contractFound: boolean; latencyMs: number }> {
if (!this.connected) {
throw new VeriTixError(
VeriTixErrorCode.ConnectionFailed,
'VeriTixClient: call connect() before healthCheck()',
);
}
const start = Date.now();
let rpcReachable = false;
try {
await this.server.getLatestLedger();
rpcReachable = true;
} catch {
rpcReachable = false;
}
const latencyMs = Date.now() - start;
let contractFound = false;
if (rpcReachable) {
try {
const entries = await this.server.getLedgerEntries(
new Contract(this.config.contractId).getFootprint(),
const contract = new Contract(this.config.contractId);
await this.server.getContractData(
new Contract(this.config.contractId).address(),
xdr.ScVal.scvVoid(),
this.config.contractId,
new Contract(this.config.contractId).address().toScVal(),
);
contractFound = (entries.entries ?? []).length > 0;
} catch {
contractFound = false;
}
}
return { rpcReachable, contractFound, latencyMs };
}
/**
* Releases the server connection and resets client state.
* Emits a `disconnected` event.
*/
disconnect(): void {
this.connected = false;
this.server = null as unknown as SorobanRpc.Server;
this.ledgerCache = null;
this.emit('disconnected');
}
/**
* Returns `true` if {@link connect} has been called successfully.
*/
isConnected(): boolean {
return this.connected;
}
/**
* Returns `true` when no `Keypair` was supplied — write operations will
* throw `VeriTixError` with code `READ_ONLY_CLIENT`.
*/
isReadOnly(): boolean {
return !this.keypair;
}
// -------------------------------------------------------------------------
// Simulation (#77)
// -------------------------------------------------------------------------
/**
* Dry-runs any contract method without submitting a transaction.
* Works without a `Keypair` — no XLM is spent.
*
* @param method - Contract function name to invoke.
* @param args - Ordered XDR `ScVal` arguments.
* @returns A {@link SimulationResult} with the return value and estimated fee.
*
* @example
* ```ts
* const result = await client.simulate('get_escrow', [nativeToScVal(1n, { type: 'u64' })]);
* if (result.success) console.log('Return value:', result.returnValue);
* ```
*/
async simulate(method: string, args: xdr.ScVal[]): Promise<SimulationResult> {
if (!this.connected) {
throw new VeriTixError(
VeriTixErrorCode.ClientNotConnected,
'VeriTixClient: call connect() before simulate()'
);
}
try {
// Use a throwaway source account (simulation does not require a real funded account)
const { Account } = await import('@stellar/stellar-sdk');
const sourceAccount = new Account(DUMMY_PUBLIC_KEY, '0');
const tx = await buildContractCall(
this.server,
sourceAccount,
this.config.contractId,
method,
args,
this.config.networkPassphrase,
);
const { transaction, simulatedFee } = await simulateTransaction(this.server, tx);
// Extract the return value from the simulation result XDR if available
const rawResult = await this.server.simulateTransaction(tx);
const returnValue =
SorobanRpc.Api.isSimulationSuccess(rawResult) && rawResult.result
? rawResult.result.retval
: undefined;
void transaction; // assembled tx not needed for simulate-only path
return {
success: true,
returnValue,
estimatedFee: simulatedFee,
};
} catch (err) {
return {
success: false,
returnValue: undefined,
estimatedFee: '0',
error: err instanceof Error ? err.message : String(err),
};
}
}
// Convenience methods
// -------------------------------------------------------------------------
/**
* Returns the current ledger sequence number.
* Result is cached for 5 seconds to avoid hammering the RPC.
*
* @throws If not connected.
*/
async getCurrentLedger(): Promise<number> {
if (!this.connected || !this.server) {
throw new VeriTixError(
VeriTixErrorCode.ClientNotConnected,
'VeriTixClient: call connect() before using module methods'
);
}
const now = Date.now();
if (
this.ledgerCache &&
now - this.ledgerCache.fetchedAt < VeriTixClient.LEDGER_CACHE_TTL_MS
) {
return this.ledgerCache.sequence;
}
const latestLedger = await this.server.getLatestLedger();
this.ledgerCache = { sequence: latestLedger.sequence, fetchedAt: now };
return latestLedger.sequence;
}
/**
* Polls the RPC until the transaction is confirmed or fails.
*
* @param hash - Stellar transaction hash to watch.
* @param options - Polling interval and timeout options.
* @returns Resolved {@link TransactionResult} when the transaction is confirmed.
* @throws {VeriTixError} `TRANSACTION_FAILED` if the transaction fails.
* @throws {VeriTixError} `WATCH_TIMEOUT` after `timeoutMs` ms.
*/
async watchTransaction(hash: string, options?: WatchOptions): Promise<TransactionResult> {
if (!this.connected || !this.server) {
throw new VeriTixError(
VeriTixErrorCode.ClientNotConnected,
'VeriTixClient: call connect() before using module methods'
);
}
const intervalMs = options?.intervalMs ?? 2_000;
const timeoutMs = options?.timeoutMs ?? 60_000;
const deadline = Date.now() + timeoutMs;
return new Promise((resolve, reject) => {
const poll = async () => {
if (Date.now() >= deadline) {
return reject(
new VeriTixError(VeriTixErrorCode.WatchTimeout, `Transaction ${hash} timed out after ${timeoutMs}ms`),
);
}
try {
const result = await this.server.getTransaction(hash);
if (result.status === 'SUCCESS') {
return resolve({
hash,
ledger: (result as { ledger?: number }).ledger ?? 0,
successful: true,
returnValue: (result as { returnValue?: unknown }).returnValue,
});
}
if (result.status === 'FAILED') {
return reject(
new VeriTixError(VeriTixErrorCode.TransactionFailed, `Transaction ${hash} failed`),
);
}
// NOT_FOUND or PENDING — keep polling
setTimeout(poll, intervalMs);
} catch {
setTimeout(poll, intervalMs);
}
};
void poll();
});
}
/**
* Fetches token metadata: name, symbol, decimals, totalSupply, contractId, network.
*
* @throws If not connected.
*/
async getContractMetadata(): Promise<ContractMetadata> {
if (!this.connected || !this.server) {
throw new VeriTixError(
VeriTixErrorCode.ClientNotConnected,
'VeriTixClient: call connect() before using module methods'
);
}
const [name, symbol, decimal, totalSupply] = await Promise.all([
this.token.name(),
this.token.symbol(),
this.token.decimals(),
this.token.totalSupply(),
]);
return {
name,
symbol,
decimal,
totalSupply,
contractId: this.config.contractId,
network: this.config.network,
};
}
/**
* Fetches Stellar account information including XLM balance, sequence number, and subentry count.
*
* @param address - Stellar account address to fetch information for
* @returns Promise resolving to AccountInfo with the account details
* @throws {VeriTixError} InvalidAddress if the account does not exist or the address is invalid
*/
async getAccountInfo(address: string): Promise<AccountInfo> {
if (!this.connected || !this.server) {
throw new VeriTixError(
VeriTixErrorCode.ClientNotConnected,
'VeriTixClient: call connect() before using module methods'
);
}
// Validate the address is a valid Stellar public key
if (!StrKey.isValidEd25519PublicKey(address)) {
throw new VeriTixError(
VeriTixErrorCode.InvalidAddress,
`Invalid Stellar account address: ${address}`
);
}
try {
const account = await this.server.getAccount(address);
// Find the native XLM balance
const xlmBalance = account.balances.find(balance => balance.asset_type === 'native')?.balance || '0';
// Convert XLM balance (which is in XLM with 7 decimals) to stroops (1 XLM = 10^7 stroops)
const xlmBalanceInStroops = (parseFloat(xlmBalance) * 10_000_000).toString();
return {
address: account.account_id,
xlmBalance: xlmBalanceInStroops,
sequence: account.sequence,
subentryCount: account.subentry_count,
};
} catch (err) {
// If the account doesn't exist or there's an error fetching it, throw InvalidAddress
throw new VeriTixError(
VeriTixErrorCode.InvalidAddress,
`Account does not exist or could not be fetched: ${address}`
);
}
}
// -------------------------------------------------------------------------
// watchEscrow (#153)
// -------------------------------------------------------------------------
/**
* Polls `getEscrow(id)` at the given interval and yields the record each
* time `released` or `refunded` flips to `true`.
*
* Throws a `VeriTixError` with code `WATCH_TIMEOUT` if no state change is
* detected within `timeoutMs`.
*
* @param id - Escrow ID to watch.
* @param options - {@link WatchOptions} (intervalMs, timeoutMs).
*
* @example
* ```ts
* for await (const record of client.watchEscrow(1n)) {
* console.log('Escrow settled:', record);
* break;
* }
* ```
*/
async *watchEscrow(id: bigint, options?: WatchOptions): AsyncIterableIterator<EscrowRecord> {
const intervalMs = options?.intervalMs ?? 3_000;
const timeoutMs = options?.timeoutMs ?? 60_000;
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const record = await this.escrow.getEscrow(id);
if (record && (record.released || record.refunded)) {
yield record;
return;
}
const remaining = deadline - Date.now();
if (remaining <= 0) break;
await new Promise<void>((resolve) => setTimeout(resolve, Math.min(intervalMs, remaining)));
}
throw new VeriTixError(
VeriTixErrorCode.WatchTimeout,
`watchEscrow timed out after ${timeoutMs}ms waiting for escrow ${id} to settle`,
);
}
// -------------------------------------------------------------------------
// Internal helpers
// -------------------------------------------------------------------------
/**
* Returns a proxy `SorobanRpc.Server` that throws a helpful error if
* `connect()` has not been called yet. Modules hold a reference to this
/**
* Connects to Horizon Server-Sent Events (SSE) endpoint to stream contract events in real-time.
* Automatically reconnects with exponential backoff if the stream drops. Supports cancellation via AbortSignal.
*
* @param options - {@link StreamEventOptions} for stream configuration (signal, backoff settings, cursor)
* @returns AsyncIterableIterator that yields {@link VeriTixEvent} as they are received
*
* @example
* ```ts
* const controller = new AbortController();
* for await (const event of client.streamEvents({ signal: controller.signal })) {
* console.log(`Received event: ${event.type} from ledger ${event.ledger}`);
* if (event.type === 'ticket_purchased') {
* console.log('New ticket sold!', event.data);
* }
* }
* ```
*/
async *streamEvents(options?: StreamEventOptions): AsyncIterableIterator<VeriTixEvent> {
if (!this.connected || !this.server) {
throw new VeriTixError(
VeriTixErrorCode.ClientNotConnected,
'VeriTixClient: call connect() before using streamEvents()'
);
}
// Get proper Horizon URL based on network
const TESTNET_HORIZON_URL = 'https://horizon-testnet.stellar.org';
const MAINNET_HORIZON_URL = 'https://horizon.stellar.org';
let baseHorizonUrl: string;
if (this.config.network === 'testnet') {
baseHorizonUrl = TESTNET_HORIZON_URL;
} else {
baseHorizonUrl = MAINNET_HORIZON_URL;
}
// If user provided a custom RPC URL that's not the default, try to derive Horizon URL from it
const isDefaultTestnetRpc = this.config.rpcUrl === 'https://soroban-testnet.stellar.org';
const isDefaultMainnetRpc = this.config.rpcUrl === 'https://mainnet.stellar.validationcloud.io/v1/soroban/rpc';
if (!isDefaultTestnetRpc && !isDefaultMainnetRpc) {
// Try to extract Horizon URL from custom RPC URL
baseHorizonUrl = this.config.rpcUrl.replace(/\/soroban\/rpc$/, '');
}
if (!baseHorizonUrl.endsWith('/')) {
baseHorizonUrl += '/';
}
const opts = {
initialBackoffMs: options?.initialBackoffMs ?? 1000,
maxBackoffMs: options?.maxBackoffMs ?? 30000,
signal: options?.signal,
cursor: options?.cursor,
};
let currentBackoff = opts.initialBackoffMs;
let eventQueue: VeriTixEvent[] = [];
let queueResolver: (() => void) | null = null;
let eventSource: any = null;
let isAborted = false;
// Dynamically import EventSource if in Node.js environment (browser has it globally)
let EventSourceImpl: typeof EventSource;
if (typeof EventSource === 'undefined') {
// Node.js environment - require eventsource package
try {
const { EventSource: NodeEventSource } = require('eventsource');
EventSourceImpl = NodeEventSource;
} catch (err) {
throw new VeriTixError(
VeriTixErrorCode.InvalidConfig,
'VeriTixClient: streamEvents() requires the "eventsource" package in Node.js environments. Please install it with npm install eventsource.'
);
}
} else {
// Browser environment - use global EventSource
EventSourceImpl = EventSource;
}
// Setup abort signal listener
if (opts.signal) {
opts.signal.addEventListener('abort', () => {
isAborted = true;
if (eventSource) {
eventSource.close();
eventSource = null;
}
if (queueResolver) {
queueResolver();
queueResolver = null;
}
});
}
// Function to create and connect EventSource
const connectStream = () => {
if (isAborted) return;
// Horizon SSE endpoint for contract events: /contract/<contractId>/events
const streamUrl = new URL(`contract/${this.config.contractId}/events`, baseHorizonUrl);
if (opts.cursor) {
streamUrl.searchParams.set('cursor', opts.cursor);
}
try {
eventSource = new EventSourceImpl(streamUrl.toString());
eventSource.onopen = () => {
// Reset backoff on successful connection
currentBackoff = opts.initialBackoffMs;
};
eventSource.onmessage = (event: any) => {
try {
const rawEvent = JSON.parse(event.data);
// Parse raw Horizon SSE event into VeriTixEvent (Horizon event format: https://developers.stellar.org/docs/data/horizon/api-reference/stream/contract-events)
const veriTixEvent: VeriTixEvent = {
type: rawEvent.topic?.[0] || 'unknown',
ledger: parseInt(rawEvent.ledger, 10),
timestamp: parseInt(rawEvent.created_at ? new Date(rawEvent.created_at).getTime() / 1000 : rawEvent.timestamp, 10),
topics: rawEvent.topic || [],
data: rawEvent.value,
};
eventQueue.push(veriTixEvent);
if (queueResolver) {
queueResolver();
queueResolver = null;
}
} catch (parseErr) {
// Skip invalid events
}
};
eventSource.onerror = () => {
if (eventSource) {
eventSource.close();
eventSource = null;
}
// Schedule reconnection with exponential backoff if not aborted
if (!isAborted) {
setTimeout(() => {
currentBackoff = Math.min(currentBackoff * 2, opts.maxBackoffMs);
connectStream();
}, currentBackoff);
}
};
} catch (err) {
// Handle connection errors, schedule reconnection
if (!isAborted) {
setTimeout(() => {
currentBackoff = Math.min(currentBackoff * 2, opts.maxBackoffMs);
connectStream();
}, currentBackoff);
}
}
};
// Start initial connection
connectStream();
// Yield events as they come in
while (!isAborted) {
if (eventQueue.length === 0) {
// Wait for new events
await new Promise<void>((resolve) => {
queueResolver = resolve;
});
} else {
const nextEvent = eventQueue.shift()!;
yield nextEvent;
}
}
}
/**
* proxy so they surface a clear message instead of a confusing crash.
*
* @internal
*/
private getLazyServer(): SorobanRpc.Server {
return new Proxy({} as SorobanRpc.Server, {
get: (_target, prop) => {
if (!this.connected || !this.server) {
throw new VeriTixError(
VeriTixErrorCode.ClientNotConnected,
`VeriTixClient: call connect() before using module methods (attempted access to server.${String(prop)})`
);
}
return (this.server as unknown as Record<string | symbol, unknown>)[prop];
},
});
}
/**
* Creates a new VeriTixClientPool that distributes calls across multiple RPC endpoints
* @param configs Array of NetworkConfig objects, one for each RPC endpoint
* @param keypair Optional Keypair to use for all clients in the pool
* @returns A proxy that acts like a VeriTixClient but distributes calls across the pool
*/
static pool(configs: NetworkConfig[], keypair?: Keypair) {
const { VeriTixClientPool } = require('./pool');
// Create a client for each configuration
const clients = configs.map(config => new VeriTixClient(config, keypair));
const pool = new VeriTixClientPool(clients);
return pool.proxy;
}
}