-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdata-api.ts
More file actions
1903 lines (1709 loc) · 68.3 KB
/
Copy pathdata-api.ts
File metadata and controls
1903 lines (1709 loc) · 68.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
TokenDetailResponse,
MultiTokensResponse,
TokenHoldersResponse,
TopHolder,
AthPrice,
BundlersResponse,
DeployerTokensResponse,
DeployerParams,
SearchParams,
SearchResponse,
TokenOverview,
PriceData,
PriceHistoryData,
PriceTimestampData,
PriceRangeData,
MultiPriceResponse,
WalletBasicResponse,
TradesResponse,
TradeParams,
TradeHistoryResponse,
TradeEvents,
TradeEventFor,
TradeEvent,
EnrichedTrade,
WalletResponse,
ChartResponse,
HoldersChartResponse,
SnipersChartResponse,
InsidersChartResponse,
BundlersChartResponse,
PnLResponse,
TokenPnLResponse,
FirstBuyerData,
TopTradersResponse,
TokenStats,
WalletChartResponse,
CreditsResponse,
WalletTradesResponse,
ProcessedEvent,
SubscriptionResponse,
ChartDataParams,
PaginatedTokenHoldersResponse,
PnlV2KOLLeaderboardParams,
PnlV2KOLLeaderboardResponse,
PnlV2KOLPeriodParams,
PnlV2KOLPeriodResponse,
PnlV2KOLCalendarParams,
PnlV2KOLCalendarResponse,
PnlV2KOLByDateParams,
PnlV2KOLByDateResponse,
PnlV2TopTradersParams,
PnlV2TopTradersResponse,
PnlV2TokenTradersParams,
PnlV2TokenTradersResponse,
PnlV2TokenFirstBuyersParams,
PnlV2WalletHistoryParams,
PnlV2WalletHistoryResponse,
PnlV2WalletPerformanceParams,
PnlV2WalletPerformanceResponse,
PnlV2WalletTokenPositionResponse,
PnlV2WalletHighlightsResponse,
PnlV2WalletRiskResponse,
PnlV2WalletPositionsParams,
PnlV2WalletPositionsResponse,
PnlV2WalletChartParams,
PnlV2WalletChartResponse,
PnlV2WalletOverviewParams,
PnlV2WalletOverviewResponse,
PnlV2WalletTokenPositionParams,
PnlV2BatchWalletPositionsResponse,
PnlV2BatchWalletSummariesResponse,
PnlV2BatchTokenPositionsResponse,
PnlV2BatchPositionPairsResponse,
PnlV2BatchParams,
PnlV2WalletQueued,
DcaListParams,
DcaProgramParams,
DcaProgramsResponse,
DcaWalletResponse,
DcaOrdersListResponse,
DcaOrder,
DcaTokenFlowResponse,
DcaTokenOrdersResponse,
DcaTokenUsersResponse,
DcaPairResponse,
LighthouseResponse,
WhaleTradesParams,
KolTradesParams,
KolTokenTradesParams,
WhaleKolTradesResponse,
WhaleMinVolume,
} from './interfaces';
import { decodeBinaryEvents } from './event-processor';
export class DataApiError extends Error {
public details?: any;
constructor(
message: string,
public status?: number,
public code?: string,
details?: any
) {
super(message);
this.name = 'DataApiError';
this.details = details;
}
}
export class RateLimitError extends DataApiError {
constructor(message: string, public retryAfter?: number, details?: any) {
super(message, 429, 'RATE_LIMIT_EXCEEDED', details);
this.name = 'RateLimitError';
}
}
export class ValidationError extends DataApiError {
constructor(message: string, details?: any) {
super(message, 400, 'VALIDATION_ERROR', details);
this.name = 'ValidationError';
}
}
/**
* Config options for the Solana Tracker Data API
*/
export interface DataApiConfig {
/** Your API key from solanatracker.io */
apiKey: string;
/** Optional base URL override */
baseUrl?: string;
}
export interface RequestOptions {
method: string;
body?: any;
/** Optional headers to include in the request */
headers?: Record<string, string>;
/** Disable logs for rate limit warnings */
disableLogs?: boolean;
}
/**
* Parameters for token overview endpoint (/tokens/multi/all)
*/
export interface TokenOverviewParams {
/** Number of tokens per category (default: 100, max: 500) */
limit?: number;
/** Minimum curve percentage for graduating tokens (default: 40) */
minCurve?: number;
/** Minimum number of holders for graduating tokens (default: 20) */
minHolders?: number;
/** Maximum number of holders for graduating tokens */
maxHolders?: number;
/** Reduce spam by filtering out quick graduated tokens */
reduceSpam?: boolean;
// Filters from buildWhereClause
minLiquidity?: number;
maxLiquidity?: number;
minMarketCap?: number;
maxMarketCap?: number;
markets?: string[];
minRiskScore?: number;
maxRiskScore?: number;
rugged?: boolean;
}
/**
* Parameters for graduated tokens endpoint (/tokens/multi/graduated)
*/
export interface GraduatedTokensParams {
/** Number of tokens to return (default: 100, max: 500) */
limit?: number;
/** Page number for pagination (default: 1) */
page?: number;
/** Reduce spam by filtering out quick graduated tokens */
reduceSpam?: boolean;
// Filters from buildWhereClause
minLiquidity?: number;
maxLiquidity?: number;
minMarketCap?: number;
maxMarketCap?: number;
markets?: string[];
minRiskScore?: number;
maxRiskScore?: number;
rugged?: boolean;
}
/**
* Parameters for graduating tokens endpoint (/tokens/multi/graduating)
*/
export interface GraduatingTokensParams {
/** Number of tokens to return (default: 100, max: 500) */
limit?: number;
/** Minimum curve percentage (default: 40) */
minCurve?: number;
/** Maximum curve percentage (default: 100) */
maxCurve?: number;
/** Minimum number of holders (default: 20) */
minHolders?: number;
/** Maximum number of holders */
maxHolders?: number;
// Filters from buildWhereClause
minLiquidity?: number;
maxLiquidity?: number;
minMarketCap?: number;
maxMarketCap?: number;
markets?: string[];
minRiskScore?: number;
maxRiskScore?: number;
rugged?: boolean;
}
/**
* Solana Tracker Data API client
*/
export class Client {
private apiKey: string;
private baseUrl: string;
/**
* Creates a new instance of the Solana Tracker Data API client
* @param config Configuration options including API key
*/
constructor(config: DataApiConfig) {
this.apiKey = config.apiKey;
this.baseUrl = config.baseUrl || 'https://data.solanatracker.io';
}
/**
* Makes a request to the API
* @param endpoint The API endpoint
* @param options Additional fetch options
* @returns The API response
*/
private async request<T>(endpoint: string, options?: RequestOptions): Promise<T> {
const headers = {
'x-api-key': this.apiKey,
'Content-Type': 'application/json',
...options?.headers,
};
try {
// Match PredictionMarketsClient and the declared Node 14+ support.
const fetchImpl: typeof fetch = typeof globalThis.fetch === 'function'
? globalThis.fetch.bind(globalThis)
: ((await import('node-fetch')).default as unknown as typeof fetch);
const response = await fetchImpl(`${this.baseUrl}${endpoint}`, {
...options,
headers,
});
if (!response.ok) {
// Default error message
let errorMessage = `API request failed: ${response.status} ${response.statusText}`;
let errorDetails: any = null;
try {
// Attempt to parse error response as JSON
const contentType = response.headers.get('content-type');
if (contentType && contentType.includes('application/json')) {
errorDetails = await response.json();
// Extract error message from various possible fields
if (typeof errorDetails === 'string') {
errorMessage = errorDetails;
} else if (errorDetails && typeof errorDetails === 'object') {
// Try different common error message fields
if (typeof errorDetails.message === 'string') {
errorMessage = errorDetails.message;
} else if (typeof errorDetails.error === 'string') {
errorMessage = errorDetails.error;
} else if (typeof errorDetails.detail === 'string') {
errorMessage = errorDetails.detail;
} else if (typeof errorDetails.msg === 'string') {
errorMessage = errorDetails.msg;
} else if (errorDetails.error && typeof errorDetails.error === 'object') {
// If error is an object, try to extract message from it
if (typeof errorDetails.error.message === 'string') {
errorMessage = errorDetails.error.message;
} else if (typeof errorDetails.error.detail === 'string') {
errorMessage = errorDetails.error.detail;
} else {
// If we can't find a string message, stringify the error object
errorMessage = `API error: ${JSON.stringify(errorDetails.error)}`;
}
} else {
// Last resort: stringify the entire error response
errorMessage = `API error: ${JSON.stringify(errorDetails)}`;
}
}
}
} catch (parseError) {
// If parsing fails, we'll use the default error message
console.error('Failed to parse error response:', parseError);
}
// Handle specific error codes
if (response.status === 429) {
const retryAfter = response.headers.get('Retry-After');
if (!options?.disableLogs) {
console.warn(`Rate limit exceeded for ${endpoint}. Retry after: ${retryAfter || '1'} seconds`);
}
const error = new RateLimitError(errorMessage, retryAfter ? parseInt(retryAfter) : undefined);
// Attach error details if available
if (errorDetails) {
(error as any).details = errorDetails;
}
throw error;
}
// For all other errors (including 500)
const error = new DataApiError(errorMessage, response.status);
// Attach error details if available
if (errorDetails) {
(error as any).details = errorDetails;
}
throw error;
}
const data = await response.json();
return this.normalizeLegacyRiskFields(data) as T;
} catch (error) {
if (error instanceof DataApiError) {
throw error;
}
// For network errors or other unexpected errors
throw new DataApiError(`An unexpected error occurred: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
/**
* Preserve the 0.3.x risk response surface while using the corrected wire
* field names. The server now returns `wallet` and may omit `bundlers`.
*/
private normalizeLegacyRiskFields(value: unknown): unknown {
if (Array.isArray(value)) {
value.forEach((item) => this.normalizeLegacyRiskFields(item));
return value;
}
if (!value || typeof value !== 'object') {
return value;
}
const record = value as Record<string, unknown>;
const isTokenRisk =
Array.isArray(record.risks) &&
record.snipers !== null &&
typeof record.snipers === 'object' &&
record.insiders !== null &&
typeof record.insiders === 'object';
if (isTokenRisk) {
for (const categoryName of ['snipers', 'insiders'] as const) {
const category = record[categoryName] as Record<string, unknown>;
if (Array.isArray(category.wallets)) {
for (const walletValue of category.wallets) {
if (walletValue && typeof walletValue === 'object') {
const wallet = walletValue as Record<string, unknown>;
if (typeof wallet.wallet === 'string' && wallet.address === undefined) {
wallet.address = wallet.wallet;
}
}
}
}
}
if (record.bundlers === undefined) {
record.bundlers = {
count: 0,
totalBalance: 0,
totalPercentage: 0,
totalInitialBalance: 0,
totalInitialPercentage: 0,
wallets: [],
};
}
}
Object.values(record).forEach((item) => this.normalizeLegacyRiskFields(item));
return value;
}
/**
* Validates a Solana public key
* @param address The address to validate
* @param paramName The parameter name for error messaging
* @throws ValidationError if the address is invalid
*/
private validatePublicKey(address: string, paramName: string) {
// Basic validation - a more robust implementation would use the PublicKey class from @solana/web3.js
if (!address || !/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(address)) {
throw new ValidationError(`Invalid ${paramName}: ${address}`);
}
}
/**
* Builds query string from parameters object
* @param params Parameters object
* @returns Query string
*/
private buildQueryString(params: Record<string, any>): string {
const queryParams = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value !== undefined && value !== null) {
// Handle arrays - convert to comma-separated string
if (Array.isArray(value)) {
queryParams.append(key, value.join(','));
} else {
queryParams.append(key, value.toString());
}
}
}
const query = queryParams.toString();
return query ? `?${query}` : '';
}
// ======== TOKEN ENDPOINTS ========
/**
* Get comprehensive information about a specific token
* @param tokenAddress The token's mint address
* @returns Detailed token information
*/
async getTokenInfo(tokenAddress: string): Promise<TokenDetailResponse> {
this.validatePublicKey(tokenAddress, 'tokenAddress');
return this.request<TokenDetailResponse>(`/tokens/${tokenAddress}`);
}
/**
* Get token information by searching with a pool address
* @param poolAddress The pool address
* @returns Detailed token information
*/
async getTokenByPool(poolAddress: string): Promise<TokenDetailResponse> {
this.validatePublicKey(poolAddress, 'poolAddress');
return this.request<TokenDetailResponse>(`/tokens/by-pool/${poolAddress}`);
}
/**
* Get token holders information
* @param tokenAddress The token's mint address
* @returns Information about token holders
*/
async getTokenHolders(tokenAddress: string, enrich?: 'identity' | 'walletPnl' | 'identity,walletPnl' | 'all' | '*'): Promise<TokenHoldersResponse> {
this.validatePublicKey(tokenAddress, 'tokenAddress');
const qs = enrich ? this.buildQueryString({ enrich }) : '';
return this.request<TokenHoldersResponse>(`/tokens/${tokenAddress}/holders${qs}`);
}
/**
* Get token holders with pagination support
* @param tokenAddress The token's mint address
* @param limit Number of holders to return per page (default: 100, max: 100)
* @param cursor Pagination cursor from previous response
* @returns Paginated token holders information
*/
async getTokenHoldersPaginated(
tokenAddress: string,
limit?: number,
cursor?: string
): Promise<PaginatedTokenHoldersResponse> {
this.validatePublicKey(tokenAddress, 'tokenAddress');
const params = new URLSearchParams();
if (limit) {
if (limit > 5000) {
throw new ValidationError('Maximum limit is 5000');
}
params.append('limit', limit.toString());
}
if (cursor) params.append('cursor', cursor);
const query = params.toString() ? `?${params.toString()}` : '';
return this.request<PaginatedTokenHoldersResponse>(
`/tokens/${tokenAddress}/holders/paginated${query}`
);
}
/**
* Get top 20 token holders
* @param tokenAddress The token's mint address
* @returns Top holders information
*/
async getTopHolders(tokenAddress: string): Promise<TopHolder[]> {
this.validatePublicKey(tokenAddress, 'tokenAddress');
return this.request<TopHolder[]>(`/tokens/${tokenAddress}/holders/top`);
}
/**
* Get the all-time high price and market cap for a token
* @param tokenAddress The token's mint address
* @returns All-time high price and market cap data
*/
async getAthPrice(tokenAddress: string): Promise<AthPrice> {
this.validatePublicKey(tokenAddress, 'tokenAddress');
return this.request<AthPrice>(`/tokens/${tokenAddress}/ath`);
}
/**
* Get bundler information for a token
* @param tokenAddress The token's mint address
* @returns Bundler wallet stats including top 500 bundler wallets
*/
async getTokenBundlers(tokenAddress: string): Promise<BundlersResponse> {
this.validatePublicKey(tokenAddress, 'tokenAddress');
return this.request<BundlersResponse>(`/tokens/${tokenAddress}/bundlers`);
}
/**
* Get tokens created by a specific wallet with pagination
* @param wallet The deployer wallet address
* @param pageOrParams Page number (legacy) or DeployerParams object
* @param limit Number of items per page when using legacy positional args
* @returns List of tokens created by the deployer (TokenDetailResponse items when format=full)
*/
async getTokensByDeployer(
wallet: string,
params: DeployerParams & { format: 'full' }
): Promise<DeployerTokensResponse<TokenDetailResponse>>;
async getTokensByDeployer(
wallet: string,
pageOrParams?: number | DeployerParams,
limit?: number
): Promise<DeployerTokensResponse>;
async getTokensByDeployer(
wallet: string,
pageOrParams?: number | DeployerParams,
limit?: number
): Promise<DeployerTokensResponse | DeployerTokensResponse<TokenDetailResponse>> {
this.validatePublicKey(wallet, 'wallet');
let deployerParams: Record<string, any> = {};
if (typeof pageOrParams === 'number') {
if (pageOrParams) deployerParams.page = pageOrParams;
if (limit) deployerParams.limit = limit;
} else if (pageOrParams) {
deployerParams = { ...pageOrParams };
}
const query = this.buildQueryString(deployerParams);
return this.request(`/deployer/${wallet}${query}`);
}
/**
* Search for tokens with flexible filtering options
* @param params Search parameters and filters
* @returns Search results (TokenDetailResponse items when format=full)
*/
async searchTokens(params: SearchParams & { format: 'full' }): Promise<SearchResponse<TokenDetailResponse>>;
async searchTokens(params: SearchParams): Promise<SearchResponse>;
async searchTokens(params: SearchParams): Promise<SearchResponse | SearchResponse<TokenDetailResponse>> {
return this.request<SearchResponse>(`/search${this.buildQueryString(params)}`);
}
/**
* Get the latest tokens
* @param page Page number (1-10)
* @returns List of latest tokens
*/
async getLatestTokens(page: number = 1): Promise<TokenDetailResponse[]> {
if (page < 1 || page > 10) {
throw new ValidationError('Page must be between 1 and 10');
}
return this.request<TokenDetailResponse[]>(`/tokens/latest?page=${page}`);
}
/**
* Get information about multiple tokens
* @param tokenAddresses Array of token addresses
* @returns Information about multiple tokens
*/
async getMultipleTokens(tokenAddresses: string[]): Promise<MultiTokensResponse> {
if (tokenAddresses.length > 20) {
throw new ValidationError('Maximum of 20 tokens per request');
}
tokenAddresses.forEach((addr) => this.validatePublicKey(addr, 'tokenAddress'));
return this.request<MultiTokensResponse>('/tokens/multi', {
method: 'POST',
body: JSON.stringify({ tokens: tokenAddresses }),
});
}
/**
* Get trending tokens
* @param timeframe Optional timeframe for trending calculation
* @returns List of trending tokens
*/
async getTrendingTokens(timeframe?: string): Promise<TokenDetailResponse[]> {
const validTimeframes = ['5m', '15m', '30m', '1h', '2h', '3h', '4h', '5h', '6h', '12h', '24h'];
if (timeframe && !validTimeframes.includes(timeframe)) {
throw new ValidationError(`Invalid timeframe. Must be one of: ${validTimeframes.join(', ')}`);
}
const endpoint = timeframe ? `/tokens/trending/${timeframe}` : '/tokens/trending';
return this.request<TokenDetailResponse[]>(endpoint);
}
/**
* Get top performing tokens by price change percentage
* @param timeframe Timeframe for performance calculation (5m, 15m, 30m, 1h, 6h, 12h, 24h)
* @returns List of top performing tokens
*/
async getTopPerformers(timeframe: string): Promise<TokenDetailResponse[]> {
const validTimeframes = ['5m', '15m', '30m', '1h', '6h', '12h', '24h'];
if (!validTimeframes.includes(timeframe)) {
throw new ValidationError(`Invalid timeframe. Must be one of: ${validTimeframes.join(', ')}`);
}
return this.request<TokenDetailResponse[]>(`/top-performers/${timeframe}`);
}
/**
* Get tokens sorted by volume
* @param timeframe Optional timeframe for volume calculation
* @returns List of tokens sorted by volume
*/
async getTokensByVolume(timeframe?: string): Promise<TokenDetailResponse[]> {
const validTimeframes = ['5m', '15m', '30m', '1h', '6h', '12h', '24h'];
if (timeframe && !validTimeframes.includes(timeframe)) {
throw new ValidationError(`Invalid timeframe. Must be one of: ${validTimeframes.join(', ')}`);
}
const endpoint = timeframe ? `/tokens/volume/${timeframe}` : '/tokens/volume';
return this.request<TokenDetailResponse[]>(endpoint);
}
/**
* Get an overview of latest, graduating, and graduated tokens
* @param limit Number of tokens per category (or params object)
* @returns Token overview (Memescope / Pumpvision style)
*/
async getTokenOverview(limit?: number): Promise<TokenOverview>;
async getTokenOverview(params?: TokenOverviewParams): Promise<TokenOverview>;
async getTokenOverview(limitOrParams?: number | TokenOverviewParams): Promise<TokenOverview> {
let params: TokenOverviewParams | undefined;
if (typeof limitOrParams === 'number') {
params = { limit: limitOrParams };
} else {
params = limitOrParams;
}
if (params?.limit !== undefined && (!Number.isInteger(params.limit) || params.limit <= 0)) {
throw new ValidationError('Limit must be a positive integer');
}
if (params?.limit !== undefined && params.limit > 500) {
throw new ValidationError('Maximum limit is 500');
}
const query = params ? this.buildQueryString(params) : '';
return this.request<TokenOverview>(`/tokens/multi/all${query}`);
}
/**
* Get graduated tokens
* @param params Optional parameters including limit, page, and filters
* @returns List of graduated tokens
*/
async getGraduatedTokens(): Promise<TokenDetailResponse[]>;
async getGraduatedTokens(params?: GraduatedTokensParams): Promise<TokenDetailResponse[]>;
async getGraduatedTokens(params?: GraduatedTokensParams): Promise<TokenDetailResponse[]> {
if (params?.limit !== undefined && (!Number.isInteger(params.limit) || params.limit <= 0)) {
throw new ValidationError('Limit must be a positive integer');
}
if (params?.limit !== undefined && params.limit > 500) {
throw new ValidationError('Maximum limit is 500');
}
if (params?.page !== undefined && (!Number.isInteger(params.page) || params.page < 1)) {
throw new ValidationError('Page must be a positive integer');
}
const query = params ? this.buildQueryString(params) : '';
return this.request<TokenDetailResponse[]>(`/tokens/multi/graduated${query}`);
}
/**
* Get graduating tokens
* @param params Optional parameters including limit, curve percentages, holders, and filters
* @returns List of graduating tokens
*/
async getGraduatingTokens(): Promise<TokenDetailResponse[]>;
async getGraduatingTokens(params?: GraduatingTokensParams): Promise<TokenDetailResponse[]>;
async getGraduatingTokens(params?: GraduatingTokensParams): Promise<TokenDetailResponse[]> {
if (params?.limit !== undefined && (!Number.isInteger(params.limit) || params.limit <= 0)) {
throw new ValidationError('Limit must be a positive integer');
}
if (params?.limit !== undefined && params.limit > 500) {
throw new ValidationError('Maximum limit is 500');
}
if (params?.minCurve !== undefined && (params.minCurve < 0 || params.minCurve > 100)) {
throw new ValidationError('minCurve must be between 0 and 100');
}
if (params?.maxCurve !== undefined && (params.maxCurve < 0 || params.maxCurve > 100)) {
throw new ValidationError('maxCurve must be between 0 and 100');
}
if (params?.minCurve !== undefined && params?.maxCurve !== undefined && params.minCurve > params.maxCurve) {
throw new ValidationError('minCurve must be less than or equal to maxCurve');
}
const query = params ? this.buildQueryString(params) : '';
return this.request<TokenDetailResponse[]>(`/tokens/multi/graduating${query}`);
}
// ======== PRICE ENDPOINTS ========
/**
* Get price information for a token
* @param tokenAddress The token's mint address
* @param priceChanges Include price change percentages
* @returns Price data
*/
async getPrice(tokenAddress: string, priceChanges?: boolean): Promise<PriceData> {
this.validatePublicKey(tokenAddress, 'tokenAddress');
const query = priceChanges ? '&priceChanges=true' : '';
return this.request<PriceData>(`/price?token=${tokenAddress}${query}`);
}
/**
* Get historic price information for a token
* @param tokenAddress The token's mint address
* @returns Historic price data
*/
async getPriceHistory(tokenAddress: string): Promise<PriceHistoryData> {
this.validatePublicKey(tokenAddress, 'tokenAddress');
return this.request<PriceHistoryData>(`/price/history?token=${tokenAddress}`);
}
/**
* Get price at a specific timestamp
* @param tokenAddress The token's mint address
* @param timestamp Unix timestamp
* @returns Price at the specified timestamp
*/
async getPriceAtTimestamp(tokenAddress: string, timestamp: number): Promise<PriceTimestampData> {
this.validatePublicKey(tokenAddress, 'tokenAddress');
return this.request<PriceTimestampData>(`/price/history/timestamp?token=${tokenAddress}×tamp=${timestamp}`);
}
/**
* Get lowest and highest price in a time range
* @param tokenAddress The token's mint address
* @param timeFrom Start time (unix timestamp)
* @param timeTo End time (unix timestamp)
* @returns Price range data
*/
async getPriceRange(tokenAddress: string, timeFrom: number, timeTo: number): Promise<PriceRangeData> {
this.validatePublicKey(tokenAddress, 'tokenAddress');
return this.request<PriceRangeData>(`/price/history/range?token=${tokenAddress}&time_from=${timeFrom}&time_to=${timeTo}`);
}
/**
* Get price information for a token (POST method)
* @param tokenAddress The token's mint address
* @param priceChanges Include price change percentages
* @returns Price data
*/
async postPrice(tokenAddress: string, priceChanges?: boolean): Promise<PriceData> {
this.validatePublicKey(tokenAddress, 'tokenAddress');
return this.request<PriceData>('/price', {
method: 'POST',
body: JSON.stringify({
token: tokenAddress,
priceChanges: priceChanges || false
})
});
}
/**
* Get price information for multiple tokens
* @param tokenAddresses Array of token addresses
* @param priceChanges Include price change percentages
* @returns Price data for multiple tokens
*/
async getMultiplePrices(tokenAddresses: string[], priceChanges?: boolean): Promise<MultiPriceResponse> {
if (tokenAddresses.length > 100) {
throw new ValidationError('Maximum of 100 tokens per request');
}
tokenAddresses.forEach((addr) => this.validatePublicKey(addr, 'tokenAddress'));
const query = priceChanges ? '&priceChanges=true' : '';
return this.request<MultiPriceResponse>(`/price/multi?tokens=${tokenAddresses.join(',')}${query}`);
}
/**
* Get price information for multiple tokens (POST method)
* @param tokenAddresses Array of token addresses
* @param priceChanges Include price change percentages
* @returns Price data for multiple tokens
*/
async postMultiplePrices(tokenAddresses: string[], priceChanges?: boolean): Promise<MultiPriceResponse> {
if (tokenAddresses.length > 100) {
throw new ValidationError('Maximum of 100 tokens per request');
}
tokenAddresses.forEach((addr) => this.validatePublicKey(addr, 'tokenAddress'));
return this.request<MultiPriceResponse>('/price/multi', {
method: 'POST',
body: JSON.stringify({
tokens: tokenAddresses,
priceChanges: priceChanges || false
})
});
}
// ======== WALLET ENDPOINTS ========
/**
* Get basic wallet information
* @param owner Wallet address
* @returns Basic wallet data
*/
async getWalletBasic(owner: string): Promise<WalletBasicResponse> {
this.validatePublicKey(owner, 'owner');
return this.request<WalletBasicResponse>(`/wallet/${owner}/basic`);
}
/**
* Get all tokens in a wallet
* @param owner Wallet address
* @returns Detailed wallet data
*/
async getWallet(owner: string): Promise<WalletResponse> {
this.validatePublicKey(owner, 'owner');
return this.request<WalletResponse>(`/wallet/${owner}`);
}
/**
* Get wallet tokens with pagination
* @param owner Wallet address
* @param page Page number
* @returns Paginated wallet data
*/
async getWalletPage(owner: string, page: number): Promise<WalletResponse> {
this.validatePublicKey(owner, 'owner');
return this.request<WalletResponse>(`/wallet/${owner}/page/${page}`);
}
/**
* Get wallet portfolio chart data with PnL information
* @param wallet Wallet address
* @returns Wallet chart data with historical values and PnL
* @throws DataApiError if no data found for the wallet
*/
async getWalletChart(wallet: string): Promise<WalletChartResponse> {
this.validatePublicKey(wallet, 'wallet');
return this.request<WalletChartResponse>(`/wallet/${wallet}/chart`);
}
/**
* Get wallet trades
* @param owner Wallet address
* @param cursor Pagination cursor
* @param showMeta Include token metadata
* @param parseJupiter Parse Jupiter swaps
* @param hideArb Hide arbitrage transactions
* @returns Wallet trades data
*/
async getWalletTrades(
owner: string,
cursor?: number,
showMeta?: boolean,
parseJupiter?: boolean,
hideArb?: boolean
): Promise<WalletTradesResponse> {
this.validatePublicKey(owner, 'owner');
const params = new URLSearchParams();
if (cursor) params.append('cursor', cursor.toString());
if (showMeta) params.append('showMeta', 'true');
if (parseJupiter) params.append('parseJupiter', 'true');
if (hideArb) params.append('hideArb', 'true');
const query = params.toString() ? `?${params.toString()}` : '';
return this.request<WalletTradesResponse>(`/wallet/${owner}/trades${query}`);
}
/** Validate filters for the opt-in activity history methods. */
private buildTradeQuery(params: TradeParams = {}): string {
if (params.limit !== undefined &&
(!Number.isInteger(params.limit) || params.limit < 1 || params.limit > 500)) {
throw new ValidationError('limit must be an integer between 1 and 500');
}
if (params.events !== undefined && !['trades', 'all', 'liquidity'].includes(params.events)) {
throw new ValidationError('events must be trades, all, or liquidity');
}
if (params.sortDirection !== undefined && !['ASC', 'DESC'].includes(params.sortDirection)) {
throw new ValidationError('sortDirection must be ASC or DESC');
}
return this.buildQueryString(params);
}
// ======== TRADE ENDPOINTS ========
/**
* Get trades for a token
* @param tokenAddress Token address
* @param cursor Pagination cursor
* @param showMeta Include token metadata
* @param parseJupiter Parse Jupiter swaps
* @param hideArb Hide arbitrage transactions
* @returns Token trades data
*/
async getTokenTrades(
tokenAddress: string,
cursor?: number,
showMeta?: boolean,
parseJupiter?: boolean,
hideArb?: boolean
): Promise<TradesResponse> {
this.validatePublicKey(tokenAddress, 'tokenAddress');
const params = new URLSearchParams();
if (cursor) params.append('cursor', cursor.toString());
if (showMeta) params.append('showMeta', 'true');
if (parseJupiter) params.append('parseJupiter', 'true');
if (hideArb) params.append('hideArb', 'true');
const query = params.toString() ? `?${params.toString()}` : '';
return this.request<TradesResponse>(`/trades/${tokenAddress}${query}`);
}
/**
* Get trades for a specific token and pool
* @param tokenAddress Token address
* @param poolAddress Pool address
* @param cursor Pagination cursor
* @param showMeta Include token metadata
* @param parseJupiter Parse Jupiter swaps
* @param hideArb Hide arbitrage transactions
* @returns Pool-specific token trades data
*/
async getPoolTrades(
tokenAddress: string,
poolAddress: string,
cursor?: number,
showMeta?: boolean,
parseJupiter?: boolean,
hideArb?: boolean
): Promise<TradesResponse> {
this.validatePublicKey(tokenAddress, 'tokenAddress');
this.validatePublicKey(poolAddress, 'poolAddress');
const params = new URLSearchParams();
if (cursor) params.append('cursor', cursor.toString());
if (showMeta) params.append('showMeta', 'true');
if (parseJupiter) params.append('parseJupiter', 'true');
if (hideArb) params.append('hideArb', 'true');
const query = params.toString() ? `?${params.toString()}` : '';
return this.request<TradesResponse>(`/trades/${tokenAddress}/${poolAddress}${query}`);
}
/**
* Get trades for a specific token, pool, and wallet
* @param tokenAddress Token address
* @param poolAddress Pool address
* @param owner Wallet address
* @param cursor Pagination cursor
* @param showMeta Include token metadata
* @param parseJupiter Parse Jupiter swaps
* @param hideArb Hide arbitrage transactions
* @returns User-specific pool trades data
*/
async getUserPoolTrades(
tokenAddress: string,
poolAddress: string,
owner: string,
cursor?: number,
showMeta?: boolean,
parseJupiter?: boolean,
hideArb?: boolean
): Promise<TradesResponse> {
this.validatePublicKey(tokenAddress, 'tokenAddress');
this.validatePublicKey(poolAddress, 'poolAddress');
this.validatePublicKey(owner, 'owner');
const params = new URLSearchParams();
if (cursor) params.append('cursor', cursor.toString());
if (showMeta) params.append('showMeta', 'true');
if (parseJupiter) params.append('parseJupiter', 'true');
if (hideArb) params.append('hideArb', 'true');
const query = params.toString() ? `?${params.toString()}` : '';
return this.request<TradesResponse>(`/trades/${tokenAddress}/${poolAddress}/${owner}${query}`);
}
/**