-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
79 lines (67 loc) · 2.07 KB
/
index.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
import axios from 'axios';
import { Ctx } from '../processor';
// import * as gql from 'gql-query-builder';
import { getChain } from '../chains';
import { ProcessorConfig } from '../chains/interfaces/processorConfig';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
type ArchiveBlockData = {
hash: string;
};
export class MultiChainBlocksMapper {
private static instance: MultiChainBlocksMapper;
private chainConfig: ProcessorConfig;
private context: Ctx | null = null;
private constructor(context?: Ctx) {
this.context = context ?? null;
this.chainConfig = getChain().config;
}
static getInstance(ctx?: Ctx) {
if (!MultiChainBlocksMapper.instance) {
MultiChainBlocksMapper.instance = new MultiChainBlocksMapper(ctx);
}
return MultiChainBlocksMapper.instance;
}
async getParaBlockHashByRelayBlockTimestamp(
blockTimestampRaw: number
): Promise<string | null> {
dayjs.extend(utc);
const queryResp = await this.blocksMapperQuery<
'blocks',
ArchiveBlockData[]
>({
query: `query ($limit: Int, $orderBy: [BlockOrderByInput!], $blockTimestamp: DateTime) { blocks (limit: $limit, orderBy: $orderBy, where: { timestamp_gte: $blockTimestamp }) { hash } }`,
variables: {
limit: 1,
orderBy: 'timestamp_ASC',
blockTimestamp: (() =>
dayjs.utc(blockTimestampRaw).format('YYYY-MM-DDTHH:mm:ss.SSS[Z]'))()
}
});
if (!queryResp || !queryResp.data) return null;
const blocks = queryResp.data.blocks;
if (!blocks || blocks.length == 0) return null;
return blocks[0].hash;
}
private async blocksMapperQuery<N extends string, R>(graphqlQuery: {
variables: any;
query: string;
}): Promise<null | {
data: Record<N, R>;
}> {
const options = {
url: this.chainConfig.blocksMapper.dataSource.endpoint,
method: 'POST',
data: graphqlQuery,
headers: {
'content-type': 'application/json'
}
};
try {
return (await axios(options)).data;
} catch (e) {
console.log(e);
}
return null;
}
}