@fenelabs/fene-sdk 0.2.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,152 @@
1
+ # Changelog
2
+
3
+ All notable changes to the Resonance SDK will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [0.2.0] - 2025-12-10
9
+
10
+ ### Added
11
+
12
+ #### Analytics API Module (Subgraph Data)
13
+ - **New `analytics` module** for accessing subgraph-indexed blockchain data
14
+ - `getProtocolStats()` - Get protocol-level statistics (total staking, validator counts, rewards)
15
+ - `getSyncStatus()` - Check synchronization status of analytics workers
16
+ - `getAllValidators()` - Get paginated list of validators with analytics data
17
+ - `getTopValidators()` - Get top validators sorted by uptime
18
+ - `getValidatorAnalytics()` - Get detailed analytics for a specific validator
19
+ - `getValidatorRewards()` - Get validator rewards and stakes with **mandatory pagination**
20
+ - `getAllValidatorRewards()` - Auto-pagination helper for fetching complete reward data
21
+
22
+ #### New Types
23
+ - `ValidatorAnalytics` - Validator analytics data structure
24
+ - `ValidatorAnalyticsListResponse` - Paginated validator list response
25
+ - `ProtocolStats` - Protocol-level statistics
26
+ - `ValidatorRewardsResponse` - Validator rewards with metadata
27
+ - `SyncStatusResponse` - Worker synchronization status
28
+ - `RewardDTO`, `StakeDTO`, `RewardSummary` - Reward-related types
29
+ - `ResponseMetadata` - Response metadata with cache and pagination info
30
+ - `PaginationOptions`, `ValidatorListOptions` - Pagination interfaces
31
+
32
+ ### Changed
33
+ - Updated main SDK class to include `analytics` module
34
+ - Enhanced README with comprehensive analytics documentation
35
+ - Added `examples/analytics-usage.ts` with complete usage examples
36
+
37
+ ### Notes
38
+ - Analytics data is sourced from The Graph subgraph and may have slight delays
39
+ - Rewards endpoint requires pagination to prevent excessive data transfer
40
+ - Always check `metadata.cached` and `metadata.stale` flags for data freshness
41
+ - Use `getSyncStatus()` to verify subgraph synchronization before critical operations
42
+
43
+ ## [0.1.1] - 2025-11-26
44
+
45
+ ### Fixed
46
+ - Fixed referral validate endpoint to use correct query parameter `code` instead of `referral_code`
47
+ - Fixed indentation in referrals.ts validate method
48
+
49
+ ### Changed
50
+ - Updated JSDoc comment to reflect correct query parameter format `?code=CODE`
51
+
52
+ ## [0.1.0] - 2024-11-26
53
+
54
+ ### Added
55
+
56
+ #### Core SDK Features
57
+ - Initial release of Resonance Network SDK
58
+ - Full TypeScript support with comprehensive type definitions
59
+ - Support for both CommonJS and ES modules
60
+ - Browser and Node.js compatibility
61
+
62
+ #### API Modules
63
+ - **Global API**: Network statistics, APR calculations, and leaderboards
64
+ - `getStats()` - Get global network statistics
65
+ - `getNetworkAPR()` - Get network APR
66
+ - `getNetworkAPRBreakdown()` - Get detailed APR breakdown
67
+ - `getLeaderboardDelegators()` - Get delegator leaderboard
68
+ - `getLeaderboardValidators()` - Get validator leaderboard
69
+
70
+ - **Validators API**: Complete validator information and metrics
71
+ - `getAll()` - List all validators
72
+ - `get()` - Get validator details
73
+ - `getDelegators()` - Get validator's delegators
74
+ - `getStakeBreakdown()` - Get stake distribution
75
+ - `getEpoch()` - Get epoch-specific data
76
+ - `getHistory()` - Get historical data
77
+ - `getWithdrawals()` - Get withdrawal history
78
+ - `getMetrics()` - Get performance metrics
79
+ - `getSlashing()` - Get slashing events
80
+ - `getAPR()` - Get validator-specific APR
81
+
82
+ - **Delegators API**: Delegator data and staking information
83
+ - `getAll()` - List all delegators
84
+ - `get()` - Get delegator details
85
+ - `getStakes()` - Get stake breakdown
86
+ - `getRewards()` - Get reward history
87
+ - `getWithdrawals()` - Get withdrawal history
88
+ - `getUnbonding()` - Get unbonding status
89
+ - `getValidators()` - Get active validators
90
+
91
+ - **Referrals API**: Referral code management
92
+ - `validate()` - Validate referral code
93
+ - `create()` - Create new referral code (authenticated)
94
+ - `apply()` - Apply referral code
95
+ - `delete()` - Delete referral code (authenticated)
96
+ - `unlink()` - Unlink delegator from referral (authenticated)
97
+ - `getDelegatorReferral()` - Get delegator's referral info
98
+ - `getValidatorReferral()` - Get validator's referral info
99
+
100
+ - **Slashing API**: Slashing events and penalties
101
+ - `getEvents()` - Get slashing events with optional filters
102
+
103
+ #### Authentication
104
+ - Web3 wallet authentication support
105
+ - JWT token management
106
+ - Session storage for token persistence
107
+ - Automatic token expiration checking
108
+ - Support for both validator and delegator roles
109
+
110
+ #### HTTP Client
111
+ - Custom timeout configuration
112
+ - Custom header support
113
+ - Automatic error handling
114
+ - Query parameter building
115
+ - Request/response type safety
116
+
117
+ #### Developer Experience
118
+ - Comprehensive TypeScript types for all API responses
119
+ - Example files for common use cases
120
+ - React hooks example for authentication
121
+ - Full JSDoc documentation
122
+ - ESLint configuration
123
+ - Build tooling with tsup
124
+
125
+ ### Documentation
126
+ - Complete README with usage examples
127
+ - API reference documentation
128
+ - React and Next.js integration examples
129
+ - Node.js usage examples
130
+ - Authentication flow examples
131
+ - Error handling examples
132
+
133
+ ### Build & Distribution
134
+ - CommonJS (CJS) build for Node.js
135
+ - ES Module (ESM) build for modern bundlers
136
+ - TypeScript declaration files (.d.ts)
137
+ - Tree-shakeable exports
138
+
139
+ ## [Unreleased]
140
+
141
+ ### Planned Features
142
+ - WebSocket support for real-time updates
143
+ - Caching layer for frequently accessed data
144
+ - Rate limiting and retry logic
145
+ - GraphQL support (if API adds GraphQL)
146
+ - Additional utility functions for common operations
147
+ - React hooks package (@resonance/sdk-react)
148
+ - Vue composables package (@resonance/sdk-vue)
149
+
150
+ ---
151
+
152
+ [0.1.0]: https://github.com/resonance-network/sdk/releases/tag/v0.1.0
package/README.md ADDED
@@ -0,0 +1,429 @@
1
+ # Resonance Network SDK
2
+
3
+ Official TypeScript/JavaScript SDK for interacting with the Resonance Network API.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @avenbreaks/resonance-sdk
9
+ # or
10
+ yarn add @avenbreaks/resonance-sdk
11
+ # or
12
+ pnpm add @avenbreaks/resonance-sdk
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ```typescript
18
+ import { ResonanceSDK } from '@avenbreaks/resonance-sdk';
19
+
20
+ // Initialize the SDK
21
+ const sdk = new ResonanceSDK({
22
+ apiUrl: 'https://api.resonance.network',
23
+ timeout: 30000, // Optional, default 30s
24
+ });
25
+
26
+ // Get global network statistics
27
+ const stats = await sdk.global.getStats();
28
+ console.log('Total Network Stake:', stats.total_network_stake);
29
+
30
+ // Get validator details
31
+ const validator = await sdk.validators.get('0x1234...');
32
+ console.log('Validator Status:', validator.status);
33
+ ```
34
+
35
+ ## Authentication
36
+
37
+ The SDK supports wallet-based authentication using Web3 providers:
38
+
39
+ ```typescript
40
+ import { ethers } from 'ethers';
41
+ import { ResonanceSDK } from '@avenbreaks/resonance-sdk';
42
+
43
+ const sdk = new ResonanceSDK({
44
+ apiUrl: 'https://api.resonance.network',
45
+ });
46
+
47
+ // Connect wallet (browser environment)
48
+ const provider = new ethers.BrowserProvider(window.ethereum);
49
+ const authResponse = await sdk.auth.connectWallet(provider, 'delegator');
50
+
51
+ // Set the JWT token for authenticated requests
52
+ sdk.setAuthToken(authResponse.token);
53
+
54
+ // Check authentication status
55
+ if (sdk.isAuthenticated()) {
56
+ console.log('User is authenticated');
57
+ }
58
+
59
+ // Logout
60
+ sdk.logout();
61
+ ```
62
+
63
+ ## API Reference
64
+
65
+ ### Global Network Stats
66
+
67
+ ```typescript
68
+ // Get global network statistics
69
+ const stats = await sdk.global.getStats();
70
+
71
+ // Get network APR
72
+ const apr = await sdk.global.getNetworkAPR();
73
+
74
+ // Get network APR breakdown
75
+ const breakdown = await sdk.global.getNetworkAPRBreakdown();
76
+
77
+ // Get delegator leaderboard
78
+ const delegatorLeaderboard = await sdk.global.getLeaderboardDelegators(10, 0);
79
+
80
+ // Get validator leaderboard
81
+ const validatorLeaderboard = await sdk.global.getLeaderboardValidators(10, 0);
82
+ ```
83
+
84
+ ### Validators
85
+
86
+ ```typescript
87
+ // Get all validators
88
+ const allValidators = await sdk.validators.getAll();
89
+
90
+ // Get specific validator details
91
+ const validator = await sdk.validators.get('0x1234...');
92
+
93
+ // Get validator delegators
94
+ const delegators = await sdk.validators.getDelegators('0x1234...');
95
+
96
+ // Get validator stake breakdown
97
+ const stakeBreakdown = await sdk.validators.getStakeBreakdown('0x1234...');
98
+
99
+ // Get validator epoch details
100
+ const epochData = await sdk.validators.getEpoch('0x1234...', 100);
101
+
102
+ // Get validator history
103
+ const history = await sdk.validators.getHistory('0x1234...', 1, 100);
104
+
105
+ // Get validator withdrawals
106
+ const withdrawals = await sdk.validators.getWithdrawals('0x1234...', 50, 0);
107
+
108
+ // Get validator metrics
109
+ const metrics = await sdk.validators.getMetrics('0x1234...');
110
+
111
+ // Get validator slashing events
112
+ const slashing = await sdk.validators.getSlashing('0x1234...');
113
+
114
+ // Get validator APR
115
+ const validatorAPR = await sdk.validators.getAPR('0x1234...');
116
+ ```
117
+
118
+ ### Delegators
119
+
120
+ ```typescript
121
+ // Get all delegators
122
+ const allDelegators = await sdk.delegators.getAll();
123
+
124
+ // Get specific delegator details
125
+ const delegator = await sdk.delegators.get('0xabcd...');
126
+
127
+ // Get delegator stakes breakdown
128
+ const stakes = await sdk.delegators.getStakes('0xabcd...');
129
+
130
+ // Get delegator rewards history
131
+ const rewards = await sdk.delegators.getRewards('0xabcd...', 50, 0);
132
+
133
+ // Get delegator withdrawals
134
+ const withdrawals = await sdk.delegators.getWithdrawals('0xabcd...', 50, 0);
135
+
136
+ // Get delegator unbonding status
137
+ const unbonding = await sdk.delegators.getUnbonding('0xabcd...');
138
+
139
+ // Get delegator active validators
140
+ const validators = await sdk.delegators.getValidators('0xabcd...');
141
+ ```
142
+
143
+ ### Referrals
144
+
145
+ ```typescript
146
+ // Validate a referral code
147
+ const validation = await sdk.referrals.validate('REF123');
148
+
149
+ // Create a new referral code (requires authentication)
150
+ const referralCode = await sdk.referrals.create({
151
+ validator_address: '0x1234...',
152
+ max_quota: 100,
153
+ expires_in_days: 30,
154
+ });
155
+
156
+ // Apply a referral code
157
+ await sdk.referrals.apply({
158
+ referral_code: 'REF123',
159
+ delegator_address: '0xabcd...',
160
+ });
161
+
162
+ // Delete a referral code (requires authentication)
163
+ await sdk.referrals.delete('REF123');
164
+
165
+ // Unlink a delegator from referral (requires authentication)
166
+ await sdk.referrals.unlink('0xabcd...');
167
+
168
+ // Get delegator referral information
169
+ const delegatorRef = await sdk.referrals.getDelegatorReferral('0xabcd...');
170
+
171
+ // Get validator referral information
172
+ const validatorRef = await sdk.referrals.getValidatorReferral('0x1234...');
173
+ ```
174
+
175
+ ### Slashing
176
+
177
+ ```typescript
178
+ // Get all slashing events
179
+ const allEvents = await sdk.slashing.getEvents();
180
+
181
+ // Get slashing events for a specific validator
182
+ const validatorEvents = await sdk.slashing.getEvents('0x1234...', 50, 0);
183
+ ```
184
+
185
+ ### Analytics (Subgraph Data)
186
+
187
+ The Analytics API provides access to aggregated and historical data indexed from the blockchain via The Graph subgraph. This data may have slight delays compared to real-time blockchain queries.
188
+
189
+ ```typescript
190
+ // Get protocol-level statistics
191
+ const protocolStats = await sdk.analytics.getProtocolStats();
192
+ console.log('Total Staking:', protocolStats.TotalStaking);
193
+ console.log('Active Validators:', protocolStats.ActiveValidators);
194
+
195
+ // Check sync status of analytics workers
196
+ const syncStatus = await sdk.analytics.getSyncStatus();
197
+ console.log('Protocol Sync Status:', syncStatus.protocol_sync.status);
198
+ console.log('Last Synced Block:', syncStatus.protocol_sync.last_block);
199
+
200
+ // Get all validators with analytics data (paginated)
201
+ const validators = await sdk.analytics.getAllValidators({
202
+ limit: 20,
203
+ offset: 0,
204
+ status: 'active',
205
+ });
206
+
207
+ // Get top validators by uptime
208
+ const topValidators = await sdk.analytics.getTopValidators(10);
209
+ topValidators.data.forEach((v, i) => {
210
+ console.log(`#${i + 1}: ${v.moniker} - ${v.uptime}% uptime`);
211
+ });
212
+
213
+ // Get specific validator analytics
214
+ const validatorAnalytics = await sdk.analytics.getValidatorAnalytics('0x1234...');
215
+ console.log('Uptime:', validatorAnalytics.uptime);
216
+ console.log('Signed Blocks:', validatorAnalytics.signed_blocks);
217
+ console.log('Total Stakers:', validatorAnalytics.total_stakers);
218
+
219
+ // Get validator rewards with manual pagination (REQUIRED for this endpoint)
220
+ const rewardsPage1 = await sdk.analytics.getValidatorRewards('0x1234...', {
221
+ limit: 50,
222
+ offset: 0,
223
+ });
224
+
225
+ console.log('Total Rewards:', rewardsPage1.summary.total_rewards);
226
+ console.log('Total Stakers:', rewardsPage1.summary.total_stakers);
227
+ console.log('Has More Data:', rewardsPage1.metadata.has_more);
228
+
229
+ // Fetch next page if available
230
+ if (rewardsPage1.metadata.has_more) {
231
+ const rewardsPage2 = await sdk.analytics.getValidatorRewards('0x1234...', {
232
+ limit: 50,
233
+ offset: 50,
234
+ });
235
+ }
236
+
237
+ // Auto-pagination helper (use with caution - makes multiple API calls)
238
+ const allRewards = await sdk.analytics.getAllValidatorRewards('0x1234...', {
239
+ batchSize: 50,
240
+ maxPages: 10, // Safety limit
241
+ });
242
+
243
+ console.log('Total Stakes Fetched:', allRewards.stakes.length);
244
+ ```
245
+
246
+ **Important Notes:**
247
+ - Analytics data is sourced from subgraph indexing and may lag behind real-time blockchain state
248
+ - Always check `metadata.cached` and `metadata.stale` flags in responses
249
+ - The rewards endpoint is heavy and **requires pagination** - never fetch without limit/offset
250
+ - Use `getSyncStatus()` to verify data freshness before making critical decisions
251
+
252
+ ## Advanced Usage
253
+
254
+ ### Custom Headers
255
+
256
+ ```typescript
257
+ const sdk = new ResonanceSDK({
258
+ apiUrl: 'https://api.resonance.network',
259
+ headers: {
260
+ 'X-Custom-Header': 'value',
261
+ },
262
+ });
263
+
264
+ // Or set headers after initialization
265
+ sdk.setHeader('X-API-Key', 'your-api-key');
266
+ ```
267
+
268
+ ### Error Handling
269
+
270
+ ```typescript
271
+ try {
272
+ const validator = await sdk.validators.get('0x1234...');
273
+ } catch (error) {
274
+ if (error instanceof Error) {
275
+ console.error('API Error:', error.message);
276
+ }
277
+ }
278
+ ```
279
+
280
+ ### Timeout Configuration
281
+
282
+ ```typescript
283
+ const sdk = new ResonanceSDK({
284
+ apiUrl: 'https://api.resonance.network',
285
+ timeout: 60000, // 60 seconds
286
+ });
287
+ ```
288
+
289
+ ## TypeScript Support
290
+
291
+ The SDK is written in TypeScript and provides full type definitions:
292
+
293
+ ```typescript
294
+ import type {
295
+ ValidatorDetailResponse,
296
+ DelegatorDetailResponse,
297
+ GlobalNetworkResponse,
298
+ } from '@avenbreaks/resonance-sdk';
299
+
300
+ const processValidator = (validator: ValidatorDetailResponse) => {
301
+ console.log(validator.validator_address);
302
+ console.log(validator.total_stake);
303
+ };
304
+ ```
305
+
306
+ ## React Example
307
+
308
+ ```typescript
309
+ import { useEffect, useState } from 'react';
310
+ import { ResonanceSDK } from '@avenbreaks/resonance-sdk';
311
+
312
+ const sdk = new ResonanceSDK({
313
+ apiUrl: 'https://api.resonance.network',
314
+ });
315
+
316
+ function ValidatorList() {
317
+ const [validators, setValidators] = useState([]);
318
+ const [loading, setLoading] = useState(true);
319
+
320
+ useEffect(() => {
321
+ const fetchValidators = async () => {
322
+ try {
323
+ const data = await sdk.validators.getAll();
324
+ setValidators(data);
325
+ } catch (error) {
326
+ console.error('Failed to fetch validators:', error);
327
+ } finally {
328
+ setLoading(false);
329
+ }
330
+ };
331
+
332
+ fetchValidators();
333
+ }, []);
334
+
335
+ if (loading) return <div>Loading...</div>;
336
+
337
+ return (
338
+ <div>
339
+ {validators.map((validator) => (
340
+ <div key={validator.address}>{validator.address}</div>
341
+ ))}
342
+ </div>
343
+ );
344
+ }
345
+ ```
346
+
347
+ ## Next.js Example
348
+
349
+ ```typescript
350
+ // app/page.tsx
351
+ import { ResonanceSDK } from '@avenbreaks/resonance-sdk';
352
+
353
+ const sdk = new ResonanceSDK({
354
+ apiUrl: process.env.NEXT_PUBLIC_API_URL || 'https://api.resonance.network',
355
+ });
356
+
357
+ export default async function HomePage() {
358
+ const stats = await sdk.global.getStats();
359
+
360
+ return (
361
+ <div>
362
+ <h1>Network Stats</h1>
363
+ <p>Total Validators: {stats.total_validators}</p>
364
+ <p>Total Delegators: {stats.total_delegators}</p>
365
+ <p>Total Stake: {stats.total_network_stake}</p>
366
+ </div>
367
+ );
368
+ }
369
+ ```
370
+
371
+ ## Node.js Example
372
+
373
+ ```typescript
374
+ import { ResonanceSDK } from '@avenbreaks/resonance-sdk';
375
+
376
+ const sdk = new ResonanceSDK({
377
+ apiUrl: 'https://api.resonance.network',
378
+ });
379
+
380
+ async function main() {
381
+ // Get network statistics
382
+ const stats = await sdk.global.getStats();
383
+ console.log('Network Stats:', stats);
384
+
385
+ // Get validator leaderboard
386
+ const leaderboard = await sdk.global.getLeaderboardValidators(10);
387
+ console.log('Top 10 Validators:', leaderboard);
388
+ }
389
+
390
+ main().catch(console.error);
391
+ ```
392
+
393
+ ## API Endpoints
394
+
395
+ All API endpoints are available under the `/eth/v1` prefix. The SDK handles this automatically.
396
+
397
+ | Module | Endpoint Pattern | Description |
398
+ |--------|-----------------|-------------|
399
+ | Global | `/eth/v1/global` | Network statistics and leaderboards |
400
+ | Validators | `/eth/v1/validators/:address` | Validator information and history |
401
+ | Delegators | `/eth/v1/delegators/:address` | Delegator information and history |
402
+ | Referrals | `/eth/v1/referrals` | Referral code management |
403
+ | Slashing | `/eth/v1/slashing/events` | Slashing events |
404
+
405
+ ## Development
406
+
407
+ ```bash
408
+ # Install dependencies
409
+ pnpm install
410
+
411
+ # Build the SDK
412
+ pnpm build
413
+
414
+ # Run type checking
415
+ pnpm type-check
416
+
417
+ # Watch mode (for development)
418
+ pnpm dev
419
+ ```
420
+
421
+ ## License
422
+
423
+ MIT
424
+
425
+ ## Support
426
+
427
+ For issues and questions, please visit:
428
+ - GitHub Issues: https://github.com/fenelabs/sdk/issues
429
+ - Documentation: https://docs.fene.network