-
Notifications
You must be signed in to change notification settings - Fork 101
/
HasuraClient.ts
655 lines (632 loc) · 18.7 KB
/
HasuraClient.ts
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
import { Schema } from '@cardano-ogmios/client'
import { exec } from 'child_process'
import util, { DataFetcher, ModuleState } from '@cardano-graphql/util'
import fetch from 'cross-fetch'
import { DocumentNode, GraphQLSchema, print } from 'graphql'
import { GraphQLClient, gql } from 'graphql-request'
import { introspectSchema, wrapSchema } from '@graphql-tools/wrap'
import pRetry from 'p-retry'
import path from 'path'
import {
AdaPots,
Asset,
AssetBalance,
AssetSupply,
Block,
PaymentAddressSummary,
ShelleyProtocolParams,
Token,
TransactionOutput
} from './graphql_types'
import { dummyLogger, Logger } from 'ts-log'
import BigNumber from 'bignumber.js'
import {
AssetMetadataAndHash,
AssetMetadataHashAndId,
AssetWithoutTokens
} from './typeAliases'
export type AdaPotsToCalculateSupply = { circulating: AssetSupply['circulating'], reserves: AdaPots['reserves']}
const notInCurrentEraMessage = 'currentEpoch is only available when close to the chain tip. This is expected during the initial chain-sync.'
const withHexPrefix = (value: string) => `\\x${value}`
export class HasuraClient {
private client: GraphQLClient
private applyingSchemaAndMetadata: boolean
public adaPotsToCalculateSupplyFetcher: DataFetcher<AdaPotsToCalculateSupply>
public currentProtocolVersionFetcher: DataFetcher<ShelleyProtocolParams['protocolVersion']>
private state: ModuleState
public schema: GraphQLSchema
constructor (
readonly hasuraCliPath: string,
readonly hasuraUri: string,
pollingInterval: number,
readonly lastConfiguredMajorVersion: number,
private logger: Logger = dummyLogger
) {
this.state = null
this.applyingSchemaAndMetadata = false
this.adaPotsToCalculateSupplyFetcher = new DataFetcher<AdaPotsToCalculateSupply>(
'AdaPotsToCalculateSupply',
() => {
try {
return this.getAdaPotsToCalculateSupply()
} catch (error) {
if (error.message !== notInCurrentEraMessage) {
throw error
}
this.logger.debug({ err: error })
}
},
pollingInterval,
this.logger
)
this.currentProtocolVersionFetcher = new DataFetcher<ShelleyProtocolParams['protocolVersion']>(
'ProtocolParams',
async () => {
const currentProtocolVersion = await this.getCurrentProtocolVersion()
this.logger.debug(
{ module: 'HasuraClient', currentProtocolVersion },
'currentProtocolVersionFetcher'
)
return currentProtocolVersion
},
1000 * 60,
this.logger
)
this.client = new GraphQLClient(
`${this.hasuraUri}/v1/graphql`,
{
headers: {
'X-Hasura-Role': 'cardano-graphql'
}
}
)
}
private async getAdaPotsToCalculateSupply (): Promise<AdaPotsToCalculateSupply> {
const result = await this.client.request(
gql`query {
cardano {
currentEpoch {
adaPots {
reserves
}
}
}
rewards_aggregate {
aggregate {
sum {
amount
}
}
}
utxos_aggregate {
aggregate {
sum {
value
}
}
}
withdrawals_aggregate {
aggregate {
sum {
amount
}
}
}
}`
)
const {
cardano,
rewards_aggregate: rewardsAggregate,
utxos_aggregate: utxosAggregate,
withdrawals_aggregate: withdrawalsAggregate
} = result
if (cardano[0]?.currentEpoch === null) {
this.logger.debug({ module: 'HasuraClient' }, notInCurrentEraMessage)
throw new Error(notInCurrentEraMessage)
}
const rewards = new BigNumber(rewardsAggregate.aggregate.sum.amount)
const utxos = new BigNumber(utxosAggregate.aggregate.sum.value)
const withdrawals = new BigNumber(withdrawalsAggregate.aggregate.sum.amount)
const withdrawableRewards = rewards.minus(withdrawals)
return {
circulating: utxos.plus(withdrawableRewards).toString(),
reserves: cardano[0]?.currentEpoch.adaPots.reserves
}
}
private async hasuraCli (command: string) {
return new Promise((resolve, reject) => {
exec(
`${this.hasuraCliPath} --skip-update-check --project ${path.resolve(__dirname, '..', 'hasura', 'project')} --endpoint ${this.hasuraUri} ${command}`,
(error, stdout) => {
if (error) {
reject(error)
}
this.logger.debug({ module: 'HasuraClient' }, stdout)
resolve()
}
)
})
}
public async initialize () {
if (this.state !== null) return
this.state = 'initializing'
this.logger.info({ module: 'HasuraClient' }, 'Initializing')
await this.applySchemaAndMetadata()
await pRetry(async () => {
this.schema = await this.buildHasuraSchema()
}, {
factor: 1.75,
retries: 9,
onFailedAttempt: util.onFailedAttemptFor(
'Fetching Hasura schema via introspection',
this.logger
)
})
this.logger.debug({ module: 'HasuraClient' }, 'graphql-engine setup')
await pRetry(async () => {
const result = await this.client.request(
gql`query {
cardano {
currentEpoch {
number
}
}
}`
)
if (result.cardano[0]?.currentEpoch === null) {
this.logger.debug({ module: 'HasuraClient' }, notInCurrentEraMessage)
throw new Error(notInCurrentEraMessage)
}
}, {
factor: 1.05,
retries: 100,
onFailedAttempt: util.onFailedAttemptFor(
'Detecting sync state being in current era',
this.logger
)
})
this.logger.debug({ module: 'HasuraClient' }, 'DB is in current era')
await this.currentProtocolVersionFetcher.initialize()
await this.adaPotsToCalculateSupplyFetcher.initialize()
this.state = 'initialized'
this.logger.info({ module: 'HasuraClient' }, 'Initialized')
}
public async shutdown () {
await this.adaPotsToCalculateSupplyFetcher.shutdown()
await this.currentProtocolVersionFetcher.shutdown()
}
public async applySchemaAndMetadata (): Promise<void> {
if (this.applyingSchemaAndMetadata) return
this.applyingSchemaAndMetadata = true
await pRetry(async () => {
await this.hasuraCli('migrate apply --down all')
await this.hasuraCli('migrate apply --up all')
}, {
factor: 1.75,
retries: 9,
onFailedAttempt: util.onFailedAttemptFor(
'Applying PostgreSQL schema migrations',
this.logger
)
})
await pRetry(async () => {
await this.hasuraCli('metadata clear')
await this.hasuraCli('metadata apply')
}, {
factor: 1.75,
retries: 9,
onFailedAttempt: util.onFailedAttemptFor('Applying Hasura metadata', this.logger)
})
this.applyingSchemaAndMetadata = false
}
public async buildHasuraSchema () {
const executor = async ({ document, variables }: { document: DocumentNode, variables?: Object }) => {
const query = print(document)
try {
const fetchResult = await fetch(`${this.hasuraUri}/v1/graphql`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Hasura-Role': 'cardano-graphql'
},
body: JSON.stringify({ query, variables })
})
return fetchResult.json()
} catch (error) {
this.logger.error({ err: error })
throw error
}
}
const coreTypes = [
'Block',
'Cardano',
'Epoch',
'Block',
'Transaction'
]
const schema = wrapSchema({
schema: await introspectSchema(executor),
executor
})
for (const t of coreTypes) {
const gqlType = schema.getType(t)
if (!gqlType) {
throw new Error(`Remote schema is missing ${t}`)
}
}
return schema
}
public async deleteAssetsAfterSlot (slotNo: Block['slotNo']): Promise<number> {
this.logger.debug(
{ module: 'HasuraClient', slotNo },
'deleting assets found in tokens after slot'
)
const result = await this.client.request(
gql`mutation DeleteAssetsAfterSlot($slotNo: Int!) {
delete_assets(
where: {
firstAppearedInSlot: {
_gt: $slotNo
}
}
) {
affected_rows
}
}`,
{
slotNo
}
)
return result.delete_assets.affected_rows
}
public async getCurrentProtocolVersion (): Promise<ShelleyProtocolParams['protocolVersion']> {
const result = await this.client.request(
gql`query {
epochs (limit: 1, order_by: { number: desc }) {
protocolParams {
protocolVersion
}
}
}`
)
return result.epochs[0]?.protocolParams.protocolVersion
}
public async getMostRecentPointWithNewAsset (): Promise<Schema.Point | null> {
// An offset of 1 is applied to ensure a partial block extraction is not skipped
const result = await this.client.request(
gql`query {
assets (
limit: 1
offset: 1
order_by: { firstAppearedInBlock: { slotNo: desc }}
) {
firstAppearedInBlock {
hash
slotNo
}
}
}`
)
if (result.assets.length === 0) return null
const { hash, slotNo } = result.assets[0].firstAppearedInBlock
return {
hash: hash.substring(2),
slot: slotNo
}
}
public async getPaymentAddressSummary (address: string, atBlock?: number): Promise<PaymentAddressSummary> {
const result = await this.client.request(
gql`query PaymentAddressSummary (
$address: String!
$atBlock: Int
){
utxos (
where: {
_and: {
address: { _eq: $address },
transaction: { block: { number: { _lte: $atBlock }}}
}
}
) {
value
tokens {
asset {
assetId
assetName
decimals
description
fingerprint
logo
metadataHash
name
ticker
tokenMints {
quantity
transaction {
hash
}
}
tokenMints_aggregate {
aggregate {
avg {
quantity
}
count
max {
quantity
}
min {
quantity
}
sum {
quantity
}
}
}
url
policyId
}
quantity
}
}
utxos_aggregate (
where: {
_and: {
address: { _eq: $address },
transaction: { block: { number: { _lte: $atBlock }}}
}
}
) {
aggregate {
count
}
}
}`,
{
address,
atBlock
}
)
const map = new Map<Asset['assetId'], AssetBalance>()
for (const utxo of result.utxos as TransactionOutput[]) {
if (map.has('ada')) {
const current = map.get('ada')
map.set('ada', {
...current,
...{
quantity: new BigNumber(current.quantity)
.plus(new BigNumber(utxo.value))
.toString()
}
})
} else {
map.set('ada', {
asset: {
assetId: 'ada',
assetName: 'ada',
name: 'ada',
policyId: '',
tokenMints: [],
tokenMints_aggregate: {
aggregate: {
avg: {
quantity: 'na'
},
count: 'na',
max: {
quantity: 'na'
},
min: {
quantity: 'na'
},
sum: {
quantity: 'na'
}
},
nodes: []
}
},
quantity: utxo.value
})
}
for (const token of utxo.tokens as Token[]) {
if (map.has(token.asset.assetId)) {
const current = map.get(token.asset.assetId)
map.set(token.asset.assetId, {
...current,
...{
quantity: new BigNumber(current.quantity)
.plus(new BigNumber(token.quantity))
.toString()
}
})
} else {
map.set(token.asset.assetId, token as unknown as AssetBalance)
}
}
}
return {
assetBalances: [...map.values()],
utxosCount: result.utxos_aggregate.aggregate.count
}
}
public async getMeta (nodeTipSlotNumber: number) {
const result = await this.client.request(
gql`query {
epochs (limit: 1, order_by: { number: desc }) {
number
}
cardano {
tip {
epoch {
number
}
slotNo
forgedAt
}
}}`
)
const { tip } = result?.cardano[0]
const lastEpoch = result?.epochs[0]
const syncPercentage = tip.slotNo / nodeTipSlotNumber * 100
return {
// cardano-db-sync writes the epoch record at the end of each epoch during times of bulk sync
// The initialization state can be determined by comparing the last epoch record against the
// tip
initialized: lastEpoch.number === tip.epoch?.number,
// we cannot assume that actual db-sync syncPercentage will be less or equal to node sync state due to race condition at the query time
syncPercentage: syncPercentage > 100 ? 100 : syncPercentage
}
}
public async hasAsset (assetId: Asset['assetId']): Promise<boolean> {
const result = await this.client.request(
gql`query HasAsset (
$assetId: bytea!
) {
assets (
where: { assetId: { _eq: $assetId }}
) {
assetId
}
}`, {
assetId: withHexPrefix(assetId)
}
)
const response = result.assets.length > 0
this.logger.debug(
{ module: 'HasuraClient', assetId, hasAsset: response },
'Has asset?'
)
return response
}
public async getAssetMetadataHashesById (assetIds: Asset['assetId'][]): Promise<AssetMetadataHashAndId[]> {
const result = await this.client.request(
gql`query AssetMetadataHashes (
$assetIds: [bytea!]!
){
assets (
where: {
assetId: { _in: $assetIds }
}) {
assetId
metadataHash
}
}`,
{
assetIds: assetIds.map(id => withHexPrefix(id))
}
)
return result.assets
}
public async isInCurrentEra () {
const protocolVersion = this.currentProtocolVersionFetcher.value
this.logger.debug({
module: 'CardanoNodeClient',
currentProtocolVersion: protocolVersion,
lastConfiguredMajorVersion: protocolVersion.major
},
'Comparing current protocol params with last known major version from cardano-node config'
)
return protocolVersion.major >= this.lastConfiguredMajorVersion
}
public addAssetFingerprints (assets: Pick<AssetWithoutTokens, 'assetId' | 'fingerprint'>[]) {
this.logger.debug(
{ module: 'HasuraClient', qty: assets.length },
'Adding fingerprint to assets'
)
return this.client.request(
gql`mutation AddAssetFingerprint($assets: [Asset_insert_input!]!) {
insert_assets(
objects: $assets,
on_conflict: {
constraint: Asset_pkey,
update_columns: [fingerprint]
}
) {
returning {
assetId
}
}
}`,
{
assets
}
)
}
public async addAssetMetadata (asset: AssetMetadataAndHash) {
this.logger.info(
{ module: 'HasuraClient', assetId: asset.assetId },
'Adding metadata to asset'
)
const result = await this.client.request(
gql`mutation AddAssetMetadata(
$assetId: bytea!
$decimals: Int
$description: String
$logo: String
$metadataHash: bpchar!
$name: String
$ticker: String
$url: String
) {
update_assets(
where: {
assetId: { _eq: $assetId }
},
_set: {
decimals: $decimals
description: $description
logo: $logo
metadataHash: $metadataHash
name: $name
ticker: $ticker
url: $url
}
) {
affected_rows
returning {
assetId
}
}
}`,
{
...asset,
...{ assetId: withHexPrefix(asset.assetId) }
}
)
if (result.errors !== undefined) {
throw new Error(result.errors)
}
}
public async insertAssets (assets: AssetWithoutTokens[]) {
this.logger.debug(
{ module: 'HasuraClient', qty: assets.length },
'inserting assets found in tokens'
)
const result = await this.client.request(
gql`mutation InsertAssets($assets: [Asset_insert_input!]!) {
insert_assets(objects: $assets) {
returning {
name
policyId
description
assetName
assetId
}
affected_rows
}
}`,
{
assets: assets.map(asset => ({
...asset,
...{
assetId: withHexPrefix(asset.assetId),
assetName: withHexPrefix(asset.assetName),
policyId: withHexPrefix(asset.policyId)
}
}))
}
)
return result
}
}