ton-provider-system 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.
@@ -0,0 +1,1686 @@
1
+ import { z } from 'zod';
2
+ import { TonClient } from '@ton/ton';
3
+ import { Address } from '@ton/core';
4
+
5
+ /**
6
+ * Unified Provider System - Type Definitions
7
+ *
8
+ * Core types for the TON RPC provider management system.
9
+ * These types are used across all components of the provider system.
10
+ */
11
+ /**
12
+ * Supported TON networks
13
+ */
14
+ type Network = 'testnet' | 'mainnet';
15
+ /**
16
+ * API version types supported by TON providers
17
+ * - v2: TON Center HTTP API v2 (JSON-RPC style) - most common
18
+ * - v4: TON API v4 (ton-community/ton-api-v4) - different format
19
+ */
20
+ type ApiVersion = 'v2' | 'v3' | 'v4';
21
+ /**
22
+ * Provider type identifier
23
+ */
24
+ type ProviderType = 'chainstack' | 'quicknode' | 'toncenter' | 'orbs' | 'onfinality' | 'ankr' | 'getblock' | 'tatum' | 'tonhub' | 'custom';
25
+ /**
26
+ * Provider endpoint configuration
27
+ */
28
+ interface ProviderEndpoints {
29
+ /** API v2 endpoint URL (may contain {key} placeholder) */
30
+ v2?: string;
31
+ /** API v3 endpoint URL (may contain {key} placeholder) */
32
+ v3?: string;
33
+ /** API v4 endpoint URL */
34
+ v4?: string;
35
+ /** WebSocket endpoint URL */
36
+ ws?: string;
37
+ }
38
+ /**
39
+ * Single provider definition from rpc.json config
40
+ */
41
+ interface ProviderConfig {
42
+ /** Human-readable provider name */
43
+ name: string;
44
+ /** Provider type for special handling */
45
+ type: ProviderType;
46
+ /** Network this provider serves */
47
+ network: Network;
48
+ /** Endpoint URLs */
49
+ endpoints: ProviderEndpoints;
50
+ /** Environment variable name for API key (replaces {key} in endpoints) */
51
+ keyEnvVar?: string;
52
+ /** Environment variable name for separate API key header */
53
+ apiKeyEnvVar?: string;
54
+ /** Requests per second limit */
55
+ rps: number;
56
+ /** Priority for selection (lower = higher priority) */
57
+ priority: number;
58
+ /** Whether this provider is enabled */
59
+ enabled: boolean;
60
+ /** Whether this provider requires dynamic endpoint discovery (e.g., Orbs) */
61
+ isDynamic?: boolean;
62
+ /** Optional description or notes */
63
+ description?: string;
64
+ }
65
+ /**
66
+ * Default provider order per network
67
+ */
68
+ interface NetworkDefaults {
69
+ testnet: string[];
70
+ mainnet: string[];
71
+ }
72
+ /**
73
+ * Complete rpc.json configuration file structure
74
+ */
75
+ interface RpcConfig {
76
+ /** JSON Schema reference (optional) */
77
+ $schema?: string;
78
+ /** Config version */
79
+ version: string;
80
+ /** Provider definitions keyed by unique ID */
81
+ providers: Record<string, ProviderConfig>;
82
+ /** Default provider order per network */
83
+ defaults: NetworkDefaults;
84
+ }
85
+ /**
86
+ * Provider health status
87
+ */
88
+ type ProviderStatus = 'available' | 'degraded' | 'offline' | 'stale' | 'untested' | 'testing';
89
+ /**
90
+ * Resolved provider with actual endpoint URLs (env vars replaced)
91
+ */
92
+ interface ResolvedProvider {
93
+ /** Unique provider ID */
94
+ id: string;
95
+ /** Human-readable name */
96
+ name: string;
97
+ /** Provider type */
98
+ type: ProviderType;
99
+ /** Network */
100
+ network: Network;
101
+ /** Resolved v2 endpoint URL (ready to use) */
102
+ endpointV2: string;
103
+ /** Resolved v3 endpoint URL (if available) */
104
+ endpointV3?: string;
105
+ /** Resolved v4 endpoint URL (if available) */
106
+ endpointV4?: string;
107
+ /** Resolved WebSocket URL (if available) */
108
+ endpointWs?: string;
109
+ /** API key (if separate from URL) */
110
+ apiKey?: string;
111
+ /** Requests per second limit */
112
+ rps: number;
113
+ /** Priority (lower = higher priority) */
114
+ priority: number;
115
+ /** Whether dynamic discovery is needed */
116
+ isDynamic: boolean;
117
+ }
118
+ /**
119
+ * Provider health check result
120
+ */
121
+ interface ProviderHealthResult {
122
+ /** Provider ID */
123
+ id: string;
124
+ /** Network */
125
+ network: Network;
126
+ /** Test success */
127
+ success: boolean;
128
+ /** Current status */
129
+ status: ProviderStatus;
130
+ /** Latency in milliseconds */
131
+ latencyMs: number | null;
132
+ /** Current masterchain seqno (block height) */
133
+ seqno: number | null;
134
+ /** Blocks behind the best provider (0 = up to date) */
135
+ blocksBehind: number;
136
+ /** Timestamp of last test */
137
+ lastTested: Date | null;
138
+ /** Cached endpoint URL */
139
+ cachedEndpoint?: string;
140
+ /** Error message if failed */
141
+ error?: string;
142
+ }
143
+ /**
144
+ * Provider state for runtime tracking
145
+ */
146
+ interface ProviderState {
147
+ /** Provider ID */
148
+ id: string;
149
+ /** Current health result */
150
+ health: ProviderHealthResult;
151
+ /** Current rate limit state */
152
+ rateLimit: RateLimitState;
153
+ }
154
+ /**
155
+ * Rate limit configuration
156
+ */
157
+ interface RateLimitConfig {
158
+ /** Requests per second */
159
+ rps: number;
160
+ /** Burst size (max tokens) */
161
+ burstSize: number;
162
+ /** Minimum delay between requests in ms */
163
+ minDelayMs: number;
164
+ /** Backoff multiplier on 429 errors */
165
+ backoffMultiplier: number;
166
+ /** Maximum backoff delay in ms */
167
+ maxBackoffMs: number;
168
+ }
169
+ /**
170
+ * Rate limit state for a provider
171
+ */
172
+ interface RateLimitState {
173
+ /** Available tokens */
174
+ tokens: number;
175
+ /** Last refill timestamp */
176
+ lastRefill: number;
177
+ /** Current backoff delay (0 = no backoff) */
178
+ currentBackoff: number;
179
+ /** Consecutive error count */
180
+ consecutiveErrors: number;
181
+ /** Whether a request is currently being processed */
182
+ processing: boolean;
183
+ /** Pending request resolvers */
184
+ queueLength: number;
185
+ }
186
+ /**
187
+ * Provider manager configuration options
188
+ */
189
+ interface ProviderManagerOptions {
190
+ /** @deprecated Unused - config is loaded from provider_system/rpc.json */
191
+ configPath?: string;
192
+ /** Adapter type: 'node' for Node.js, 'browser' for browser */
193
+ adapter?: 'node' | 'browser';
194
+ /** Whether to auto-initialize on first use */
195
+ autoInit?: boolean;
196
+ /** Request timeout in ms (default: 10000) */
197
+ requestTimeoutMs?: number;
198
+ /** Health check interval in ms (0 = disabled) */
199
+ healthCheckIntervalMs?: number;
200
+ /** Maximum blocks behind before marking as stale */
201
+ maxBlocksBehind?: number;
202
+ /** Custom logger (default: console) */
203
+ logger?: Logger;
204
+ }
205
+ /**
206
+ * Logger interface for custom logging
207
+ */
208
+ interface Logger {
209
+ debug: (message: string, data?: Record<string, unknown>) => void;
210
+ info: (message: string, data?: Record<string, unknown>) => void;
211
+ warn: (message: string, data?: Record<string, unknown>) => void;
212
+ error: (message: string, data?: Record<string, unknown>) => void;
213
+ }
214
+ /**
215
+ * Provider manager state
216
+ */
217
+ interface ProviderManagerState {
218
+ /** Current network */
219
+ network: Network | null;
220
+ /** Whether initialized */
221
+ initialized: boolean;
222
+ /** Whether testing is in progress */
223
+ isTesting: boolean;
224
+ /** All provider states */
225
+ providers: Map<string, ProviderState>;
226
+ /** Best provider ID per network */
227
+ bestProviderByNetwork: Map<Network, string>;
228
+ /** Manually selected provider ID (null = auto) */
229
+ selectedProviderId: string | null;
230
+ /** Whether auto-selection is enabled */
231
+ autoSelect: boolean;
232
+ /** Custom endpoint override */
233
+ customEndpoint: string | null;
234
+ }
235
+ /**
236
+ * State change listener
237
+ */
238
+ type StateListener = (state: ProviderManagerState) => void;
239
+ /**
240
+ * TON API getMasterchainInfo response
241
+ */
242
+ interface MasterchainInfo {
243
+ /** Current masterchain block seqno */
244
+ last: {
245
+ seqno: number;
246
+ workchain: number;
247
+ shard: string;
248
+ root_hash: string;
249
+ file_hash: string;
250
+ };
251
+ /** State root hash */
252
+ state_root_hash: string;
253
+ /** Init block */
254
+ init: {
255
+ workchain: number;
256
+ seqno: number;
257
+ root_hash: string;
258
+ file_hash: string;
259
+ };
260
+ }
261
+ /**
262
+ * Generic TON API response wrapper
263
+ */
264
+ interface TonApiResponse<T = unknown> {
265
+ ok: boolean;
266
+ result?: T;
267
+ error?: string;
268
+ code?: number;
269
+ }
270
+ /**
271
+ * Timeout error class
272
+ */
273
+ declare class TimeoutError extends Error {
274
+ readonly operation: string;
275
+ readonly timeoutMs: number;
276
+ constructor(operation: string, timeoutMs: number, message?: string);
277
+ }
278
+ /**
279
+ * Provider error class
280
+ */
281
+ declare class ProviderError extends Error {
282
+ readonly providerId: string;
283
+ readonly operation: string;
284
+ readonly cause?: Error | undefined;
285
+ constructor(providerId: string, operation: string, message: string, cause?: Error | undefined);
286
+ }
287
+ /**
288
+ * Rate limit error class
289
+ */
290
+ declare class RateLimitError extends Error {
291
+ readonly providerId: string;
292
+ readonly retryAfterMs?: number | undefined;
293
+ constructor(providerId: string, retryAfterMs?: number | undefined);
294
+ }
295
+ /**
296
+ * Configuration error class
297
+ */
298
+ declare class ConfigError extends Error {
299
+ constructor(message: string);
300
+ }
301
+
302
+ /**
303
+ * Unified Provider System - Configuration Schema
304
+ *
305
+ * Zod schema for validating rpc.json configuration files.
306
+ * Provides type-safe parsing and detailed error messages.
307
+ */
308
+
309
+ /**
310
+ * Network schema
311
+ */
312
+ declare const NetworkSchema: z.ZodEnum<["testnet", "mainnet"]>;
313
+ /**
314
+ * Provider type schema
315
+ */
316
+ declare const ProviderTypeSchema: z.ZodEnum<["chainstack", "quicknode", "toncenter", "orbs", "onfinality", "ankr", "getblock", "tatum", "tonhub", "custom"]>;
317
+ /**
318
+ * API version schema
319
+ */
320
+ declare const ApiVersionSchema: z.ZodEnum<["v2", "v3", "v4"]>;
321
+ /**
322
+ * Single provider configuration schema
323
+ */
324
+ declare const ProviderConfigSchema: z.ZodObject<{
325
+ name: z.ZodString;
326
+ type: z.ZodEnum<["chainstack", "quicknode", "toncenter", "orbs", "onfinality", "ankr", "getblock", "tatum", "tonhub", "custom"]>;
327
+ network: z.ZodEnum<["testnet", "mainnet"]>;
328
+ endpoints: z.ZodEffects<z.ZodObject<{
329
+ v2: z.ZodOptional<z.ZodString>;
330
+ v3: z.ZodOptional<z.ZodString>;
331
+ v4: z.ZodOptional<z.ZodString>;
332
+ ws: z.ZodOptional<z.ZodString>;
333
+ }, "strip", z.ZodTypeAny, {
334
+ v2?: string | undefined;
335
+ v3?: string | undefined;
336
+ v4?: string | undefined;
337
+ ws?: string | undefined;
338
+ }, {
339
+ v2?: string | undefined;
340
+ v3?: string | undefined;
341
+ v4?: string | undefined;
342
+ ws?: string | undefined;
343
+ }>, {
344
+ v2?: string | undefined;
345
+ v3?: string | undefined;
346
+ v4?: string | undefined;
347
+ ws?: string | undefined;
348
+ }, {
349
+ v2?: string | undefined;
350
+ v3?: string | undefined;
351
+ v4?: string | undefined;
352
+ ws?: string | undefined;
353
+ }>;
354
+ keyEnvVar: z.ZodOptional<z.ZodString>;
355
+ apiKeyEnvVar: z.ZodOptional<z.ZodString>;
356
+ rps: z.ZodDefault<z.ZodNumber>;
357
+ priority: z.ZodDefault<z.ZodNumber>;
358
+ enabled: z.ZodDefault<z.ZodBoolean>;
359
+ isDynamic: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
360
+ description: z.ZodOptional<z.ZodString>;
361
+ }, "strip", z.ZodTypeAny, {
362
+ type: "chainstack" | "quicknode" | "toncenter" | "orbs" | "onfinality" | "ankr" | "getblock" | "tatum" | "tonhub" | "custom";
363
+ name: string;
364
+ network: "testnet" | "mainnet";
365
+ endpoints: {
366
+ v2?: string | undefined;
367
+ v3?: string | undefined;
368
+ v4?: string | undefined;
369
+ ws?: string | undefined;
370
+ };
371
+ rps: number;
372
+ priority: number;
373
+ enabled: boolean;
374
+ isDynamic: boolean;
375
+ keyEnvVar?: string | undefined;
376
+ apiKeyEnvVar?: string | undefined;
377
+ description?: string | undefined;
378
+ }, {
379
+ type: "chainstack" | "quicknode" | "toncenter" | "orbs" | "onfinality" | "ankr" | "getblock" | "tatum" | "tonhub" | "custom";
380
+ name: string;
381
+ network: "testnet" | "mainnet";
382
+ endpoints: {
383
+ v2?: string | undefined;
384
+ v3?: string | undefined;
385
+ v4?: string | undefined;
386
+ ws?: string | undefined;
387
+ };
388
+ keyEnvVar?: string | undefined;
389
+ apiKeyEnvVar?: string | undefined;
390
+ rps?: number | undefined;
391
+ priority?: number | undefined;
392
+ enabled?: boolean | undefined;
393
+ isDynamic?: boolean | undefined;
394
+ description?: string | undefined;
395
+ }>;
396
+ /**
397
+ * Complete RPC configuration schema
398
+ */
399
+ declare const RpcConfigSchema: z.ZodEffects<z.ZodObject<{
400
+ $schema: z.ZodOptional<z.ZodString>;
401
+ version: z.ZodDefault<z.ZodString>;
402
+ providers: z.ZodRecord<z.ZodString, z.ZodObject<{
403
+ name: z.ZodString;
404
+ type: z.ZodEnum<["chainstack", "quicknode", "toncenter", "orbs", "onfinality", "ankr", "getblock", "tatum", "tonhub", "custom"]>;
405
+ network: z.ZodEnum<["testnet", "mainnet"]>;
406
+ endpoints: z.ZodEffects<z.ZodObject<{
407
+ v2: z.ZodOptional<z.ZodString>;
408
+ v3: z.ZodOptional<z.ZodString>;
409
+ v4: z.ZodOptional<z.ZodString>;
410
+ ws: z.ZodOptional<z.ZodString>;
411
+ }, "strip", z.ZodTypeAny, {
412
+ v2?: string | undefined;
413
+ v3?: string | undefined;
414
+ v4?: string | undefined;
415
+ ws?: string | undefined;
416
+ }, {
417
+ v2?: string | undefined;
418
+ v3?: string | undefined;
419
+ v4?: string | undefined;
420
+ ws?: string | undefined;
421
+ }>, {
422
+ v2?: string | undefined;
423
+ v3?: string | undefined;
424
+ v4?: string | undefined;
425
+ ws?: string | undefined;
426
+ }, {
427
+ v2?: string | undefined;
428
+ v3?: string | undefined;
429
+ v4?: string | undefined;
430
+ ws?: string | undefined;
431
+ }>;
432
+ keyEnvVar: z.ZodOptional<z.ZodString>;
433
+ apiKeyEnvVar: z.ZodOptional<z.ZodString>;
434
+ rps: z.ZodDefault<z.ZodNumber>;
435
+ priority: z.ZodDefault<z.ZodNumber>;
436
+ enabled: z.ZodDefault<z.ZodBoolean>;
437
+ isDynamic: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
438
+ description: z.ZodOptional<z.ZodString>;
439
+ }, "strip", z.ZodTypeAny, {
440
+ type: "chainstack" | "quicknode" | "toncenter" | "orbs" | "onfinality" | "ankr" | "getblock" | "tatum" | "tonhub" | "custom";
441
+ name: string;
442
+ network: "testnet" | "mainnet";
443
+ endpoints: {
444
+ v2?: string | undefined;
445
+ v3?: string | undefined;
446
+ v4?: string | undefined;
447
+ ws?: string | undefined;
448
+ };
449
+ rps: number;
450
+ priority: number;
451
+ enabled: boolean;
452
+ isDynamic: boolean;
453
+ keyEnvVar?: string | undefined;
454
+ apiKeyEnvVar?: string | undefined;
455
+ description?: string | undefined;
456
+ }, {
457
+ type: "chainstack" | "quicknode" | "toncenter" | "orbs" | "onfinality" | "ankr" | "getblock" | "tatum" | "tonhub" | "custom";
458
+ name: string;
459
+ network: "testnet" | "mainnet";
460
+ endpoints: {
461
+ v2?: string | undefined;
462
+ v3?: string | undefined;
463
+ v4?: string | undefined;
464
+ ws?: string | undefined;
465
+ };
466
+ keyEnvVar?: string | undefined;
467
+ apiKeyEnvVar?: string | undefined;
468
+ rps?: number | undefined;
469
+ priority?: number | undefined;
470
+ enabled?: boolean | undefined;
471
+ isDynamic?: boolean | undefined;
472
+ description?: string | undefined;
473
+ }>>;
474
+ defaults: z.ZodObject<{
475
+ testnet: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
476
+ mainnet: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
477
+ }, "strip", z.ZodTypeAny, {
478
+ testnet: string[];
479
+ mainnet: string[];
480
+ }, {
481
+ testnet?: string[] | undefined;
482
+ mainnet?: string[] | undefined;
483
+ }>;
484
+ }, "strip", z.ZodTypeAny, {
485
+ version: string;
486
+ providers: Record<string, {
487
+ type: "chainstack" | "quicknode" | "toncenter" | "orbs" | "onfinality" | "ankr" | "getblock" | "tatum" | "tonhub" | "custom";
488
+ name: string;
489
+ network: "testnet" | "mainnet";
490
+ endpoints: {
491
+ v2?: string | undefined;
492
+ v3?: string | undefined;
493
+ v4?: string | undefined;
494
+ ws?: string | undefined;
495
+ };
496
+ rps: number;
497
+ priority: number;
498
+ enabled: boolean;
499
+ isDynamic: boolean;
500
+ keyEnvVar?: string | undefined;
501
+ apiKeyEnvVar?: string | undefined;
502
+ description?: string | undefined;
503
+ }>;
504
+ defaults: {
505
+ testnet: string[];
506
+ mainnet: string[];
507
+ };
508
+ $schema?: string | undefined;
509
+ }, {
510
+ providers: Record<string, {
511
+ type: "chainstack" | "quicknode" | "toncenter" | "orbs" | "onfinality" | "ankr" | "getblock" | "tatum" | "tonhub" | "custom";
512
+ name: string;
513
+ network: "testnet" | "mainnet";
514
+ endpoints: {
515
+ v2?: string | undefined;
516
+ v3?: string | undefined;
517
+ v4?: string | undefined;
518
+ ws?: string | undefined;
519
+ };
520
+ keyEnvVar?: string | undefined;
521
+ apiKeyEnvVar?: string | undefined;
522
+ rps?: number | undefined;
523
+ priority?: number | undefined;
524
+ enabled?: boolean | undefined;
525
+ isDynamic?: boolean | undefined;
526
+ description?: string | undefined;
527
+ }>;
528
+ defaults: {
529
+ testnet?: string[] | undefined;
530
+ mainnet?: string[] | undefined;
531
+ };
532
+ $schema?: string | undefined;
533
+ version?: string | undefined;
534
+ }>, {
535
+ version: string;
536
+ providers: Record<string, {
537
+ type: "chainstack" | "quicknode" | "toncenter" | "orbs" | "onfinality" | "ankr" | "getblock" | "tatum" | "tonhub" | "custom";
538
+ name: string;
539
+ network: "testnet" | "mainnet";
540
+ endpoints: {
541
+ v2?: string | undefined;
542
+ v3?: string | undefined;
543
+ v4?: string | undefined;
544
+ ws?: string | undefined;
545
+ };
546
+ rps: number;
547
+ priority: number;
548
+ enabled: boolean;
549
+ isDynamic: boolean;
550
+ keyEnvVar?: string | undefined;
551
+ apiKeyEnvVar?: string | undefined;
552
+ description?: string | undefined;
553
+ }>;
554
+ defaults: {
555
+ testnet: string[];
556
+ mainnet: string[];
557
+ };
558
+ $schema?: string | undefined;
559
+ }, {
560
+ providers: Record<string, {
561
+ type: "chainstack" | "quicknode" | "toncenter" | "orbs" | "onfinality" | "ankr" | "getblock" | "tatum" | "tonhub" | "custom";
562
+ name: string;
563
+ network: "testnet" | "mainnet";
564
+ endpoints: {
565
+ v2?: string | undefined;
566
+ v3?: string | undefined;
567
+ v4?: string | undefined;
568
+ ws?: string | undefined;
569
+ };
570
+ keyEnvVar?: string | undefined;
571
+ apiKeyEnvVar?: string | undefined;
572
+ rps?: number | undefined;
573
+ priority?: number | undefined;
574
+ enabled?: boolean | undefined;
575
+ isDynamic?: boolean | undefined;
576
+ description?: string | undefined;
577
+ }>;
578
+ defaults: {
579
+ testnet?: string[] | undefined;
580
+ mainnet?: string[] | undefined;
581
+ };
582
+ $schema?: string | undefined;
583
+ version?: string | undefined;
584
+ }>;
585
+ /**
586
+ * Parse and validate RPC configuration
587
+ * @param data - Raw configuration data
588
+ * @returns Validated RpcConfig
589
+ * @throws ConfigError on validation failure
590
+ */
591
+ declare function parseRpcConfig(data: unknown): RpcConfig;
592
+ /**
593
+ * Validate a single provider configuration
594
+ * @param id - Provider ID
595
+ * @param data - Provider configuration data
596
+ * @returns Validated ProviderConfig
597
+ */
598
+ declare function parseProviderConfig(id: string, data: unknown): ProviderConfig;
599
+ /**
600
+ * Create a minimal valid RpcConfig for testing
601
+ */
602
+ declare function createEmptyConfig(): RpcConfig;
603
+ /**
604
+ * Merge two RPC configurations (useful for defaults + user config)
605
+ * @param base - Base configuration
606
+ * @param override - Override configuration
607
+ * @returns Merged configuration
608
+ */
609
+ declare function mergeConfigs(base: RpcConfig, override: Partial<RpcConfig>): RpcConfig;
610
+ /**
611
+ * Type guard for Network
612
+ */
613
+ declare function isNetwork(value: unknown): value is Network;
614
+ /**
615
+ * Type guard for ProviderType
616
+ */
617
+ declare function isProviderType(value: unknown): value is ProviderType;
618
+ /**
619
+ * Type guard for ApiVersion
620
+ */
621
+ declare function isApiVersion(value: unknown): value is ApiVersion;
622
+
623
+ /**
624
+ * Unified Provider System - Configuration Parser
625
+ *
626
+ * Loads provider definitions from provider_system/rpc.json.
627
+ * Resolves API keys from environment variables (.env).
628
+ * Supports both Node.js (file system) and browser (fetch/embedded) environments.
629
+ */
630
+
631
+ /**
632
+ * Get environment variable value.
633
+ * Works in both Node.js and browser environments.
634
+ */
635
+ declare function getEnvVar(name: string): string | undefined;
636
+ /**
637
+ * Resolve {key} placeholder in URL with environment variable value
638
+ */
639
+ declare function resolveKeyPlaceholder(url: string, keyEnvVar?: string): string;
640
+ /**
641
+ * Resolve all placeholders in endpoint URLs
642
+ */
643
+ declare function resolveEndpoints(endpoints: ProviderConfig['endpoints'], keyEnvVar?: string): {
644
+ v2?: string;
645
+ v3?: string;
646
+ v4?: string;
647
+ ws?: string;
648
+ };
649
+ /**
650
+ * Convert a ProviderConfig to a ResolvedProvider with actual URLs
651
+ */
652
+ declare function resolveProvider(id: string, config: ProviderConfig): ResolvedProvider | null;
653
+ /**
654
+ * Resolve all providers from config
655
+ */
656
+ declare function resolveAllProviders(config: RpcConfig): ResolvedProvider[];
657
+ /**
658
+ * Get providers for a specific network
659
+ */
660
+ declare function getProvidersForNetwork(config: RpcConfig, network: Network): ResolvedProvider[];
661
+ /**
662
+ * Get providers in default order for a network
663
+ */
664
+ declare function getDefaultProvidersForNetwork(config: RpcConfig, network: Network): ResolvedProvider[];
665
+ /**
666
+ * Load RPC config from the built-in rpc.json file (Node.js)
667
+ */
668
+ declare function loadBuiltinConfig(): Promise<RpcConfig>;
669
+ /**
670
+ * Load RPC config from a URL (browser-compatible)
671
+ */
672
+ declare function loadConfigFromUrl(url: string): Promise<RpcConfig>;
673
+ /**
674
+ * Load RPC config from raw JSON data
675
+ */
676
+ declare function loadConfigFromData(data: unknown): RpcConfig;
677
+ /**
678
+ * Auto-detect and load config.
679
+ * - Browser: checks for embedded __RPC_CONFIG__ or fetches from URL
680
+ * - Node.js: loads from provider_system/rpc.json
681
+ */
682
+ declare function loadConfig(): Promise<RpcConfig>;
683
+ /**
684
+ * Minimal default providers when rpc.json is not available.
685
+ * These are free public endpoints that don't require API keys.
686
+ */
687
+ declare const DEFAULT_PROVIDERS: Record<string, ProviderConfig>;
688
+ /**
689
+ * Create a default config with minimal providers (no API keys required)
690
+ */
691
+ declare function createDefaultConfig(): RpcConfig;
692
+ /**
693
+ * Merge user config with defaults
694
+ */
695
+ declare function mergeWithDefaults(config: RpcConfig): RpcConfig;
696
+
697
+ /**
698
+ * Unified Provider System - Provider Registry
699
+ *
700
+ * Manages provider definitions, filtering, and lookup.
701
+ * Acts as a central repository for all available providers.
702
+ */
703
+
704
+ /**
705
+ * Provider Registry
706
+ *
707
+ * Manages all provider definitions and provides lookup/filtering capabilities.
708
+ */
709
+ declare class ProviderRegistry {
710
+ private config;
711
+ private providers;
712
+ private logger;
713
+ constructor(config?: RpcConfig, logger?: Logger);
714
+ /**
715
+ * Load and resolve all providers from config
716
+ */
717
+ private loadProviders;
718
+ /**
719
+ * Get a provider by ID
720
+ */
721
+ getProvider(id: string): ResolvedProvider | undefined;
722
+ /**
723
+ * Get all providers
724
+ */
725
+ getAllProviders(): ResolvedProvider[];
726
+ /**
727
+ * Get providers for a specific network
728
+ */
729
+ getProvidersForNetwork(network: Network): ResolvedProvider[];
730
+ /**
731
+ * Get providers in default order for a network
732
+ */
733
+ getDefaultOrderForNetwork(network: Network): ResolvedProvider[];
734
+ /**
735
+ * Get providers by type
736
+ */
737
+ getProvidersByType(type: ProviderType): ResolvedProvider[];
738
+ /**
739
+ * Get providers that have v2 API endpoints
740
+ */
741
+ getV2Providers(): ResolvedProvider[];
742
+ /**
743
+ * Get v2 providers for a specific network
744
+ */
745
+ getV2ProvidersForNetwork(network: Network): ResolvedProvider[];
746
+ /**
747
+ * Check if a provider exists
748
+ */
749
+ hasProvider(id: string): boolean;
750
+ /**
751
+ * Get provider count
752
+ */
753
+ get size(): number;
754
+ /**
755
+ * Get the underlying config
756
+ */
757
+ getConfig(): RpcConfig;
758
+ /**
759
+ * Update config and reload providers
760
+ */
761
+ updateConfig(config: RpcConfig): void;
762
+ /**
763
+ * Add or update a provider at runtime
764
+ */
765
+ setProvider(id: string, provider: ResolvedProvider): void;
766
+ /**
767
+ * Remove a provider
768
+ */
769
+ removeProvider(id: string): boolean;
770
+ /**
771
+ * Get provider IDs
772
+ */
773
+ getProviderIds(): string[];
774
+ /**
775
+ * Get network default provider IDs
776
+ */
777
+ getDefaultProviderIds(network: Network): string[];
778
+ /**
779
+ * Find provider by endpoint URL (useful for error reporting)
780
+ */
781
+ findProviderByEndpoint(endpoint: string): ResolvedProvider | undefined;
782
+ }
783
+ /**
784
+ * Create a registry by loading from provider_system/rpc.json
785
+ */
786
+ declare function createRegistry(logger?: Logger): Promise<ProviderRegistry>;
787
+ /**
788
+ * @deprecated Use createRegistry() instead
789
+ */
790
+ declare function createRegistryFromFile(_filePath?: string, logger?: Logger): Promise<ProviderRegistry>;
791
+ /**
792
+ * Create a registry with default providers only
793
+ */
794
+ declare function createDefaultRegistry(logger?: Logger): ProviderRegistry;
795
+ /**
796
+ * Create a registry from raw config data
797
+ */
798
+ declare function createRegistryFromData(data: RpcConfig, logger?: Logger): ProviderRegistry;
799
+
800
+ /**
801
+ * Unified Provider System - Health Checker
802
+ *
803
+ * Tests provider connectivity, measures latency, and compares block heights.
804
+ * Identifies stale, degraded, or offline providers.
805
+ */
806
+
807
+ interface HealthCheckConfig {
808
+ /** Request timeout in milliseconds */
809
+ timeoutMs: number;
810
+ /** Maximum blocks behind before marking as stale */
811
+ maxBlocksBehind: number;
812
+ /** Latency threshold (ms) for degraded status */
813
+ degradedLatencyMs: number;
814
+ }
815
+ /**
816
+ * Health Checker
817
+ *
818
+ * Tests provider health by calling getMasterchainInfo and measuring
819
+ * latency and block height.
820
+ */
821
+ declare class HealthChecker {
822
+ private config;
823
+ private logger;
824
+ private results;
825
+ private highestSeqno;
826
+ constructor(config?: Partial<HealthCheckConfig>, logger?: Logger);
827
+ /**
828
+ * Test a single provider's health
829
+ */
830
+ testProvider(provider: ResolvedProvider): Promise<ProviderHealthResult>;
831
+ /**
832
+ * Test multiple providers in parallel with staggered batches
833
+ */
834
+ testProviders(providers: ResolvedProvider[], batchSize?: number, batchDelayMs?: number): Promise<ProviderHealthResult[]>;
835
+ /**
836
+ * Get the last health result for a provider
837
+ */
838
+ getResult(providerId: string, network: Network): ProviderHealthResult | undefined;
839
+ /**
840
+ * Get all results for a network
841
+ */
842
+ getResultsForNetwork(network: Network): ProviderHealthResult[];
843
+ /**
844
+ * Get available providers for a network (status = available or degraded)
845
+ */
846
+ getAvailableProviders(network: Network): ProviderHealthResult[];
847
+ /**
848
+ * Get the best provider for a network (lowest latency among available)
849
+ */
850
+ getBestProvider(network: Network): ProviderHealthResult | undefined;
851
+ /**
852
+ * Get highest known seqno for a network
853
+ */
854
+ getHighestSeqno(network: Network): number;
855
+ /**
856
+ * Clear all results
857
+ */
858
+ clearResults(): void;
859
+ /**
860
+ * Mark a provider as degraded (e.g., on 429 error)
861
+ */
862
+ markDegraded(providerId: string, network: Network, error?: string): void;
863
+ /**
864
+ * Mark a provider as offline
865
+ */
866
+ markOffline(providerId: string, network: Network, error?: string): void;
867
+ private getResultKey;
868
+ /**
869
+ * Get endpoint URL for a provider (handles dynamic providers like Orbs)
870
+ */
871
+ private getEndpoint;
872
+ /**
873
+ * Call getMasterchainInfo API
874
+ */
875
+ private callGetMasterchainInfo;
876
+ private sleep;
877
+ }
878
+ /**
879
+ * Create a health checker with default configuration
880
+ */
881
+ declare function createHealthChecker(config?: Partial<HealthCheckConfig>, logger?: Logger): HealthChecker;
882
+
883
+ /**
884
+ * Unified Provider System - Rate Limiter
885
+ *
886
+ * Token bucket rate limiter with per-provider tracking.
887
+ * Implements request queuing, serialization, and exponential backoff.
888
+ */
889
+
890
+ /**
891
+ * Default rate limit config (conservative for public endpoints)
892
+ */
893
+ declare const DEFAULT_RATE_LIMIT: RateLimitConfig;
894
+ /**
895
+ * Chainstack free plan limits (25 RPS)
896
+ */
897
+ declare const CHAINSTACK_RATE_LIMIT: RateLimitConfig;
898
+ /**
899
+ * QuickNode free plan limits (10 RPS)
900
+ */
901
+ declare const QUICKNODE_RATE_LIMIT: RateLimitConfig;
902
+ /**
903
+ * Orbs TON Access (decentralized, no hard limit)
904
+ */
905
+ declare const ORBS_RATE_LIMIT: RateLimitConfig;
906
+ /**
907
+ * Get rate limit config by provider type
908
+ */
909
+ declare function getRateLimitForType(type: string): RateLimitConfig;
910
+ /**
911
+ * Token Bucket Rate Limiter
912
+ *
913
+ * Implements a token bucket algorithm with:
914
+ * - Configurable RPS and burst size
915
+ * - Request queuing (FIFO)
916
+ * - Serialized request processing
917
+ * - Exponential backoff on 429 errors
918
+ */
919
+ declare class TokenBucketRateLimiter {
920
+ private config;
921
+ private tokens;
922
+ private lastRefill;
923
+ private currentBackoff;
924
+ private consecutiveErrors;
925
+ private requestQueue;
926
+ private processing;
927
+ private logger;
928
+ constructor(config?: Partial<RateLimitConfig>, logger?: Logger);
929
+ /**
930
+ * Get current state
931
+ */
932
+ getState(): RateLimitState;
933
+ /**
934
+ * Acquire a token (wait if necessary)
935
+ *
936
+ * @param timeoutMs - Maximum time to wait for a token (default: 60s)
937
+ * @returns true if token acquired, false if timeout
938
+ */
939
+ acquire(timeoutMs?: number): Promise<boolean>;
940
+ /**
941
+ * Release a token (call on request completion)
942
+ */
943
+ release(): void;
944
+ /**
945
+ * Report a successful request (resets backoff)
946
+ */
947
+ reportSuccess(): void;
948
+ /**
949
+ * Report a rate limit error (applies backoff)
950
+ */
951
+ reportRateLimitError(): void;
952
+ /**
953
+ * Report a general error
954
+ */
955
+ reportError(): void;
956
+ /**
957
+ * Reset rate limiter state
958
+ */
959
+ reset(): void;
960
+ /**
961
+ * Update configuration
962
+ */
963
+ updateConfig(config: Partial<RateLimitConfig>): void;
964
+ /**
965
+ * Refill tokens based on time elapsed
966
+ */
967
+ private refill;
968
+ }
969
+ /**
970
+ * Provider Rate Limiter Manager
971
+ *
972
+ * Manages rate limiters for multiple providers.
973
+ */
974
+ declare class RateLimiterManager {
975
+ private limiters;
976
+ private configs;
977
+ private logger;
978
+ constructor(logger?: Logger);
979
+ /**
980
+ * Get or create rate limiter for a provider
981
+ */
982
+ getLimiter(providerId: string, config?: Partial<RateLimitConfig>): TokenBucketRateLimiter;
983
+ /**
984
+ * Set rate limit config for a provider
985
+ */
986
+ setConfig(providerId: string, config: RateLimitConfig): void;
987
+ /**
988
+ * Get rate limit state for a provider
989
+ */
990
+ getState(providerId: string): RateLimitState | null;
991
+ /**
992
+ * Acquire token for a provider
993
+ */
994
+ acquire(providerId: string, timeoutMs?: number): Promise<boolean>;
995
+ /**
996
+ * Report success for a provider
997
+ */
998
+ reportSuccess(providerId: string): void;
999
+ /**
1000
+ * Report rate limit error for a provider
1001
+ */
1002
+ reportRateLimitError(providerId: string): void;
1003
+ /**
1004
+ * Report general error for a provider
1005
+ */
1006
+ reportError(providerId: string): void;
1007
+ /**
1008
+ * Reset a provider's rate limiter
1009
+ */
1010
+ reset(providerId: string): void;
1011
+ /**
1012
+ * Reset all rate limiters
1013
+ */
1014
+ resetAll(): void;
1015
+ /**
1016
+ * Remove a provider's rate limiter
1017
+ */
1018
+ remove(providerId: string): void;
1019
+ /**
1020
+ * Clear all limiters
1021
+ */
1022
+ clear(): void;
1023
+ }
1024
+ /**
1025
+ * Create a rate limiter with RPS-based config
1026
+ */
1027
+ declare function createRateLimiter(rps: number, logger?: Logger): TokenBucketRateLimiter;
1028
+ /**
1029
+ * Create a rate limiter manager
1030
+ */
1031
+ declare function createRateLimiterManager(logger?: Logger): RateLimiterManager;
1032
+
1033
+ /**
1034
+ * Unified Provider System - Provider Selector
1035
+ *
1036
+ * Selects the best available provider based on health, latency, and priority.
1037
+ * Supports auto-selection, manual override, and custom endpoint.
1038
+ */
1039
+
1040
+ interface SelectionConfig {
1041
+ /** Prefer providers with latency below this threshold (ms) */
1042
+ preferredLatencyMs: number;
1043
+ /** Weight for latency in scoring (0-1) */
1044
+ latencyWeight: number;
1045
+ /** Weight for priority in scoring (0-1) */
1046
+ priorityWeight: number;
1047
+ /** Weight for block freshness in scoring (0-1) */
1048
+ freshnessWeight: number;
1049
+ /** Minimum acceptable provider status */
1050
+ minStatus: ProviderStatus[];
1051
+ }
1052
+ /**
1053
+ * Provider Selector
1054
+ *
1055
+ * Selects the best provider based on multiple criteria:
1056
+ * - Health status (available > degraded > offline)
1057
+ * - Latency (lower is better)
1058
+ * - Priority (from config, lower is higher priority)
1059
+ * - Block freshness (fewer blocks behind is better)
1060
+ */
1061
+ declare class ProviderSelector {
1062
+ private registry;
1063
+ private healthChecker;
1064
+ private config;
1065
+ private logger;
1066
+ private selectedProviderId;
1067
+ private autoSelect;
1068
+ private customEndpoint;
1069
+ private bestProviderByNetwork;
1070
+ constructor(registry: ProviderRegistry, healthChecker: HealthChecker, config?: Partial<SelectionConfig>, logger?: Logger);
1071
+ /**
1072
+ * Get the best provider for a network
1073
+ */
1074
+ getBestProvider(network: Network): ResolvedProvider | null;
1075
+ /**
1076
+ * Find the best provider for a network (recalculates)
1077
+ */
1078
+ findBestProvider(network: Network): ResolvedProvider | null;
1079
+ /**
1080
+ * Get all available providers for a network, sorted by score
1081
+ */
1082
+ getAvailableProviders(network: Network): ResolvedProvider[];
1083
+ /**
1084
+ * Get the next best provider (for failover)
1085
+ */
1086
+ getNextProvider(network: Network, excludeIds: string[]): ResolvedProvider | null;
1087
+ /**
1088
+ * Calculate a score for a provider (higher is better)
1089
+ */
1090
+ private scoreProvider;
1091
+ private getStatusScore;
1092
+ private getLatencyScore;
1093
+ private getPriorityScore;
1094
+ private getFreshnessScore;
1095
+ /**
1096
+ * Set manual provider selection
1097
+ */
1098
+ setSelectedProvider(providerId: string | null): void;
1099
+ /**
1100
+ * Get currently selected provider ID
1101
+ */
1102
+ getSelectedProviderId(): string | null;
1103
+ /**
1104
+ * Enable/disable auto-selection
1105
+ */
1106
+ setAutoSelect(enabled: boolean): void;
1107
+ /**
1108
+ * Check if auto-selection is enabled
1109
+ */
1110
+ isAutoSelectEnabled(): boolean;
1111
+ /**
1112
+ * Set custom endpoint override
1113
+ */
1114
+ setCustomEndpoint(endpoint: string | null): void;
1115
+ /**
1116
+ * Get custom endpoint
1117
+ */
1118
+ getCustomEndpoint(): string | null;
1119
+ /**
1120
+ * Check if using custom endpoint
1121
+ */
1122
+ isUsingCustomEndpoint(): boolean;
1123
+ /**
1124
+ * Clear cached best providers (forces recalculation)
1125
+ */
1126
+ clearCache(): void;
1127
+ /**
1128
+ * Update best provider after health check
1129
+ */
1130
+ updateBestProvider(network: Network): void;
1131
+ /**
1132
+ * Handle provider failure (switch to next best)
1133
+ */
1134
+ handleProviderFailure(providerId: string, network: Network): ResolvedProvider | null;
1135
+ /**
1136
+ * Get active provider info
1137
+ */
1138
+ getActiveProviderInfo(network: Network): {
1139
+ id: string;
1140
+ name: string;
1141
+ isCustom: boolean;
1142
+ } | null;
1143
+ /**
1144
+ * Create a pseudo-provider for custom endpoint
1145
+ */
1146
+ private createCustomProvider;
1147
+ }
1148
+ /**
1149
+ * Create a provider selector
1150
+ */
1151
+ declare function createSelector(registry: ProviderRegistry, healthChecker: HealthChecker, config?: Partial<SelectionConfig>, logger?: Logger): ProviderSelector;
1152
+
1153
+ /**
1154
+ * Unified Provider System - Provider Manager
1155
+ *
1156
+ * Main entry point for the provider system.
1157
+ * Coordinates registry, health checker, rate limiter, and selector.
1158
+ */
1159
+
1160
+ /**
1161
+ * Provider Manager
1162
+ *
1163
+ * Main entry point for the unified provider system.
1164
+ * Manages providers, health checks, rate limiting, and selection.
1165
+ *
1166
+ * Usage:
1167
+ * ```typescript
1168
+ * // Singleton pattern (Node.js)
1169
+ * const pm = ProviderManager.getInstance();
1170
+ * await pm.init('testnet');
1171
+ * const endpoint = await pm.getEndpoint();
1172
+ *
1173
+ * // Instance pattern (Browser/React)
1174
+ * const pm = new ProviderManager({ adapter: 'browser' });
1175
+ * await pm.init(network);
1176
+ * ```
1177
+ */
1178
+ declare class ProviderManager {
1179
+ private static instance;
1180
+ private registry;
1181
+ private healthChecker;
1182
+ private rateLimiter;
1183
+ private selector;
1184
+ private options;
1185
+ private network;
1186
+ private initialized;
1187
+ private isTesting;
1188
+ private healthCheckInterval;
1189
+ private listeners;
1190
+ constructor(options?: ProviderManagerOptions);
1191
+ /**
1192
+ * Get singleton instance (recommended for Node.js)
1193
+ */
1194
+ static getInstance(options?: ProviderManagerOptions): ProviderManager;
1195
+ /**
1196
+ * Reset singleton instance (for testing)
1197
+ */
1198
+ static resetInstance(): void;
1199
+ /**
1200
+ * Initialize the provider manager
1201
+ *
1202
+ * @param network - Network to initialize for
1203
+ * @param testProviders - Whether to test providers immediately (default: true)
1204
+ */
1205
+ init(network: Network, testProviders?: boolean): Promise<void>;
1206
+ /**
1207
+ * Check if manager is initialized
1208
+ */
1209
+ isInitialized(): boolean;
1210
+ /**
1211
+ * Destroy the manager (cleanup)
1212
+ */
1213
+ destroy(): void;
1214
+ /**
1215
+ * Test all providers for current network
1216
+ */
1217
+ testAllProviders(): Promise<ProviderHealthResult[]>;
1218
+ /**
1219
+ * Test a specific provider
1220
+ */
1221
+ testProvider(providerId: string): Promise<ProviderHealthResult | null>;
1222
+ /**
1223
+ * Check if testing is in progress
1224
+ */
1225
+ isTestingProviders(): boolean;
1226
+ /**
1227
+ * Get endpoint URL for current network
1228
+ *
1229
+ * Handles: custom endpoint > manual selection > auto-selection > fallback
1230
+ */
1231
+ getEndpoint(): Promise<string>;
1232
+ /**
1233
+ * Get endpoint with rate limiting
1234
+ *
1235
+ * Waits for rate limit token before returning endpoint.
1236
+ */
1237
+ getEndpointWithRateLimit(timeoutMs?: number): Promise<string>;
1238
+ /**
1239
+ * Get current active provider
1240
+ */
1241
+ getActiveProvider(): ResolvedProvider | null;
1242
+ /**
1243
+ * Get active provider info
1244
+ */
1245
+ getActiveProviderInfo(): {
1246
+ id: string;
1247
+ name: string;
1248
+ isCustom: boolean;
1249
+ } | null;
1250
+ /**
1251
+ * Report a successful request
1252
+ */
1253
+ reportSuccess(): void;
1254
+ /**
1255
+ * Report an error (triggers provider switch if needed)
1256
+ */
1257
+ reportError(error: Error | string): void;
1258
+ /**
1259
+ * Set manual provider selection
1260
+ */
1261
+ setSelectedProvider(providerId: string | null): void;
1262
+ /**
1263
+ * Get selected provider ID
1264
+ */
1265
+ getSelectedProviderId(): string | null;
1266
+ /**
1267
+ * Set auto-select mode
1268
+ */
1269
+ setAutoSelect(enabled: boolean): void;
1270
+ /**
1271
+ * Check if auto-select is enabled
1272
+ */
1273
+ isAutoSelectEnabled(): boolean;
1274
+ /**
1275
+ * Set custom endpoint override
1276
+ */
1277
+ setCustomEndpoint(endpoint: string | null): void;
1278
+ /**
1279
+ * Get custom endpoint
1280
+ */
1281
+ getCustomEndpoint(): string | null;
1282
+ /**
1283
+ * Check if using custom endpoint
1284
+ */
1285
+ isUsingCustomEndpoint(): boolean;
1286
+ /**
1287
+ * Get current network
1288
+ */
1289
+ getNetwork(): Network | null;
1290
+ /**
1291
+ * Get all providers for current network
1292
+ */
1293
+ getProviders(): ResolvedProvider[];
1294
+ /**
1295
+ * Get provider health results for current network
1296
+ */
1297
+ getProviderHealthResults(): ProviderHealthResult[];
1298
+ /**
1299
+ * Get registry (for advanced usage)
1300
+ */
1301
+ getRegistry(): ProviderRegistry | null;
1302
+ /**
1303
+ * Get health checker (for advanced usage)
1304
+ */
1305
+ getHealthChecker(): HealthChecker | null;
1306
+ /**
1307
+ * Get rate limiter manager (for advanced usage)
1308
+ */
1309
+ getRateLimiter(): RateLimiterManager | null;
1310
+ /**
1311
+ * Get current state (for UI)
1312
+ */
1313
+ getState(): ProviderManagerState;
1314
+ /**
1315
+ * Subscribe to state changes
1316
+ */
1317
+ subscribe(listener: StateListener): () => void;
1318
+ /**
1319
+ * Notify all listeners
1320
+ */
1321
+ private notifyListeners;
1322
+ private ensureInitialized;
1323
+ private getFallbackEndpoint;
1324
+ private startHealthCheckInterval;
1325
+ private stopHealthCheckInterval;
1326
+ }
1327
+ /**
1328
+ * Create a new ProviderManager instance
1329
+ */
1330
+ declare function createProviderManager(options?: ProviderManagerOptions): ProviderManager;
1331
+ /**
1332
+ * Get singleton ProviderManager instance
1333
+ */
1334
+ declare function getProviderManager(options?: ProviderManagerOptions): ProviderManager;
1335
+
1336
+ /**
1337
+ * Unified Provider System - Node.js Adapter
1338
+ *
1339
+ * Provides TonClient integration for Node.js environments.
1340
+ * Handles client caching and endpoint changes.
1341
+ */
1342
+
1343
+ /**
1344
+ * Node.js Adapter for Provider System
1345
+ *
1346
+ * Provides TonClient and direct REST API access for Node.js environments.
1347
+ */
1348
+ declare class NodeAdapter {
1349
+ private manager;
1350
+ private logger;
1351
+ constructor(manager: ProviderManager, logger?: Logger);
1352
+ /**
1353
+ * Get TonClient instance
1354
+ *
1355
+ * Creates a new client if endpoint changed, otherwise returns cached.
1356
+ */
1357
+ getClient(): Promise<TonClient>;
1358
+ /**
1359
+ * Reset client cache (forces new client creation)
1360
+ */
1361
+ resetClient(): void;
1362
+ /**
1363
+ * Get cached client info (for debugging)
1364
+ */
1365
+ getClientInfo(): {
1366
+ endpoint: string;
1367
+ network: Network;
1368
+ age: number;
1369
+ } | null;
1370
+ /**
1371
+ * Get address state via REST API
1372
+ */
1373
+ getAddressState(address: Address | string, timeoutMs?: number): Promise<'uninit' | 'active' | 'frozen'>;
1374
+ /**
1375
+ * Get address balance via REST API
1376
+ */
1377
+ getAddressBalance(address: Address | string, timeoutMs?: number): Promise<bigint>;
1378
+ /**
1379
+ * Run a get method via REST API
1380
+ */
1381
+ runGetMethod(address: Address | string, method: string, stack?: unknown[], timeoutMs?: number): Promise<{
1382
+ exit_code: number;
1383
+ stack: unknown[];
1384
+ }>;
1385
+ /**
1386
+ * Send BOC via REST API
1387
+ */
1388
+ sendBoc(boc: Buffer | string, timeoutMs?: number): Promise<void>;
1389
+ /**
1390
+ * Check if contract is deployed
1391
+ */
1392
+ isContractDeployed(address: Address | string, timeoutMs?: number): Promise<boolean>;
1393
+ /**
1394
+ * Unwrap TON API response
1395
+ */
1396
+ private unwrapResponse;
1397
+ }
1398
+ /**
1399
+ * Create a Node adapter
1400
+ */
1401
+ declare function createNodeAdapter(manager: ProviderManager, logger?: Logger): NodeAdapter;
1402
+ /**
1403
+ * Get TonClient from ProviderManager (convenience function)
1404
+ */
1405
+ declare function getTonClient(manager: ProviderManager): Promise<TonClient>;
1406
+ /**
1407
+ * Get TonClient for network (one-shot convenience)
1408
+ */
1409
+ declare function getTonClientForNetwork(network: Network, configPath?: string): Promise<TonClient>;
1410
+ /**
1411
+ * Reset all cached state
1412
+ */
1413
+ declare function resetNodeAdapter(): void;
1414
+
1415
+ /**
1416
+ * Unified Provider System - Browser Adapter
1417
+ *
1418
+ * Provides browser-compatible TON client functionality.
1419
+ * Designed for use in React/Next.js applications.
1420
+ */
1421
+
1422
+ /**
1423
+ * Browser Adapter for Provider System
1424
+ *
1425
+ * Provides fetch-based TON API access for browser environments.
1426
+ * Compatible with React, Next.js, and other browser frameworks.
1427
+ *
1428
+ * Note: TonClient from @ton/ton works in browser but requires polyfills.
1429
+ * This adapter provides a lighter alternative using fetch directly.
1430
+ */
1431
+ declare class BrowserAdapter {
1432
+ private manager;
1433
+ private logger;
1434
+ constructor(manager: ProviderManager, logger?: Logger);
1435
+ /**
1436
+ * Get current endpoint URL
1437
+ */
1438
+ getEndpoint(): Promise<string>;
1439
+ /**
1440
+ * Get endpoint with rate limiting
1441
+ */
1442
+ getEndpointWithRateLimit(timeoutMs?: number): Promise<string>;
1443
+ /**
1444
+ * Make a JSON-RPC call to the TON API
1445
+ */
1446
+ jsonRpc<T = unknown>(method: string, params?: Record<string, unknown>, timeoutMs?: number): Promise<T>;
1447
+ /**
1448
+ * Get address state
1449
+ */
1450
+ getAddressState(address: string, timeoutMs?: number): Promise<'uninit' | 'active' | 'frozen'>;
1451
+ /**
1452
+ * Get address balance
1453
+ */
1454
+ getAddressBalance(address: string, timeoutMs?: number): Promise<bigint>;
1455
+ /**
1456
+ * Get address information
1457
+ */
1458
+ getAddressInfo(address: string, timeoutMs?: number): Promise<{
1459
+ state: 'uninit' | 'active' | 'frozen';
1460
+ balance: bigint;
1461
+ lastTransactionLt?: string;
1462
+ lastTransactionHash?: string;
1463
+ }>;
1464
+ /**
1465
+ * Run get method
1466
+ */
1467
+ runGetMethod(address: string, method: string, stack?: unknown[], timeoutMs?: number): Promise<{
1468
+ exit_code: number;
1469
+ stack: unknown[];
1470
+ }>;
1471
+ /**
1472
+ * Get masterchain info
1473
+ */
1474
+ getMasterchainInfo(timeoutMs?: number): Promise<{
1475
+ seqno: number;
1476
+ stateRootHash: string;
1477
+ }>;
1478
+ /**
1479
+ * Get provider manager
1480
+ */
1481
+ getManager(): ProviderManager;
1482
+ /**
1483
+ * Get active provider info
1484
+ */
1485
+ getActiveProviderInfo(): {
1486
+ id: string;
1487
+ name: string;
1488
+ isCustom: boolean;
1489
+ } | null;
1490
+ /**
1491
+ * Get provider health results
1492
+ */
1493
+ getProviderHealthResults(): ProviderHealthResult[];
1494
+ /**
1495
+ * Test all providers
1496
+ */
1497
+ testAllProviders(): Promise<ProviderHealthResult[]>;
1498
+ /**
1499
+ * Unwrap TON API response
1500
+ */
1501
+ private unwrapResponse;
1502
+ }
1503
+ /**
1504
+ * Create a Browser adapter
1505
+ */
1506
+ declare function createBrowserAdapter(manager: ProviderManager, logger?: Logger): BrowserAdapter;
1507
+ /**
1508
+ * Create a Browser adapter with auto-initialized manager
1509
+ */
1510
+ declare function createBrowserAdapterForNetwork(network: Network, configPath?: string, logger?: Logger): Promise<BrowserAdapter>;
1511
+
1512
+ /**
1513
+ * Unified Provider System - Endpoint Utilities
1514
+ *
1515
+ * URL normalization and manipulation for TON RPC endpoints.
1516
+ */
1517
+ /**
1518
+ * Normalize endpoint URL for TonClient v2 API.
1519
+ * Ensures the endpoint has /jsonRPC suffix for JSON-RPC POST requests.
1520
+ *
1521
+ * Different providers have different endpoint formats:
1522
+ * - toncenter.com: POST to /api/v2/jsonRPC
1523
+ * - Chainstack: POST to /api/v2/jsonRPC (needs /jsonRPC suffix!)
1524
+ * - TON Access (orbs): Already returns correct JSON-RPC endpoint
1525
+ * - QuickNode: Usually needs /jsonRPC appended
1526
+ */
1527
+ declare function normalizeV2Endpoint(endpoint: string): string;
1528
+ /**
1529
+ * Convert any endpoint to v2 base URL (without /jsonRPC suffix).
1530
+ */
1531
+ declare function toV2Base(endpoint: string): string;
1532
+ /**
1533
+ * Convert any endpoint to v3 base URL.
1534
+ */
1535
+ declare function toV3Base(endpoint: string): string;
1536
+ /**
1537
+ * Extract the base URL (protocol + host) from an endpoint.
1538
+ */
1539
+ declare function getBaseUrl(endpoint: string): string;
1540
+ /**
1541
+ * Check if an endpoint is a Chainstack URL.
1542
+ */
1543
+ declare function isChainstackUrl(url: string): boolean;
1544
+ /**
1545
+ * Check if an endpoint is a QuickNode URL.
1546
+ */
1547
+ declare function isQuickNodeUrl(url: string): boolean;
1548
+ /**
1549
+ * Check if an endpoint is a TonCenter URL.
1550
+ */
1551
+ declare function isTonCenterUrl(url: string): boolean;
1552
+ /**
1553
+ * Check if an endpoint is an Orbs URL.
1554
+ */
1555
+ declare function isOrbsUrl(url: string): boolean;
1556
+ /**
1557
+ * Build a full endpoint URL for a specific API method (REST style).
1558
+ */
1559
+ declare function buildRestUrl(baseEndpoint: string, method: string): string;
1560
+ /**
1561
+ * Build URL for getAddressState call.
1562
+ */
1563
+ declare function buildGetAddressStateUrl(baseEndpoint: string, address: string): string;
1564
+ /**
1565
+ * Build URL for getAddressBalance call.
1566
+ */
1567
+ declare function buildGetAddressBalanceUrl(baseEndpoint: string, address: string): string;
1568
+ /**
1569
+ * Build URL for getAddressInformation call.
1570
+ */
1571
+ declare function buildGetAddressInfoUrl(baseEndpoint: string, address: string): string;
1572
+ /**
1573
+ * Detect network from endpoint URL.
1574
+ */
1575
+ declare function detectNetworkFromEndpoint(endpoint: string): 'testnet' | 'mainnet' | null;
1576
+ /**
1577
+ * Validate that a string is a valid HTTP(S) URL.
1578
+ */
1579
+ declare function isValidHttpUrl(str: string): boolean;
1580
+ /**
1581
+ * Validate that a string is a valid WebSocket URL.
1582
+ */
1583
+ declare function isValidWsUrl(str: string): boolean;
1584
+
1585
+ /**
1586
+ * Unified Provider System - Timeout Utilities
1587
+ *
1588
+ * Promise timeout helpers for async operations.
1589
+ */
1590
+
1591
+ /** Default timeout for TON provider requests */
1592
+ declare const DEFAULT_PROVIDER_TIMEOUT_MS = 30000;
1593
+ /** Default timeout for contract calls */
1594
+ declare const DEFAULT_CONTRACT_TIMEOUT_MS = 45000;
1595
+ /** Default timeout for health checks */
1596
+ declare const DEFAULT_HEALTH_CHECK_TIMEOUT_MS = 10000;
1597
+ /**
1598
+ * Execute a promise with a timeout.
1599
+ *
1600
+ * @param promise - The promise to execute
1601
+ * @param timeoutMs - Timeout in milliseconds
1602
+ * @param operationName - Name of the operation (for error messages)
1603
+ * @returns The result of the promise
1604
+ * @throws TimeoutError if the operation times out
1605
+ */
1606
+ declare function withTimeout<T>(promise: Promise<T>, timeoutMs: number, operationName: string): Promise<T>;
1607
+ /**
1608
+ * Execute a function with a timeout.
1609
+ *
1610
+ * @param fn - The async function to execute
1611
+ * @param timeoutMs - Timeout in milliseconds
1612
+ * @param operationName - Name of the operation (for error messages)
1613
+ * @returns The result of the function
1614
+ * @throws TimeoutError if the operation times out
1615
+ */
1616
+ declare function withTimeoutFn<T>(fn: () => Promise<T>, timeoutMs: number, operationName: string): Promise<T>;
1617
+ /**
1618
+ * Create an AbortController with automatic timeout.
1619
+ *
1620
+ * @param timeoutMs - Timeout in milliseconds
1621
+ * @returns AbortController that will abort after timeout
1622
+ */
1623
+ declare function createTimeoutController(timeoutMs: number): {
1624
+ controller: AbortController;
1625
+ clear: () => void;
1626
+ };
1627
+ /**
1628
+ * Execute a fetch request with timeout.
1629
+ *
1630
+ * @param url - The URL to fetch
1631
+ * @param options - Fetch options (excluding signal)
1632
+ * @param timeoutMs - Timeout in milliseconds
1633
+ * @returns Fetch response
1634
+ * @throws TimeoutError if the request times out
1635
+ */
1636
+ declare function fetchWithTimeout(url: string, options: Omit<RequestInit, 'signal'>, timeoutMs: number): Promise<Response>;
1637
+ /**
1638
+ * Retry options for async operations.
1639
+ */
1640
+ interface RetryOptions {
1641
+ /** Maximum number of retry attempts */
1642
+ maxRetries: number;
1643
+ /** Base delay between retries in ms */
1644
+ baseDelayMs: number;
1645
+ /** Maximum delay between retries in ms */
1646
+ maxDelayMs: number;
1647
+ /** Backoff multiplier for exponential backoff */
1648
+ backoffMultiplier: number;
1649
+ /** Function to determine if error is retryable */
1650
+ isRetryable?: (error: Error) => boolean;
1651
+ }
1652
+ /**
1653
+ * Execute a function with automatic retries on failure.
1654
+ *
1655
+ * @param fn - The async function to execute
1656
+ * @param options - Retry options
1657
+ * @returns The result of the function
1658
+ * @throws The last error if all retries fail
1659
+ */
1660
+ declare function withRetry<T>(fn: () => Promise<T>, options?: Partial<RetryOptions>): Promise<T>;
1661
+ /**
1662
+ * Execute a function with both timeout and retry.
1663
+ *
1664
+ * @param fn - The async function to execute
1665
+ * @param timeoutMs - Timeout per attempt in milliseconds
1666
+ * @param operationName - Name of the operation
1667
+ * @param retryOptions - Retry options
1668
+ * @returns The result of the function
1669
+ */
1670
+ declare function withTimeoutAndRetry<T>(fn: () => Promise<T>, timeoutMs: number, operationName: string, retryOptions?: Partial<RetryOptions>): Promise<T>;
1671
+ /**
1672
+ * Sleep for a specified duration.
1673
+ *
1674
+ * @param ms - Duration in milliseconds
1675
+ */
1676
+ declare function sleep(ms: number): Promise<void>;
1677
+ /**
1678
+ * Check if an error is a timeout error.
1679
+ */
1680
+ declare function isTimeoutError(error: unknown): error is TimeoutError;
1681
+ /**
1682
+ * Check if an error appears to be a rate limit error.
1683
+ */
1684
+ declare function isRateLimitError(error: unknown): boolean;
1685
+
1686
+ export { type ApiVersion, ApiVersionSchema, BrowserAdapter, CHAINSTACK_RATE_LIMIT, ConfigError, DEFAULT_CONTRACT_TIMEOUT_MS, DEFAULT_HEALTH_CHECK_TIMEOUT_MS, DEFAULT_PROVIDERS, DEFAULT_PROVIDER_TIMEOUT_MS, DEFAULT_RATE_LIMIT, type HealthCheckConfig, HealthChecker, type Logger, type MasterchainInfo, type Network, type NetworkDefaults, NetworkSchema, NodeAdapter, ORBS_RATE_LIMIT, type ProviderConfig, ProviderConfigSchema, type ProviderEndpoints, ProviderError, type ProviderHealthResult, ProviderManager, type ProviderManagerOptions, type ProviderManagerState, ProviderRegistry, ProviderSelector, type ProviderState, type ProviderStatus, type ProviderType, ProviderTypeSchema, QUICKNODE_RATE_LIMIT, type RateLimitConfig, RateLimitError, type RateLimitState, RateLimiterManager, type ResolvedProvider, type RetryOptions, type RpcConfig, RpcConfigSchema, type SelectionConfig, type StateListener, TimeoutError, TokenBucketRateLimiter, type TonApiResponse, buildGetAddressBalanceUrl, buildGetAddressInfoUrl, buildGetAddressStateUrl, buildRestUrl, createBrowserAdapter, createBrowserAdapterForNetwork, createDefaultConfig, createDefaultRegistry, createEmptyConfig, createHealthChecker, createNodeAdapter, createProviderManager, createRateLimiter, createRateLimiterManager, createRegistry, createRegistryFromData, createRegistryFromFile, createSelector, createTimeoutController, detectNetworkFromEndpoint, fetchWithTimeout, getBaseUrl, getDefaultProvidersForNetwork, getEnvVar, getProviderManager, getProvidersForNetwork, getRateLimitForType, getTonClient, getTonClientForNetwork, isApiVersion, isChainstackUrl, isNetwork, isOrbsUrl, isProviderType, isQuickNodeUrl, isRateLimitError, isTimeoutError, isTonCenterUrl, isValidHttpUrl, isValidWsUrl, loadBuiltinConfig, loadConfig, loadConfigFromData, loadConfigFromUrl, mergeConfigs, mergeWithDefaults, normalizeV2Endpoint, parseProviderConfig, parseRpcConfig, resetNodeAdapter, resolveAllProviders, resolveEndpoints, resolveKeyPlaceholder, resolveProvider, sleep, toV2Base, toV3Base, withRetry, withTimeout, withTimeoutAndRetry, withTimeoutFn };