-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathhedera-mirrornode-service.ts
More file actions
623 lines (555 loc) · 17.9 KB
/
hedera-mirrornode-service.ts
File metadata and controls
623 lines (555 loc) · 17.9 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
import type { NetworkService } from '@/core/services/network/network-service.interface';
import type { HederaMirrornodeService } from './hedera-mirrornode-service.interface';
import type {
AccountListItemAPIResponse,
AccountListItemDto,
AccountResponse,
ContractCallRequest,
ContractCallResponse,
ContractInfo,
ExchangeRateResponse,
GetAccountsAPIResponse,
GetAccountsQueryParams,
GetAccountsResponse,
NftInfo,
TokenAirdropsResponse,
TokenBalancesResponse,
TokenInfo,
TopicInfo,
TopicMessage,
TopicMessageQueryParams,
TopicMessagesAPIResponse,
TopicMessagesQueryParams,
TopicMessagesResponse,
TransactionDetailsResponse,
} from './types';
import {
CliError,
ConfigurationError,
NetworkError,
NotFoundError,
} from '@/core/errors';
import { KeyAlgorithm } from '@/core/shared/constants';
import { parseWithSchema } from '@/core/shared/validation/parse-with-schema.zod';
import { handleMirrorNodeErrorResponse } from '@/core/utils/handle-mirror-node-error-response';
import {
AccountAPIResponseSchema,
ContractInfoSchema,
ExchangeRateResponseSchema,
GetAccountsAPIResponseSchema,
NftInfoSchema,
TokenAirdropsResponseSchema,
TokenBalancesResponseSchema,
TokenInfoSchema,
TopicInfoSchema,
TopicMessagesAPIResponseSchema,
TopicMessageSchema,
TransactionDetailsResponseSchema,
} from './schemas';
import { MirrorNodeKeyType, NetworkToBaseUrl } from './types';
export class HederaMirrornodeServiceDefaultImpl implements HederaMirrornodeService {
private static readonly API_PATH = '/api/v1';
private readonly networkService: NetworkService;
constructor(networkService: NetworkService) {
this.networkService = networkService;
}
private getBaseUrl(): string {
const network = this.networkService.getCurrentNetwork();
if (!NetworkToBaseUrl.has(network)) {
throw new ConfigurationError(`Network type ${network} not supported`);
}
return NetworkToBaseUrl.get(network)!;
}
private getApiBaseUrl(): string {
return `${this.getBaseUrl()}${HederaMirrornodeServiceDefaultImpl.API_PATH}`;
}
async getAccountOrThrow(accountId: string): Promise<AccountResponse> {
const account = await this.getAccount(accountId);
if (!account) {
throw new NotFoundError(`Account ${accountId} not found`);
}
return account;
}
async getAccount(accountId: string): Promise<AccountResponse | null> {
const url = `${this.getApiBaseUrl()}/accounts/${accountId}`;
try {
const response = await fetch(url);
if (!response.ok) {
await handleMirrorNodeErrorResponse(
response,
`Failed to fetch account ${accountId}`,
false,
);
return null;
}
const data = parseWithSchema(
AccountAPIResponseSchema,
await response.json(),
`Mirror Node GET /accounts/${accountId}`,
);
if (!data.account) {
throw new NotFoundError(`Account ${accountId} not found`);
}
if (!data.key) {
throw new NotFoundError(
'No key is associated with the specified account.',
);
}
return {
accountId: data.account,
accountPublicKey: data.key.key,
balance: data.balance,
evmAddress: data.evm_address,
keyAlgorithm: this.getKeyAlgorithm(data.key._type),
};
} catch (error) {
if (error instanceof CliError) throw error;
throw new NetworkError(`Failed to fetch account ${accountId}`, {
cause: error,
recoverable: true,
});
}
}
async getAccountTokenBalances(
accountId: string,
tokenId?: string,
): Promise<TokenBalancesResponse> {
const tokenIdParam = tokenId ? `&token.id=${tokenId}` : '';
const url = `${this.getApiBaseUrl()}/accounts/${accountId}/tokens?${tokenIdParam}`;
try {
const response = await fetch(url);
if (!response.ok) {
await handleMirrorNodeErrorResponse(
response,
`Failed to fetch balance for an account ${accountId}`,
true,
`Account ${accountId} not found`,
);
}
return parseWithSchema(
TokenBalancesResponseSchema,
await response.json(),
`Mirror Node GET /accounts/${accountId}/tokens`,
);
} catch (error) {
if (error instanceof CliError) throw error;
throw new NetworkError(
`Failed to fetch token balances for ${accountId}`,
{ cause: error, recoverable: true },
);
}
}
async getAccounts(
queryParams?: GetAccountsQueryParams,
): Promise<GetAccountsResponse> {
const params = queryParams ?? {};
const queryParts: string[] = [];
if (params.accountBalance) {
queryParts.push(
`account.balance=${params.accountBalance.operator}:${params.accountBalance.value}`,
);
}
if (params.accountId) {
queryParts.push(`account.id=${params.accountId}`);
}
if (params.accountPublicKey) {
queryParts.push(`account.publickey=${params.accountPublicKey}`);
}
queryParts.push(`balance=${params.balance ?? false}`);
queryParts.push(`limit=${params.limit ?? 25}`);
queryParts.push(`order=${params.order ?? 'asc'}`);
const queryString = queryParts.join('&');
let url: string | null = `${this.getApiBaseUrl()}/accounts?${queryString}`;
const allAccounts: AccountListItemAPIResponse[] = [];
let fetchedPages = 0;
while (url) {
fetchedPages += 1;
try {
const response = await fetch(url);
if (!response.ok) {
await handleMirrorNodeErrorResponse(
response,
'Failed to get accounts',
false,
);
break;
}
const pagePayload: GetAccountsAPIResponse = parseWithSchema(
GetAccountsAPIResponseSchema,
await response.json(),
`Mirror Node GET /accounts (page ${fetchedPages})`,
);
allAccounts.push(...(pagePayload.accounts ?? []));
if (fetchedPages >= 100) {
break;
}
url = pagePayload.links?.next
? this.getBaseUrl() + pagePayload.links.next
: null;
} catch (error) {
if (error instanceof CliError) throw error;
throw new NetworkError(`Failed to fetch accounts`, {
cause: error,
recoverable: true,
});
}
}
const accounts: AccountListItemDto[] = allAccounts.map((a) =>
this.mapAccountToDto(a),
);
return { accounts };
}
private mapAccountToDto(
apiAccount: AccountListItemAPIResponse,
): AccountListItemDto {
const dto: AccountListItemDto = {
accountId: apiAccount.account,
createdTimestamp: apiAccount.created_timestamp,
};
if (apiAccount.alias != null) dto.alias = apiAccount.alias;
if (apiAccount.deleted !== undefined) dto.deleted = apiAccount.deleted;
if (apiAccount.memo !== undefined) dto.memo = apiAccount.memo;
if (apiAccount.evm_address !== undefined)
dto.evmAddress = apiAccount.evm_address;
if (apiAccount.balance) {
dto.balance = {
timestamp: apiAccount.balance.timestamp,
balance: apiAccount.balance.balance,
};
if (apiAccount.balance.tokens) {
dto.balance.tokens = apiAccount.balance.tokens.map((t) => ({
tokenId: t.token_id,
balance: t.balance,
}));
}
}
if (apiAccount.key && apiAccount.key.key) {
dto.accountPublicKey = apiAccount.key.key;
dto.keyAlgorithm = this.getKeyAlgorithm(apiAccount.key._type);
}
return dto;
}
async getTopicMessage(
queryParams: TopicMessageQueryParams,
): Promise<TopicMessage> {
const url = `${this.getApiBaseUrl()}/topics/${queryParams.topicId}/messages/${queryParams.sequenceNumber}`;
try {
const response = await fetch(url);
if (!response.ok) {
await handleMirrorNodeErrorResponse(
response,
`Failed to get topic message for ${queryParams.topicId}`,
true,
`Topic message ${queryParams.sequenceNumber} not found for topic ${queryParams.topicId}`,
);
}
return parseWithSchema(
TopicMessageSchema,
await response.json(),
`Mirror Node GET /topics/${queryParams.topicId}/messages/${queryParams.sequenceNumber}`,
);
} catch (error) {
if (error instanceof CliError) throw error;
throw new NetworkError(
`Failed to fetch topic message for ${queryParams.topicId}`,
{ cause: error, recoverable: true },
);
}
}
async getTopicMessages(
queryParams: TopicMessagesQueryParams,
): Promise<TopicMessagesResponse> {
const { filters } = queryParams;
const queryParamsArray = (filters || []).map(
(f) => `${f.field}=${f.operation}:${f.value}`,
);
const filterParams =
queryParamsArray.length > 0 ? queryParamsArray.join('&') : '';
const baseParams = 'order=desc&limit=100';
const allParams = filterParams
? `${filterParams}&${baseParams}`
: baseParams;
let url: string | null =
`${this.getApiBaseUrl()}/topics/${queryParams.topicId}/messages?${allParams}`;
const arrayOfMessages: TopicMessage[] = [];
let fetchedMessages = 0;
while (url) {
fetchedMessages += 1;
try {
const response = await fetch(url);
if (!response.ok) {
await handleMirrorNodeErrorResponse(
response,
`Failed to get topic messages for ${queryParams.topicId}`,
false,
);
break;
}
const pagePayload: TopicMessagesAPIResponse = parseWithSchema(
TopicMessagesAPIResponseSchema,
await response.json(),
`Mirror Node GET /topics/${queryParams.topicId}/messages (page ${fetchedMessages})`,
);
arrayOfMessages.push(...pagePayload.messages);
if (fetchedMessages >= 100) break;
url = pagePayload.links?.next
? this.getBaseUrl() + pagePayload.links.next
: null;
} catch (error) {
if (error instanceof CliError) throw error;
throw new NetworkError(
`Failed to fetch topic messages for ${queryParams.topicId}`,
{ cause: error, recoverable: true },
);
}
}
return {
topicId: queryParams.topicId,
messages: arrayOfMessages,
};
}
async getTokenInfo(tokenId: string): Promise<TokenInfo> {
const url = `${this.getApiBaseUrl()}/tokens/${tokenId}`;
try {
const response = await fetch(url);
if (!response.ok) {
await handleMirrorNodeErrorResponse(
response,
`Failed to get token info for a token ${tokenId}`,
true,
`Token ${tokenId} not found`,
);
}
return parseWithSchema(
TokenInfoSchema,
await response.json(),
`Mirror Node GET /tokens/${tokenId}`,
);
} catch (error) {
if (error instanceof CliError) throw error;
throw new NetworkError(`Failed to fetch token info for ${tokenId}`, {
cause: error,
recoverable: true,
});
}
}
async getNftInfo(tokenId: string, serialNumber: number): Promise<NftInfo> {
const url = `${this.getApiBaseUrl()}/tokens/${tokenId}/nfts/${serialNumber}`;
try {
const response = await fetch(url);
if (!response.ok) {
await handleMirrorNodeErrorResponse(
response,
`Failed to get NFT info for token ${tokenId} serial ${serialNumber}`,
true,
`NFT ${tokenId} serial ${serialNumber} not found`,
);
}
return parseWithSchema(
NftInfoSchema,
await response.json(),
`Mirror Node GET /tokens/${tokenId}/nfts/${serialNumber}`,
);
} catch (error) {
if (error instanceof CliError) throw error;
throw new NetworkError(
`Failed to fetch NFT info for ${tokenId} serial ${serialNumber}`,
{ cause: error, recoverable: true },
);
}
}
async getTopicInfo(topicId: string): Promise<TopicInfo> {
const url = `${this.getApiBaseUrl()}/topics/${topicId}`;
try {
const response = await fetch(url);
if (!response.ok) {
await handleMirrorNodeErrorResponse(
response,
`Failed to get topic info for ${topicId}`,
true,
`Topic ${topicId} not found`,
);
}
return parseWithSchema(
TopicInfoSchema,
await response.json(),
`Mirror Node GET /topics/${topicId}`,
);
} catch (error) {
if (error instanceof CliError) throw error;
throw new NetworkError(`Failed to fetch topic info for ${topicId}`, {
cause: error,
recoverable: true,
});
}
}
async getTransactionRecord(
transactionId: string,
nonce?: number,
): Promise<TransactionDetailsResponse> {
let url = `${this.getApiBaseUrl()}/transactions/${transactionId}`;
if (nonce !== undefined) {
url += `?nonce=${nonce}`;
}
try {
const response = await fetch(url);
if (!response.ok) {
await handleMirrorNodeErrorResponse(
response,
`Failed to get transaction record for ${transactionId}`,
true,
`Transaction ${transactionId} not found`,
);
}
return parseWithSchema(
TransactionDetailsResponseSchema,
await response.json(),
`Mirror Node GET /transactions/${transactionId}`,
);
} catch (error) {
if (error instanceof CliError) throw error;
throw new NetworkError(
`Failed to fetch transaction record for ${transactionId}`,
{ cause: error, recoverable: true },
);
}
}
async getContractInfo(contractId: string): Promise<ContractInfo> {
const url = `${this.getApiBaseUrl()}/contracts/${contractId}`;
try {
const response = await fetch(url);
if (!response.ok) {
await handleMirrorNodeErrorResponse(
response,
`Failed to get contract info for ${contractId}`,
true,
`Contract ${contractId} not found`,
);
}
return parseWithSchema(
ContractInfoSchema,
await response.json(),
`Mirror Node GET /contracts/${contractId}`,
);
} catch (error) {
if (error instanceof CliError) throw error;
throw new NetworkError(
`Failed to fetch contract info for ${contractId}`,
{ cause: error, recoverable: true },
);
}
}
async getPendingAirdrops(accountId: string): Promise<TokenAirdropsResponse> {
const url = `${this.getApiBaseUrl()}/accounts/${accountId}/airdrops/pending`;
try {
const response = await fetch(url);
if (!response.ok) {
await handleMirrorNodeErrorResponse(
response,
`Failed to fetch pending airdrops for an account ${accountId}`,
true,
`Account ${accountId} not found`,
);
}
return parseWithSchema(
TokenAirdropsResponseSchema,
await response.json(),
`Mirror Node GET /accounts/${accountId}/airdrops/pending`,
);
} catch (error) {
if (error instanceof CliError) throw error;
throw new NetworkError(
`Failed to fetch pending airdrops for ${accountId}`,
{ cause: error, recoverable: true },
);
}
}
async getOutstandingAirdrops(
accountId: string,
): Promise<TokenAirdropsResponse> {
const url = `${this.getApiBaseUrl()}/accounts/${accountId}/airdrops/outstanding`;
try {
const response = await fetch(url);
if (!response.ok) {
await handleMirrorNodeErrorResponse(
response,
`Failed to fetch outstanding airdrops for an account ${accountId}`,
true,
`Account ${accountId} not found`,
);
}
return parseWithSchema(
TokenAirdropsResponseSchema,
await response.json(),
`Mirror Node GET /accounts/${accountId}/airdrops/outstanding`,
);
} catch (error) {
if (error instanceof CliError) throw error;
throw new NetworkError(
`Failed to fetch outstanding airdrops for ${accountId}`,
{ cause: error, recoverable: true },
);
}
}
async getExchangeRate(timestamp?: string): Promise<ExchangeRateResponse> {
const timestampParam = timestamp
? `?timestamp=${encodeURIComponent(timestamp)}`
: '';
const url = `${this.getApiBaseUrl()}/network/exchangerate${timestampParam}`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new NetworkError(
`HTTP error! status: ${response.status}. Message: ${response.statusText}`,
{ recoverable: true },
);
}
return parseWithSchema(
ExchangeRateResponseSchema,
await response.json(),
'Mirror Node GET /network/exchangerate',
);
} catch (error) {
if (error instanceof CliError) throw error;
throw new NetworkError('Failed to fetch exchange rate', {
cause: error,
recoverable: true,
});
}
}
async postContractCall(
request: ContractCallRequest,
): Promise<ContractCallResponse> {
const url = `${this.getApiBaseUrl()}/contracts/call`;
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(request),
});
if (!response.ok) {
throw new NetworkError(
`Failed to call contract via mirror node: ${response.status} ${response.statusText}`,
{ recoverable: true },
);
}
return (await response.json()) as ContractCallResponse;
} catch (error) {
if (error instanceof CliError) throw error;
throw new NetworkError('Failed to call contract via mirror node', {
cause: error,
recoverable: true,
});
}
}
private getKeyAlgorithm(keyType: MirrorNodeKeyType): KeyAlgorithm {
switch (keyType) {
case MirrorNodeKeyType.ECDSA_SECP256K1:
return KeyAlgorithm.ECDSA;
case MirrorNodeKeyType.ED25519:
return KeyAlgorithm.ED25519;
}
}
}