-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathHasuraClient.ts
More file actions
370 lines (358 loc) · 10.9 KB
/
Copy pathHasuraClient.ts
File metadata and controls
370 lines (358 loc) · 10.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
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 {
AdaPots,
Asset,
AssetBalance,
AssetSupply,
PaymentAddressSummary,
ProtocolParams,
Token,
TransactionOutput
} from './graphql_types'
import { dummyLogger, Logger } from 'ts-log'
import BigNumber from 'bignumber.js'
export type AdaPotsToCalculateSupply = { circulating: AssetSupply['circulating'], reserves: AdaPots['reserves']}
const epochInformationNotYetAvailable = 'Epoch information not yet available. This is expected during the initial chain-sync.'
export class HasuraClient {
private client: GraphQLClient
public adaPotsToCalculateSupplyFetcher: DataFetcher<AdaPotsToCalculateSupply>
private state: ModuleState
public schema: GraphQLSchema
constructor (
readonly hasuraUri: string,
pollingInterval: number,
private logger: Logger = dummyLogger
) {
this.state = null
this.adaPotsToCalculateSupplyFetcher = new DataFetcher<AdaPotsToCalculateSupply>(
'AdaPotsToCalculateSupply',
() => {
try {
return this.getAdaPotsToCalculateSupply()
} catch (error) {
if (error.message !== epochInformationNotYetAvailable) {
console.debug(error.message)
}
this.logger.trace({ err: error })
}
},
pollingInterval,
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 {
epochs (limit: 1, order_by: { number: desc }) {
adaPots {
reserves
}
}
rewards_aggregate {
aggregate {
sum {
amount
}
}
}
utxos_aggregate {
aggregate {
sum {
value
}
}
}
withdrawals_aggregate {
aggregate {
sum {
amount
}
}
}
}`
)
const {
epochs,
rewards_aggregate: rewardsAggregate,
utxos_aggregate: utxosAggregate,
withdrawals_aggregate: withdrawalsAggregate
} = result
if (epochs.length === 0 || epochs[0]?.adaPots === null) {
this.logger.debug({ module: 'HasuraClient' }, epochInformationNotYetAvailable)
throw new Error(epochInformationNotYetAvailable)
}
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: epochs[0]?.adaPots.reserves
}
}
public async initialize () {
if (this.state !== null) return
this.state = 'initializing'
this.logger.info({ module: 'HasuraClient' }, 'Initializing')
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')
this.adaPotsToCalculateSupplyFetcher.initialize().catch(error => {
this.logger.error({ module: 'HasuraClient', err: error }, 'AdaPots fetcher initialization failed')
})
this.state = 'initialized'
this.logger.info({ module: 'HasuraClient' }, 'Initialized')
}
public async shutdown () {
await this.adaPotsToCalculateSupplyFetcher.shutdown()
}
public async buildHasuraSchema () {
const executor = async ({ document, variables }: { document: DocumentNode, variables?: Object }) => {
const query = print(document)
const isIntrospection = query.includes('__schema') || query.includes('__type')
if (!isIntrospection) {
this.logger.debug({ module: 'HasuraClient', query, variables: JSON.stringify(variables) }, 'Delegating to Hasura')
}
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 })
})
const result = await fetchResult.json()
if (!isIntrospection && result.errors) {
this.logger.error({ module: 'HasuraClient', errors: JSON.stringify(result.errors), query, variables: JSON.stringify(variables) }, 'Hasura returned errors')
}
return result
} 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 getCurrentProtocolVersion (): Promise<ProtocolParams['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 getPaymentAddressSummary (address: string, atBlock?: number): Promise<PaymentAddressSummary> {
let args = 'address: { _eq: $address }'
if (atBlock) {
args = args + '\n transaction: { block: { number: { _lte: $atBlock }}}'
}
const query = `query PaymentAddressSummary (
$address: String!
$atBlock: Int
){
utxos (
where: {
_and: {
${args}
}
}
) {
value
tokens {
asset {
assetId
assetName
decimals
description
fingerprint
logo
metadataHash
name
ticker
tokenMints {
quantity
transaction {
hash
}
}
tokenMints_aggregate {
aggregate {
count
max {
quantity
}
min {
quantity
}
sum {
quantity
}
}
}
url
policyId
}
quantity
}
}
utxos_aggregate (
where: {
_and: {
${args}
}
}
) {
aggregate {
count
}
}
}`
const result = await this.client.request(
gql`${query}`,
{ 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: '\\xada',
assetName: '\\xada',
name: 'ada',
policyId: '\\xada',
tokenMints: [],
tokenMints_aggregate: {
aggregate: {
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 {
initialized: lastEpoch.number === tip.epoch?.number,
syncPercentage: syncPercentage > 100 ? 100 : syncPercentage
}
}
public async getAssetSyncPercentage (): Promise<number> {
const response = await fetch(`${this.hasuraUri}/v2/query`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
type: 'run_sql',
args: {
sql: 'SELECT (SELECT COUNT(*)::int FROM multi_asset) AS total, (SELECT COUNT(*)::int FROM "Asset") AS synced'
}
})
})
const result = await response.json()
const [, [total, synced]] = result.result
const totalNum = Number(total)
if (totalNum === 0) return 0
return Math.min(Math.round(Number(synced) / totalNum * 100), 100)
}
}