@fenelabs/fene-sdk 0.3.0 → 0.3.3

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.
package/dist/index.d.mts CHANGED
@@ -1,937 +1,310 @@
1
- import { ethers } from 'ethers';
2
-
3
- interface APIResponse<T> {
4
- data: T;
5
- meta?: Record<string, any>;
6
- }
7
- interface APIError {
8
- error: {
9
- code: string;
10
- message: string;
1
+ type Address = `0x${string}`;
2
+ interface PaginatedResponse<T> {
3
+ data: T[];
4
+ pagination?: {
5
+ page: number;
6
+ limit: number;
7
+ total: number;
8
+ total_pages: number;
11
9
  };
12
10
  }
13
- interface ValidatorDetailResponse {
14
- validator_address: string;
15
- name: string;
16
- description: string;
17
- commission_rate: number;
18
- status: string;
19
- self_stake: string;
20
- delegators_stake: string;
21
- total_stake: string;
22
- uptime: string;
23
- missed_blocks: number;
24
- signed_blocks: number;
25
- total_delegators: number;
26
- withdrawn_rewards_total: string;
27
- }
28
- interface ValidatorEpochResponse {
29
- validator_address: string;
30
- epoch: number;
31
- reward: EpochReward;
32
- stakes: EpochStakes;
33
- distribution: EpochDistribution;
34
- unclaimed: EpochUnclaimed;
35
- }
36
- interface EpochReward {
37
- reward_gross: string;
38
- commission_rate: number;
39
- commission_fee: string;
40
- delegator_pool: string;
41
- }
42
- interface EpochStakes {
43
- self_stake: string;
44
- delegators_stake: string;
45
- total_stake_validator: string;
46
- }
47
- interface EpochDistribution {
48
- self_reward_from_pool: string;
49
- validator_total_reward: string;
50
- delegators_total_reward: string;
51
- }
52
- interface EpochUnclaimed {
53
- unclaimed_validator_reward: string;
54
- unclaimed_delegators_reward_total: string;
55
- delegators: UnclaimedDelegator[];
56
- }
57
- interface UnclaimedDelegator {
58
- delegator_address: string;
59
- stake: string;
60
- reward: string;
61
- unclaimed_reward: string;
62
- }
63
- interface ValidatorListResponse {
11
+ interface NonceResponse {
64
12
  address: string;
65
- count: number;
13
+ nonce: string;
14
+ message: string;
66
15
  }
67
- interface ValidatorDelegatorsResponse {
68
- validator_address: string;
69
- total_delegators: number;
70
- delegators: DelegatorStakeInfo[];
16
+ interface AuthResponse {
17
+ token: string;
18
+ address: string;
19
+ role: 'validator' | 'delegator' | 'public';
20
+ expires_at: number;
71
21
  }
72
- interface DelegatorStakeInfo {
73
- delegator_address: string;
74
- stake: string;
75
- percentage: string;
22
+ declare enum ValidatorStatus {
23
+ NOT_EXIST = 0,
24
+ CREATED = 1,
25
+ STAKED = 2,
26
+ VALIDATED = 3,
27
+ UNSTAKED = 4
76
28
  }
77
- interface ValidatorStakeBreakdownResponse {
78
- validator_address: string;
29
+ interface Validator {
30
+ address: string;
31
+ reward_address: string;
32
+ status: ValidatorStatus;
79
33
  self_stake: string;
80
- delegators_stake: string;
81
34
  total_stake: string;
82
- self_stake_percent: string;
83
- }
84
- interface ValidatorHistoryResponse {
85
- validator_address: string;
86
- from_epoch: number;
87
- to_epoch: number;
88
- history: ValidatorHistoryItem[];
89
- }
90
- interface ValidatorHistoryItem {
91
- epoch: number;
92
- reward: string;
93
- total_stake: string;
94
- uptime: string;
95
- missed_blocks: number;
96
- }
97
- interface ValidatorWithdrawalsResponse {
98
- validator_address: string;
99
- total_withdrawn: string;
100
- withdrawals: ValidatorWithdrawal[];
101
- }
102
- interface ValidatorWithdrawal {
103
- tx_hash: string;
104
- amount: string;
105
- timestamp: number;
106
- block_num: number;
107
- }
108
- interface ValidatorMetricsResponse {
109
- validator_address: string;
110
- uptime: number;
111
- missed_blocks: number;
112
- signed_blocks: number;
113
- total_blocks: number;
114
- apr: number;
115
- total_stake: string;
116
- total_delegators: number;
117
- }
118
- interface ValidatorAPRResponse {
119
- validator_address: string;
120
- apr_decimal: number;
121
- apr_percent: string;
122
- }
123
- interface DelegatorDetailResponse {
124
- delegator_address: string;
125
- total_stake: string;
126
- active_validators: ActiveValidator[];
127
- total_rewards: string;
128
- withdrawn_rewards_total: string;
129
- unbonding?: UnbondingInfo;
130
- }
131
- interface ActiveValidator {
132
- validator_address: string;
133
- stake: string;
134
- }
135
- interface UnbondingInfo {
136
- amount: string;
137
- unbonding_start: number;
138
- unbonding_end: number;
35
+ commission_rate: number;
36
+ claimable_reward: string;
37
+ acc_reward_per_stake: string;
38
+ created_at: number;
39
+ unstake_block: number;
40
+ active_dc_count: number;
41
+ moniker: string;
42
+ phone_number: string;
43
+ details: string;
139
44
  }
140
- interface DelegatorListResponse {
45
+ interface ValidatorSummary {
141
46
  address: string;
142
- count: number;
143
- }
144
- interface DelegatorStakesResponse {
145
- delegator_address: string;
47
+ moniker: string;
146
48
  total_stake: string;
147
- stakes: DelegatorValidatorStake[];
148
- }
149
- interface DelegatorValidatorStake {
150
- validator_address: string;
151
- stake: string;
152
- percentage: string;
153
- }
154
- interface DelegatorRewardsResponse {
155
- delegator_address: string;
156
- total_rewards: string;
157
- rewards: DelegatorReward[];
158
- }
159
- interface DelegatorReward {
160
- validator_address: string;
161
- epoch: number;
162
- amount: string;
163
- timestamp: number;
164
- }
165
- interface DelegatorWithdrawalsResponse {
166
- delegator_address: string;
167
- total_withdrawn: string;
168
- withdrawals: DelegatorWithdrawal[];
169
- }
170
- interface DelegatorWithdrawal {
171
- tx_hash: string;
172
- amount: string;
173
- timestamp: number;
174
- block_num: number;
175
- }
176
- interface DelegatorUnbondingResponse {
177
- delegator_address: string;
178
- has_unbonding: boolean;
179
- unbonding?: UnbondingInfo;
180
- }
181
- interface DelegatorValidatorsResponse {
182
- delegator_address: string;
183
- total_validators: number;
184
- validators: ActiveValidator[];
185
- }
186
- interface ReferralCreateRequest {
187
- validator_address: string;
188
- max_quota?: number;
189
- expires_in_days?: number;
190
- }
191
- interface ReferralValidateRequest {
192
- referral_code: string;
193
- }
194
- interface ReferralApplyRequest {
195
- referral_code: string;
196
- delegator_address: string;
197
- }
198
- interface ReferralValidateResponse {
199
- is_valid: boolean;
200
- referral_code?: string;
201
- message?: string;
202
- }
203
- interface ReferralDelegatorResponse {
204
- delegator_address: string;
205
- referred_by_validator: string;
206
- referral_code_used: string;
207
- }
208
- interface ReferralValidatorResponse {
209
- validator_address: string;
210
- referral_code: string;
211
- delegators: string[];
212
- total_referred: number;
49
+ commission_rate: number;
50
+ status: ValidatorStatus;
51
+ delegator_count: number;
213
52
  }
214
- interface SlashingEventResponse {
215
- validator_address: string;
216
- reason: string;
217
- block_height: number;
218
- penalty_amount: string;
219
- jailed_until?: number;
220
- timestamp: number;
53
+ declare enum DelegatorStatus {
54
+ NOT_EXIST = 0,
55
+ ACTIVE = 1,
56
+ UNSTAKING = 2
221
57
  }
222
- interface GlobalNetworkResponse {
223
- total_network_stake: string;
58
+ interface Delegator {
59
+ address: string;
60
+ validator: string;
61
+ stake_amount: string;
62
+ pending_rewards: string;
63
+ joined_at: number;
64
+ status: DelegatorStatus;
65
+ }
66
+ interface DelegatorStake {
67
+ validator: string;
68
+ stake_amount: string;
69
+ pending_rewards: string;
70
+ status: DelegatorStatus;
71
+ }
72
+ interface DelegatorRewards {
73
+ validator: string;
74
+ pending_rewards: string;
75
+ total_claimed: string;
76
+ }
77
+ interface ReferralKey {
78
+ key: string;
79
+ validator: string;
80
+ created_at: number;
81
+ used_count: number;
82
+ max_uses: number;
83
+ active: boolean;
84
+ }
85
+ interface WhitelistCheckRequest {
86
+ key: string;
87
+ }
88
+ interface WhitelistCheckResponse {
89
+ whitelisted: boolean;
90
+ validator: string;
91
+ tier: number;
92
+ }
93
+ interface GeoNode {
94
+ address: string;
95
+ ip: string;
96
+ latitude: number;
97
+ longitude: number;
98
+ city: string;
99
+ country: string;
100
+ country_code: string;
101
+ last_seen: string;
102
+ node_type: 'validator' | 'rpc' | 'bootstrap';
103
+ online: boolean;
104
+ }
105
+ interface GeoStats {
106
+ total_nodes: number;
107
+ online_nodes: number;
108
+ countries: number;
109
+ cities: number;
110
+ }
111
+ interface GeoUpdateRequest {
112
+ latitude: number;
113
+ longitude: number;
114
+ node_type: string;
115
+ }
116
+ interface NetworkStats {
224
117
  total_validators: number;
118
+ active_validators: number;
225
119
  total_delegators: number;
120
+ total_stake: string;
121
+ current_block: number;
226
122
  epoch: number;
227
- block_height: number;
228
- jailed_validators: number;
229
- ranking_top_delegators: TopDelegatorRank[];
123
+ block_time: number;
230
124
  }
231
- interface TopDelegatorRank {
232
- rank: number;
233
- address: string;
234
- total_stake: string;
125
+ interface EpochInfo {
126
+ number: number;
127
+ start_block: number;
128
+ end_block: number;
129
+ blocks_remaining: number;
130
+ estimated_end: string;
235
131
  }
236
- interface NetworkAPRResponse {
132
+ interface NetworkAPR {
237
133
  network_apr: number;
134
+ annual_emission: string;
135
+ block_reward: string;
136
+ blocks_per_year: number;
238
137
  }
239
- interface NetworkAPRBreakdownResponse {
240
- reward_per_block: string;
241
- reward_per_epoch: string;
242
- reward_per_year: string;
243
- epochs_per_day: number;
244
- effective_inflation: number;
245
- }
246
- interface LeaderboardDelegatorResponse {
247
- rank: number;
248
- address: string;
249
- stake: string;
250
- }
251
- interface LeaderboardValidatorResponse {
252
- rank: number;
253
- address: string;
254
- apr_decimal: number;
255
- total_stake: string;
256
- self_stake: string;
257
- }
258
- interface JWTClaims {
259
- address: string;
260
- role: 'validator' | 'delegator';
261
- exp: number;
262
- iat: number;
263
- iss: string;
264
- }
265
- interface AuthResponse {
266
- token: string;
267
- address: string;
268
- role: string;
269
- expires_at: number;
270
- }
271
- interface SDKConfig {
272
- apiUrl: string;
273
- timeout?: number;
274
- headers?: Record<string, string>;
275
- }
276
- interface QueryParams {
277
- [key: string]: string | number | boolean | undefined;
138
+ interface ValidatorAPR {
139
+ network_apr: number;
140
+ validator_apr: number;
141
+ delegator_apr: number;
278
142
  }
279
- interface ValidatorAnalytics {
280
- address: string;
281
- moniker: string;
282
- uptime: number;
283
- signed_blocks: number;
284
- missed_blocks: number;
285
- total_rewards: number;
286
- total_stakers: number;
287
- status: string;
288
- updated_at: string;
289
- subgraph_indexing_block: number;
143
+ interface UploadResponse {
144
+ success: boolean;
145
+ key: string;
146
+ size: number;
290
147
  }
291
- interface ValidatorAnalyticsListResponse {
292
- count: number;
293
- data: ValidatorAnalytics[];
148
+ interface AvatarResponse {
149
+ url: string | null;
294
150
  }
295
- interface ProtocolStats {
296
- Admin: string;
297
- IsPaused: boolean;
298
- TotalStaking: string;
299
- TotalValidators: string;
300
- ActiveValidators: string;
301
- JailedValidators: string;
302
- TotalRewardsDistributed: string;
303
- TotalSlashed: string;
304
- LastSyncedAt: string;
305
- SubgraphIndexingBlock: number;
151
+ interface DailyBlockStats {
152
+ date: string;
153
+ blocks: number;
154
+ transactions: number;
155
+ gas: number;
306
156
  }
307
- interface RewardDTO {
157
+ interface RewardHistory {
308
158
  block: number;
309
159
  amount: string;
310
- timestamp: number;
311
- }
312
- interface StakeDTO {
313
- staker: string;
314
- amount: string;
315
- }
316
- interface RewardSummary {
317
- total_rewards: string;
318
- total_stakers: number;
319
- uptime: number;
320
- signed_blocks: number;
321
- missed_blocks: number;
322
- last_signed_block: number;
323
- updated_at_block: number;
324
- updated_at_timestamp: number;
325
- rewards_count: number;
326
- stakes_count: number;
327
- last_reward_block: number;
328
- last_reward_amount: string;
329
- total_staked_amount: string;
330
- }
331
- interface ResponseMetadata {
332
- cached: boolean;
333
- stale: boolean;
334
- subgraph_block: number;
335
- limit: number;
336
- offset: number;
337
- has_more: boolean;
338
- }
339
- interface ValidatorRewardsResponse {
340
- address: string;
341
- moniker: string;
342
- reward_address: string;
343
- status: string;
344
- rewards: RewardDTO[];
345
- stakes: StakeDTO[];
346
- summary: RewardSummary;
347
- metadata: ResponseMetadata;
348
- }
349
- interface SyncJobStatus {
350
- status: 'success' | 'degraded' | 'failed' | 'pending';
351
- last_sync_at: string | null;
352
- last_block: number | null;
353
- next_retry_at: string | null;
354
- error: string | null;
355
- retry_count: number;
356
- failure_count: number;
357
- success_count: number;
358
- total_count: number;
359
- failure_rate: number;
360
- }
361
- interface SyncStatusResponse {
362
- protocol_sync: SyncJobStatus;
363
- validator_sync?: SyncJobStatus;
364
- }
365
- interface PaginationOptions {
366
- limit?: number;
367
- offset?: number;
368
- }
369
- interface ValidatorListOptions extends PaginationOptions {
370
- status?: 'active' | 'inactive' | 'jailed';
371
- }
372
-
373
- declare class AuthService {
374
- private apiUrl;
375
- private tokenKey;
376
- constructor(apiUrl: string);
377
- /**
378
- * Get nonce for wallet authentication
379
- * POST /eth/v1/auth/nonce
380
- */
381
- getNonce(address: string): Promise<{
382
- nonce: string;
383
- message: string;
384
- }>;
385
- /**
386
- * Verify wallet signature and get JWT token
387
- * POST /eth/v1/auth/verify
388
- */
389
- verify(params: {
390
- address: string;
391
- signature: string;
392
- role: 'validator' | 'delegator';
393
- }): Promise<{
394
- token: string;
395
- }>;
396
- /**
397
- * Connect wallet and authenticate
398
- */
399
- connectWallet(provider: ethers.BrowserProvider, role?: 'validator' | 'delegator'): Promise<AuthResponse>;
400
- /**
401
- * Get stored JWT token
402
- */
403
- getToken(): string | null;
404
- /**
405
- * Check if user is authenticated
406
- */
407
- isAuthenticated(): boolean;
408
- /**
409
- * Parse JWT token to get claims
410
- */
411
- parseToken(token: string): JWTClaims;
412
- /**
413
- * Get user info from token
414
- */
415
- getUserInfo(): {
416
- address: string;
417
- role: string;
418
- } | null;
419
- /**
420
- * Logout user
421
- */
422
- logout(): void;
423
- /**
424
- * Check if token is expiring soon (within 5 minutes)
425
- */
426
- isTokenExpiringSoon(): boolean;
160
+ timestamp: string;
427
161
  }
428
162
 
429
- declare class HTTPClient {
163
+ interface RequestContext {
164
+ method: string;
165
+ url: string;
166
+ headers: Record<string, string>;
167
+ body?: any;
168
+ timestamp: number;
169
+ attemptNumber: number;
170
+ }
171
+ interface ResponseContext extends RequestContext {
172
+ status: number;
173
+ statusText: string;
174
+ duration: number;
175
+ data?: any;
176
+ }
177
+ interface ResonanceClientConfig {
178
+ /** Base URL of the API. If not provided, reads from RESONANCE_API_URL env var */
179
+ baseUrl?: string;
180
+ /** Bearer token for authentication */
181
+ token?: string;
182
+ /** Request timeout in milliseconds (default: 30000) */
183
+ timeout?: number;
184
+ /** Number of retry attempts for failed requests (default: 2) */
185
+ retries?: number;
186
+ /** Initial delay between retries in milliseconds (default: 1000) */
187
+ retryDelay?: number;
188
+ /** Called when token expires (401 response) */
189
+ onTokenExpired?: () => void;
190
+ /** Called before each request */
191
+ onRequest?: (ctx: RequestContext) => void;
192
+ /** Called after successful response */
193
+ onResponse?: (ctx: ResponseContext) => void;
194
+ /** Called when request fails */
195
+ onError?: (error: Error, ctx: RequestContext) => void;
196
+ }
197
+ declare class ResonanceClient {
430
198
  private baseUrl;
199
+ private token?;
431
200
  private timeout;
432
- private headers;
433
- constructor(config: SDKConfig);
434
- /**
435
- * Build URL with query parameters
436
- */
437
- private buildUrl;
438
- /**
439
- * Set authorization token
440
- */
441
- setAuthToken(token: string | null): void;
442
- /**
443
- * Set custom header
444
- */
445
- setHeader(key: string, value: string): void;
446
- /**
447
- * Make HTTP GET request
448
- */
449
- get<T>(path: string, params?: QueryParams): Promise<T>;
450
- /**
451
- * Make HTTP POST request
452
- */
453
- post<T>(path: string, body?: any): Promise<T>;
454
- /**
455
- * Make HTTP DELETE request
456
- */
457
- delete<T>(path: string): Promise<T>;
458
- /**
459
- * Handle HTTP errors
460
- */
461
- private handleError;
462
- private fetchWithRetry;
463
- }
464
-
465
- declare class ValidatorsAPI {
466
- private client;
467
- constructor(client: HTTPClient);
468
- /**
469
- * Get all validators
470
- * GET /eth/v1/validators
471
- */
472
- getAll(): Promise<ValidatorListResponse>;
473
- /**
474
- * Get validator details
475
- * GET /eth/v1/validators/:address
476
- */
477
- get(address: string): Promise<ValidatorDetailResponse>;
478
- /**
479
- * Get validator delegators
480
- * GET /eth/v1/validators/:address/delegators
481
- */
482
- getDelegators(address: string): Promise<ValidatorDelegatorsResponse>;
483
- /**
484
- * Get validator stake breakdown
485
- * GET /eth/v1/validators/:address/stake
486
- */
487
- getStakeBreakdown(address: string): Promise<ValidatorStakeBreakdownResponse>;
488
- /**
489
- * Get validator epoch details
490
- * GET /eth/v1/validators/:address/epochs/:epoch
491
- */
492
- getEpoch(address: string, epoch: number): Promise<ValidatorEpochResponse>;
493
- /**
494
- * Get validator history
495
- * GET /eth/v1/validators/:address/history
496
- * @param address - Validator address
497
- * @param fromEpoch - Optional starting epoch
498
- * @param toEpoch - Optional ending epoch
499
- */
500
- getHistory(address: string, fromEpoch?: number, toEpoch?: number): Promise<ValidatorHistoryResponse>;
501
- /**
502
- * Get validator withdrawals
503
- * GET /eth/v1/validators/:address/withdrawals
504
- * @param address - Validator address
505
- * @param limit - Optional limit
506
- * @param offset - Optional offset
507
- */
508
- getWithdrawals(address: string, limit?: number, offset?: number): Promise<ValidatorWithdrawalsResponse>;
509
- /**
510
- * Get validator metrics
511
- * GET /eth/v1/validators/:address/metrics
512
- */
513
- getMetrics(address: string): Promise<ValidatorMetricsResponse>;
514
- /**
515
- * Get validator slashing events
516
- * GET /eth/v1/validators/:address/slashing
517
- */
518
- getSlashing(address: string): Promise<SlashingEventResponse[]>;
519
- /**
520
- * Get validator APR
521
- * GET /eth/v1/validators/:address/apr
522
- */
523
- getAPR(address: string): Promise<ValidatorAPRResponse>;
524
- }
525
-
526
- declare class DelegatorsAPI {
527
- private client;
528
- constructor(client: HTTPClient);
529
- /**
530
- * Get all delegators
531
- * GET /eth/v1/delegators
532
- */
533
- getAll(): Promise<DelegatorListResponse>;
534
- /**
535
- * Get delegator details
536
- * GET /eth/v1/delegators/:address
537
- */
538
- get(address: string): Promise<DelegatorDetailResponse>;
539
- /**
540
- * Get delegator stakes breakdown per validator
541
- * GET /eth/v1/delegators/:address/stakes
542
- */
543
- getStakes(address: string): Promise<DelegatorStakesResponse>;
544
- /**
545
- * Get delegator rewards history
546
- * GET /eth/v1/delegators/:address/rewards
547
- * @param address - Delegator address
548
- * @param limit - Optional limit
549
- * @param offset - Optional offset
550
- */
551
- getRewards(address: string, limit?: number, offset?: number): Promise<DelegatorRewardsResponse>;
552
- /**
553
- * Get delegator withdrawals history
554
- * GET /eth/v1/delegators/:address/withdrawals
555
- * @param address - Delegator address
556
- * @param limit - Optional limit
557
- * @param offset - Optional offset
558
- */
559
- getWithdrawals(address: string, limit?: number, offset?: number): Promise<DelegatorWithdrawalsResponse>;
560
- /**
561
- * Get delegator unbonding status
562
- * GET /eth/v1/delegators/:address/unbonding
563
- */
564
- getUnbonding(address: string): Promise<DelegatorUnbondingResponse>;
565
- /**
566
- * Get delegator active validators
567
- * GET /eth/v1/delegators/:address/validators
568
- */
569
- getValidators(address: string): Promise<DelegatorValidatorsResponse>;
570
- }
571
-
572
- declare class ReferralsAPI {
573
- private client;
574
- constructor(client: HTTPClient);
575
- /**
576
- * Validate a referral code
577
- * GET /eth/v1/referrals/validate?code=CODE
578
- */
579
- validate(referralCode: string): Promise<ReferralValidateResponse>;
580
- /**
581
- * Create a new referral code
582
- * POST /eth/v1/referrals
583
- * @param request - Referral creation request
584
- */
585
- create(request: ReferralCreateRequest): Promise<ReferralValidatorResponse>;
586
- /**
587
- * Apply a referral code
588
- * POST /eth/v1/referrals/apply
589
- * @param request - Referral application request
590
- */
591
- apply(request: ReferralApplyRequest): Promise<{
592
- message: string;
593
- }>;
594
- /**
595
- * Delete a referral code
596
- * DELETE /eth/v1/referrals/:referral_code
597
- * @param referralCode - The referral code to delete
598
- */
599
- delete(referralCode: string): Promise<{
600
- message: string;
601
- }>;
602
- /**
603
- * Unlink a delegator from referral
604
- * DELETE /eth/v1/referrals/unlink/:delegator_address
605
- * @param delegatorAddress - The delegator address to unlink
606
- */
607
- unlink(delegatorAddress: string): Promise<{
608
- message: string;
609
- }>;
610
- /**
611
- * Get delegator referral information
612
- * GET /eth/v1/referrals/delegators/:delegator_address
613
- */
614
- getDelegatorReferral(delegatorAddress: string): Promise<ReferralDelegatorResponse>;
615
- /**
616
- * Get validator referral information
617
- * GET /eth/v1/referrals/validators/:validator_address
618
- */
619
- getValidatorReferral(validatorAddress: string): Promise<ReferralValidatorResponse>;
620
- }
621
-
622
- declare class GlobalAPI {
623
- private client;
624
- constructor(client: HTTPClient);
625
- /**
626
- * Get global network statistics
627
- * GET /eth/v1/global
628
- */
629
- getStats(): Promise<GlobalNetworkResponse>;
630
- /**
631
- * Get network APR (from /global endpoint)
632
- * GET /eth/v1/global/network_apr
633
- */
634
- getNetworkAPRFromGlobal(): Promise<NetworkAPRResponse>;
635
- /**
636
- * Get network APR (from /network endpoint)
637
- * GET /eth/v1/network/apr
638
- */
639
- getNetworkAPR(): Promise<NetworkAPRResponse>;
640
- /**
641
- * Get network APR breakdown
642
- * GET /eth/v1/network/apr/breakdown
643
- */
644
- getNetworkAPRBreakdown(): Promise<NetworkAPRBreakdownResponse>;
645
- /**
646
- * Get delegator leaderboard
647
- * GET /eth/v1/leaderboard/delegators
648
- * @param limit - Optional limit (default backend value)
649
- * @param offset - Optional offset for pagination
650
- */
651
- getLeaderboardDelegators(limit?: number, offset?: number): Promise<LeaderboardDelegatorResponse[]>;
652
- /**
653
- * Get validator leaderboard
654
- * GET /eth/v1/leaderboard/validators
655
- * @param limit - Optional limit (default backend value)
656
- * @param offset - Optional offset for pagination
657
- */
658
- getLeaderboardValidators(limit?: number, offset?: number): Promise<LeaderboardValidatorResponse[]>;
659
- }
660
-
661
- declare class SlashingAPI {
662
- private client;
663
- constructor(client: HTTPClient);
664
- /**
665
- * Get slashing events
666
- * GET /eth/v1/slashing/events
667
- * @param validatorAddress - Optional validator address filter
668
- * @param limit - Optional limit
669
- * @param offset - Optional offset
670
- */
671
- getEvents(validatorAddress?: string, limit?: number, offset?: number): Promise<SlashingEventResponse[]>;
672
- }
201
+ private retries;
202
+ private retryDelay;
203
+ private onTokenExpired?;
204
+ private onRequest?;
205
+ private onResponse?;
206
+ private onError?;
207
+ constructor(config?: ResonanceClientConfig);
208
+ setToken(token: string): void;
209
+ clearToken(): void;
210
+ private request;
211
+ private executeRequest;
212
+ getNonce(address: Address): Promise<NonceResponse>;
213
+ verify(address: Address, signature: string): Promise<AuthResponse>;
214
+ getValidators(): Promise<ValidatorSummary[]>;
215
+ getActiveValidators(): Promise<ValidatorSummary[]>;
216
+ getCandidates(): Promise<ValidatorSummary[]>;
217
+ getValidator(address: Address): Promise<Validator>;
218
+ getValidatorDelegators(address: Address): Promise<Delegator[]>;
219
+ getDelegator(address: Address): Promise<Delegator>;
220
+ getDelegatorStakes(address: Address): Promise<DelegatorStake[]>;
221
+ getDelegatorRewards(address: Address): Promise<DelegatorRewards[]>;
222
+ getReferralKey(key: string): Promise<ReferralKey>;
223
+ getValidatorKeys(address: Address): Promise<ReferralKey[]>;
224
+ checkWhitelist(data: WhitelistCheckRequest): Promise<WhitelistCheckResponse>;
225
+ getGeoNodes(): Promise<GeoNode[]>;
226
+ getGeoValidators(): Promise<GeoNode[]>;
227
+ getGeoStats(): Promise<GeoStats>;
228
+ updateGeoLocation(data: GeoUpdateRequest): Promise<void>;
229
+ getNetworkStats(): Promise<NetworkStats>;
230
+ getCurrentEpoch(): Promise<EpochInfo>;
231
+ getNetworkAPR(): Promise<NetworkAPR>;
232
+ getValidatorAPR(address: Address): Promise<ValidatorAPR>;
233
+ uploadAvatar(file: File): Promise<UploadResponse>;
234
+ getAvatar(address: Address): Promise<AvatarResponse>;
235
+ getDailyBlockStats(days?: number): Promise<DailyBlockStats[]>;
236
+ getValidatorRewardHistory(address: Address, limit?: number): Promise<RewardHistory[]>;
237
+ }
238
+ declare function createResonanceClient(config: ResonanceClientConfig): ResonanceClient;
673
239
 
674
240
  /**
675
- * Analytics API Module
676
- *
677
- * Provides access to analytics endpoints powered by subgraph indexing.
678
- * These endpoints provide aggregated and historical data from the blockchain.
679
- *
680
- * @remarks
681
- * Analytics data is sourced from The Graph subgraph and may have slight delays
682
- * compared to real-time blockchain data. Check sync status for data freshness.
683
- *
684
- * @example
685
- * ```typescript
686
- * // Get protocol statistics
687
- * const stats = await sdk.analytics.getProtocolStats();
688
- *
689
- * // Get top validators by uptime
690
- * const topValidators = await sdk.analytics.getTopValidators(10);
691
- *
692
- * // Get validator rewards with pagination
693
- * const rewards = await sdk.analytics.getValidatorRewards(
694
- * '0x1234...',
695
- * { limit: 50, offset: 0 }
696
- * );
697
- * ```
241
+ * Error codes matching the Resonance API error system
698
242
  */
699
- declare class AnalyticsAPI {
700
- private client;
701
- private readonly basePath;
702
- constructor(client: HTTPClient);
703
- /**
704
- * Get protocol-level statistics
705
- *
706
- * Returns aggregated statistics about the entire protocol including
707
- * total staking, validator counts, and rewards distribution.
708
- *
709
- * @returns Protocol statistics from subgraph
710
- *
711
- * @example
712
- * ```typescript
713
- * const stats = await sdk.analytics.getProtocolStats();
714
- * console.log(`Total Staking: ${stats.TotalStaking}`);
715
- * console.log(`Active Validators: ${stats.ActiveValidators}`);
716
- * ```
717
- */
718
- getProtocolStats(): Promise<ProtocolStats>;
719
- /**
720
- * Get sync status of analytics workers
721
- *
722
- * Returns the current synchronization status of background workers
723
- * that index blockchain data into the analytics database.
724
- *
725
- * @returns Sync status for each worker
726
- *
727
- * @example
728
- * ```typescript
729
- * const status = await sdk.analytics.getSyncStatus();
730
- * if (status.protocol_sync.status === 'success') {
731
- * console.log(`Last synced at block: ${status.protocol_sync.last_block}`);
732
- * }
733
- * ```
734
- */
735
- getSyncStatus(): Promise<SyncStatusResponse>;
736
- /**
737
- * Get all validators with analytics data
738
- *
739
- * Returns a paginated list of validators with their analytics metrics
740
- * including uptime, signed blocks, and staker counts.
741
- *
742
- * @param options - Pagination and filter options
743
- * @returns Paginated list of validators
744
- *
745
- * @example
746
- * ```typescript
747
- * // Get first 20 validators
748
- * const result = await sdk.analytics.getAllValidators({ limit: 20 });
749
- *
750
- * // Get next page
751
- * const nextPage = await sdk.analytics.getAllValidators({
752
- * limit: 20,
753
- * offset: 20
754
- * });
755
- *
756
- * // Filter by status
757
- * const active = await sdk.analytics.getAllValidators({
758
- * status: 'active',
759
- * limit: 50
760
- * });
761
- * ```
762
- */
763
- getAllValidators(options?: ValidatorListOptions): Promise<ValidatorAnalyticsListResponse>;
764
- /**
765
- * Get top validators by uptime
766
- *
767
- * Returns validators sorted by uptime percentage in descending order.
768
- * Useful for displaying leaderboards or finding most reliable validators.
769
- *
770
- * @param limit - Maximum number of validators to return (default: 10)
771
- * @returns Top validators by uptime
772
- *
773
- * @example
774
- * ```typescript
775
- * // Get top 5 validators
776
- * const top5 = await sdk.analytics.getTopValidators(5);
777
- *
778
- * top5.data.forEach((validator, index) => {
779
- * console.log(`#${index + 1}: ${validator.moniker} - ${validator.uptime}% uptime`);
780
- * });
781
- * ```
782
- */
783
- getTopValidators(limit?: number): Promise<ValidatorAnalyticsListResponse>;
784
- /**
785
- * Get analytics data for a specific validator
786
- *
787
- * Returns detailed analytics metrics for a single validator including
788
- * performance statistics and current status.
789
- *
790
- * @param address - Validator address (with or without 0x prefix)
791
- * @returns Validator analytics data
792
- *
793
- * @throws {ResonanceAPIError} 404 if validator not found
794
- *
795
- * @example
796
- * ```typescript
797
- * const validator = await sdk.analytics.getValidatorAnalytics('0x1234...');
798
- * console.log(`${validator.moniker}: ${validator.uptime}% uptime`);
799
- * console.log(`Signed: ${validator.signed_blocks}, Missed: ${validator.missed_blocks}`);
800
- * ```
801
- */
802
- getValidatorAnalytics(address: string): Promise<ValidatorAnalytics>;
803
- /**
804
- * Get validator rewards with pagination
805
- *
806
- * Returns detailed reward and stake information for a validator.
807
- * This is a heavy endpoint that MUST use pagination.
808
- *
809
- * @param address - Validator address (with or without 0x prefix)
810
- * @param options - Pagination options (required)
811
- * @returns Validator rewards, stakes, and summary
812
- *
813
- * @throws {ResonanceAPIError} 404 if validator not found
814
- *
815
- * @remarks
816
- * This endpoint can return large amounts of data. Always use pagination
817
- * with reasonable limit values (recommended: 50-100).
818
- *
819
- * @example
820
- * ```typescript
821
- * // Get first page of rewards
822
- * const page1 = await sdk.analytics.getValidatorRewards('0x1234...', {
823
- * limit: 50,
824
- * offset: 0
825
- * });
826
- *
827
- * console.log(`Total stakers: ${page1.summary.total_stakers}`);
828
- * console.log(`Has more data: ${page1.metadata.has_more}`);
829
- *
830
- * // Get next page if available
831
- * if (page1.metadata.has_more) {
832
- * const page2 = await sdk.analytics.getValidatorRewards('0x1234...', {
833
- * limit: 50,
834
- * offset: 50
835
- * });
836
- * }
837
- * ```
838
- */
839
- getValidatorRewards(address: string, options: PaginationOptions): Promise<ValidatorRewardsResponse>;
840
- /**
841
- * Get all validator rewards with automatic pagination
842
- *
843
- * Automatically fetches all pages of validator rewards data.
844
- * Use with caution as this can make multiple API calls.
845
- *
846
- * @param address - Validator address (with or without 0x prefix)
847
- * @param options - Batch size and safety limits
848
- * @returns Complete validator rewards data
849
- *
850
- * @throws {ResonanceAPIError} 404 if validator not found
851
- * @throws {Error} If max pages limit is reached
852
- *
853
- * @remarks
854
- * This method will make multiple API calls. Use maxPages to prevent
855
- * infinite loops or excessive API usage.
856
- *
857
- * @example
858
- * ```typescript
859
- * // Fetch all rewards with default settings
860
- * const allRewards = await sdk.analytics.getAllValidatorRewards('0x1234...');
861
- *
862
- * // Custom batch size and limit
863
- * const rewards = await sdk.analytics.getAllValidatorRewards('0x1234...', {
864
- * batchSize: 100,
865
- * maxPages: 5
866
- * });
867
- *
868
- * console.log(`Total rewards: ${rewards.summary.total_rewards}`);
869
- * console.log(`Total API calls made: ${Math.ceil(rewards.stakes.length / 100)}`);
870
- * ```
871
- */
872
- getAllValidatorRewards(address: string, options?: {
873
- batchSize?: number;
874
- maxPages?: number;
875
- }): Promise<ValidatorRewardsResponse>;
243
+ declare const ErrorCode: {
244
+ readonly VALIDATOR_NOT_FOUND: "VALIDATOR_NOT_FOUND";
245
+ readonly VALIDATOR_INACTIVE: "VALIDATOR_INACTIVE";
246
+ readonly DELEGATOR_NOT_FOUND: "DELEGATOR_NOT_FOUND";
247
+ readonly NOT_WHITELISTED: "NOT_WHITELISTED";
248
+ readonly REFERRAL_KEY_INVALID: "REFERRAL_KEY_INVALID";
249
+ readonly REFERRAL_KEY_EXPIRED: "REFERRAL_KEY_EXPIRED";
250
+ readonly REFERRAL_KEY_USED: "REFERRAL_KEY_USED";
251
+ readonly INVALID_SIGNATURE: "INVALID_SIGNATURE";
252
+ readonly NONCE_EXPIRED: "NONCE_EXPIRED";
253
+ readonly UNAUTHORIZED: "UNAUTHORIZED";
254
+ readonly RPC_UNAVAILABLE: "RPC_UNAVAILABLE";
255
+ readonly CACHE_UNAVAILABLE: "CACHE_UNAVAILABLE";
256
+ readonly DATABASE_UNAVAILABLE: "DATABASE_UNAVAILABLE";
257
+ readonly BAD_REQUEST: "BAD_REQUEST";
258
+ readonly INTERNAL_ERROR: "INTERNAL_ERROR";
259
+ readonly RATE_LIMITED: "RATE_LIMITED";
260
+ readonly TIMEOUT: "TIMEOUT";
261
+ readonly NETWORK_ERROR: "NETWORK_ERROR";
262
+ };
263
+ type ErrorCodeType = typeof ErrorCode[keyof typeof ErrorCode];
264
+ /**
265
+ * API Error response structure from Resonance API
266
+ */
267
+ interface APIErrorResponse {
268
+ code: string;
269
+ message: string;
270
+ details?: any;
876
271
  }
877
-
878
272
  /**
879
- * Resonance Network SDK
880
- *
881
- * Main SDK class that provides access to all API endpoints
882
- *
883
- * @example
884
- * ```typescript
885
- * import { ResonanceSDK } from '@avenbreaks/resonance-sdk';
886
- *
887
- * const sdk = new ResonanceSDK({
888
- * apiUrl: 'https://api.resonance.network'
889
- * });
890
- *
891
- * // Get global network stats
892
- * const stats = await sdk.global.getStats();
893
- *
894
- * // Get validator details
895
- * const validator = await sdk.validators.get('0x1234...');
896
- *
897
- * // Get analytics data (from subgraph)
898
- * const analytics = await sdk.analytics.getProtocolStats();
899
- * const topValidators = await sdk.analytics.getTopValidators(10);
900
- * ```
273
+ * ResonanceError represents a structured error from the Resonance API
901
274
  */
902
- declare class ResonanceSDK {
903
- private client;
904
- auth: AuthService;
905
- validators: ValidatorsAPI;
906
- delegators: DelegatorsAPI;
907
- referrals: ReferralsAPI;
908
- global: GlobalAPI;
909
- slashing: SlashingAPI;
910
- analytics: AnalyticsAPI;
911
- constructor(config: SDKConfig);
912
- /**
913
- * Set authentication token for API requests
914
- * @param token - JWT token
915
- */
916
- setAuthToken(token: string | null): void;
917
- /**
918
- * Set custom header for API requests
919
- * @param key - Header key
920
- * @param value - Header value
921
- */
922
- setHeader(key: string, value: string): void;
923
- /**
924
- * Get the current auth token from storage
925
- */
926
- getAuthToken(): string | null;
275
+ declare class ResonanceError extends Error {
276
+ readonly code: string;
277
+ readonly details?: any;
278
+ readonly statusCode?: number;
279
+ constructor(code: string, message: string, details?: any, statusCode?: number);
927
280
  /**
928
- * Check if user is authenticated
281
+ * Check if this is a specific error code
929
282
  */
930
- isAuthenticated(): boolean;
283
+ is(code: ErrorCodeType): boolean;
931
284
  /**
932
- * Logout user and clear auth token
285
+ * Convert to JSON representation
933
286
  */
934
- logout(): void;
287
+ toJSON(): APIErrorResponse;
935
288
  }
289
+ /**
290
+ * Type guard to check if an error is a ResonanceError
291
+ */
292
+ declare function isResonanceError(error: unknown): error is ResonanceError;
293
+ /**
294
+ * Type guard to check if an error has a specific error code
295
+ */
296
+ declare function hasErrorCode(error: unknown, code: ErrorCodeType): boolean;
297
+ /**
298
+ * Check if error is a network/connectivity error
299
+ */
300
+ declare function isNetworkError(error: unknown): boolean;
301
+ /**
302
+ * Check if error is an authentication error
303
+ */
304
+ declare function isAuthError(error: unknown): boolean;
305
+ /**
306
+ * Check if error is a not found error
307
+ */
308
+ declare function isNotFoundError(error: unknown): boolean;
936
309
 
937
- export { type APIError, type APIResponse, type ActiveValidator, AnalyticsAPI, type AuthResponse, AuthService, type DelegatorDetailResponse, type DelegatorListResponse, type DelegatorReward, type DelegatorRewardsResponse, type DelegatorStakeInfo, type DelegatorStakesResponse, type DelegatorUnbondingResponse, type DelegatorValidatorStake, type DelegatorValidatorsResponse, type DelegatorWithdrawal, type DelegatorWithdrawalsResponse, DelegatorsAPI, type EpochDistribution, type EpochReward, type EpochStakes, type EpochUnclaimed, GlobalAPI, type GlobalNetworkResponse, HTTPClient, type JWTClaims, type LeaderboardDelegatorResponse, type LeaderboardValidatorResponse, type NetworkAPRBreakdownResponse, type NetworkAPRResponse, type PaginationOptions, type ProtocolStats, type QueryParams, type ReferralApplyRequest, type ReferralCreateRequest, type ReferralDelegatorResponse, type ReferralValidateRequest, type ReferralValidateResponse, type ReferralValidatorResponse, ReferralsAPI, ResonanceSDK, type ResponseMetadata, type RewardDTO, type RewardSummary, type SDKConfig, SlashingAPI, type SlashingEventResponse, type StakeDTO, type SyncJobStatus, type SyncStatusResponse, type TopDelegatorRank, type UnbondingInfo, type UnclaimedDelegator, type ValidatorAPRResponse, type ValidatorAnalytics, type ValidatorAnalyticsListResponse, type ValidatorDelegatorsResponse, type ValidatorDetailResponse, type ValidatorEpochResponse, type ValidatorHistoryItem, type ValidatorHistoryResponse, type ValidatorListOptions, type ValidatorListResponse, type ValidatorMetricsResponse, type ValidatorRewardsResponse, type ValidatorStakeBreakdownResponse, type ValidatorWithdrawal, type ValidatorWithdrawalsResponse, ValidatorsAPI, ResonanceSDK as default };
310
+ export { type APIErrorResponse, type Address, type AuthResponse, type AvatarResponse, type DailyBlockStats, type Delegator, type DelegatorRewards, type DelegatorStake, DelegatorStatus, type EpochInfo, ErrorCode, type ErrorCodeType, type GeoNode, type GeoStats, type GeoUpdateRequest, type NetworkAPR, type NetworkStats, type NonceResponse, type PaginatedResponse, type ReferralKey, type RequestContext, ResonanceClient, type ResonanceClientConfig, ResonanceError, type ResponseContext, type RewardHistory, type UploadResponse, type Validator, type ValidatorAPR, ValidatorStatus, type ValidatorSummary, type WhitelistCheckRequest, type WhitelistCheckResponse, createResonanceClient, hasErrorCode, isAuthError, isNetworkError, isNotFoundError, isResonanceError };