-
Notifications
You must be signed in to change notification settings - Fork 357
/
Copy pathsubstrate.ts
494 lines (454 loc) · 14.2 KB
/
substrate.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
// Copyright 2020-2025 SubQuery Pte Ltd authors & contributors
// SPDX-License-Identifier: GPL-3.0
import assert from 'assert';
import { ApiPromise } from '@polkadot/api';
import { Vec } from '@polkadot/types';
import '@polkadot/api-augment/substrate';
import {
BlockHash,
EventRecord,
RuntimeVersion,
SignedBlock,
Header as SubstrateHeader,
} from '@polkadot/types/interfaces';
import { BN, BN_THOUSAND, BN_TWO, bnMin } from '@polkadot/util';
import {
getLogger,
IBlock,
Header,
filterBlockTimestamp,
} from '@subql/node-core';
import {
SpecVersionRange,
SubstrateBlockFilter,
SubstrateCallFilter,
SubstrateEventFilter,
SubstrateBlock,
SubstrateEvent,
SubstrateExtrinsic,
BlockHeader,
} from '@subql/types';
import { merge } from 'lodash';
import { SubqlProjectBlockFilter } from '../configure/SubqueryProject';
import { ApiPromiseConnection } from '../indexer/apiPromise.connection';
import { BlockContent, LightBlockContent } from '../indexer/types';
const logger = getLogger('fetch');
const INTERVAL_THRESHOLD = BN_THOUSAND.div(BN_TWO);
const DEFAULT_TIME = new BN(6_000);
const A_DAY = new BN(24 * 60 * 60 * 1000);
export function substrateHeaderToHeader(header: SubstrateHeader): Header {
return {
blockHeight: header.number.toNumber(),
blockHash: header.hash.toHex(),
parentHash: header.parentHash.toHex(),
};
}
export function substrateBlockToHeader(block: SignedBlock): Header {
return {
...substrateHeaderToHeader(block.block.header),
timestamp: getTimestamp(block),
};
}
export function wrapBlock(
signedBlock: SignedBlock,
events: EventRecord[],
specVersion: number,
): SubstrateBlock {
return merge(signedBlock, {
timestamp: getTimestamp(signedBlock),
specVersion: specVersion,
events,
});
}
export function getTimestamp({
block: { extrinsics },
}: SignedBlock): Date | undefined {
// extrinsics can be undefined when fetching light blocks
if (extrinsics) {
for (const e of extrinsics) {
const {
method: { method, section },
} = e;
if (section === 'timestamp' && method === 'set') {
const date = new Date(e.args[0].toJSON() as number);
if (isNaN(date.getTime())) {
throw new Error('timestamp args type wrong');
}
return date;
}
}
}
// For network that doesn't use timestamp-set, return undefined
// See test `return undefined if no timestamp set extrinsic`
// E.g Shiden
return undefined;
}
export function wrapExtrinsics(
wrappedBlock: SubstrateBlock,
allEvents: EventRecord[],
): SubstrateExtrinsic[] {
const groupedEvents = groupEventsByExtrinsic(allEvents);
return wrappedBlock.block.extrinsics.map((extrinsic, idx) => {
const events = groupedEvents[idx];
return {
idx,
extrinsic,
block: wrappedBlock,
events,
success: getExtrinsicSuccess(events),
};
});
}
function getExtrinsicSuccess(events: EventRecord[]): boolean {
return (
events.findIndex((evt) => evt.event.method === 'ExtrinsicSuccess') > -1
);
}
function groupEventsByExtrinsic(
events: EventRecord[],
): Record<number, EventRecord[]> {
return events.reduce(
(acc, event) => {
const extrinsicIdx = event.phase.isApplyExtrinsic
? event.phase.asApplyExtrinsic.toNumber()
: undefined;
if (extrinsicIdx === undefined) {
return acc;
}
acc[extrinsicIdx] ??= [];
acc[extrinsicIdx].push(event);
return acc;
},
{} as Record<number, EventRecord[]>,
);
}
export function wrapEvents(
extrinsics: SubstrateExtrinsic[],
events: EventRecord[],
block: SubstrateBlock,
): SubstrateEvent[] {
return events.reduce((acc, event, idx) => {
const { phase } = event;
const wrappedEvent: SubstrateEvent = merge(event, { idx, block });
if (phase.isApplyExtrinsic) {
wrappedEvent.extrinsic = extrinsics[phase.asApplyExtrinsic.toNumber()];
}
acc.push(wrappedEvent);
return acc;
}, [] as SubstrateEvent[]);
}
function checkSpecRange(
specVersionRange: SpecVersionRange,
specVersion: number,
) {
const [lowerBond, upperBond] = specVersionRange;
return (
(lowerBond === undefined ||
lowerBond === null ||
specVersion >= lowerBond) &&
(upperBond === undefined || upperBond === null || specVersion <= upperBond)
);
}
export function filterBlock(
block: SubstrateBlock,
filter?: SubstrateBlockFilter,
): SubstrateBlock | undefined {
if (!filter) return block;
if (!filterBlockModulo(block, filter)) return;
if (
block.timestamp &&
!filterBlockTimestamp(
block.timestamp.getTime(),
filter as SubqlProjectBlockFilter,
)
) {
return;
}
return filter.specVersion === undefined ||
block.specVersion === undefined ||
checkSpecRange(filter.specVersion, block.specVersion)
? block
: undefined;
}
export function filterBlockModulo(
block: SubstrateBlock,
filter: SubstrateBlockFilter,
): boolean {
const { modulo } = filter;
if (!modulo) return true;
return block.block.header.number.toNumber() % modulo === 0;
}
export function filterExtrinsic(
{ block, extrinsic, success }: SubstrateExtrinsic,
filter?: SubstrateCallFilter,
): boolean {
if (!filter) return true;
return (
(filter.specVersion === undefined ||
block.specVersion === undefined ||
checkSpecRange(filter.specVersion, block.specVersion)) &&
(filter.module === undefined ||
extrinsic.method.section === filter.module) &&
(filter.method === undefined ||
extrinsic.method.method === filter.method) &&
(filter.success === undefined || success === filter.success) &&
(filter.isSigned === undefined || extrinsic.isSigned === filter.isSigned)
);
}
export function filterExtrinsics(
extrinsics: SubstrateExtrinsic[],
filterOrFilters: SubstrateCallFilter | SubstrateCallFilter[] | undefined,
): SubstrateExtrinsic[] {
if (
!filterOrFilters ||
(filterOrFilters instanceof Array && filterOrFilters.length === 0)
) {
return extrinsics;
}
const filters =
filterOrFilters instanceof Array ? filterOrFilters : [filterOrFilters];
return extrinsics.filter((extrinsic) =>
filters.find((filter) => filterExtrinsic(extrinsic, filter)),
);
}
export function filterEvent(
{ block, event }: SubstrateEvent,
filter?: SubstrateEventFilter,
): boolean {
if (!filter) return true;
return (
(filter.specVersion === undefined ||
block.specVersion === undefined ||
checkSpecRange(filter.specVersion, block.specVersion)) &&
(filter.module ? event.section === filter.module : true) &&
(filter.method ? event.method === filter.method : true)
);
}
export function filterEvents(
events: SubstrateEvent[],
filterOrFilters?: SubstrateEventFilter | SubstrateEventFilter[] | undefined,
): SubstrateEvent[] {
if (
!filterOrFilters ||
(filterOrFilters instanceof Array && filterOrFilters.length === 0)
) {
return events;
}
const filters =
filterOrFilters instanceof Array ? filterOrFilters : [filterOrFilters];
return events.filter((event) =>
filters.find((filter) => filterEvent(event, filter)),
);
}
// TODO: prefetch all known runtime upgrades at once
export async function prefetchMetadata(
api: ApiPromise,
hash: BlockHash,
): Promise<void> {
await api.getBlockRegistry(hash);
}
/**
*
* @param api
* @param startHeight
* @param endHeight
* @param overallSpecVer exists if all blocks in the range have same parant specVersion
*/
export async function getBlockByHeight(
api: ApiPromise,
height: number,
): Promise<SignedBlock> {
const blockHash = await api.rpc.chain.getBlockHash(height).catch((e) => {
logger.error(`failed to fetch BlockHash ${height}`);
throw ApiPromiseConnection.handleError(e);
});
const block = await api.rpc.chain.getBlock(blockHash).catch((e) => {
logger.error(
`failed to fetch Block hash="${blockHash}" height="${height}"${getApiDecodeErrMsg(
e.message,
)}`,
);
throw ApiPromiseConnection.handleError(e);
});
// validate block is valid
if (block.block.header.hash.toHex() !== blockHash.toHex()) {
throw new Error(
`fetched block header hash ${block.block.header.hash.toHex()} is not match with blockHash ${blockHash.toHex()} at block ${height}. This is likely a problem with the rpc provider.`,
);
}
return block;
}
export async function getHeaderByHeight(
api: ApiPromise,
height: number,
): Promise<SubstrateHeader> {
const blockHash = await api.rpc.chain.getBlockHash(height).catch((e) => {
logger.error(`failed to fetch BlockHash ${height}`);
throw ApiPromiseConnection.handleError(e);
});
const header = await api.rpc.chain.getHeader(blockHash).catch((e) => {
logger.error(
`failed to fetch Block Header hash="${blockHash}" height="${height}"`,
);
throw ApiPromiseConnection.handleError(e);
});
// validate block is valid
if (header.hash.toHex() !== blockHash.toHex()) {
throw new Error(
`fetched block header hash ${header.hash.toHex()} is not match with blockHash ${blockHash.toHex()} at block ${height}. This is likely a problem with the rpc provider.`,
);
}
return header;
}
export async function fetchBlocksArray(
api: ApiPromise,
blockArray: number[],
): Promise<SignedBlock[]> {
return Promise.all(
blockArray.map(async (height) => getBlockByHeight(api, height)),
);
}
export async function fetchHeaderArray(
api: ApiPromise,
blockArray: number[],
): Promise<SubstrateHeader[]> {
return Promise.all(
blockArray.map(async (height) => getHeaderByHeight(api, height)),
);
}
export async function fetchEventsRange(
api: ApiPromise,
hashs: BlockHash[],
): Promise<Vec<EventRecord>[]> {
return Promise.all(
hashs.map((hash) =>
api.query.system.events.at(hash).catch((e) => {
logger.error(
`failed to fetch events at block ${hash}${getApiDecodeErrMsg(
e.message,
)}`,
);
throw ApiPromiseConnection.handleError(e);
}),
),
);
}
export async function fetchRuntimeVersionRange(
api: ApiPromise,
hashs: BlockHash[],
): Promise<RuntimeVersion[]> {
return Promise.all(
hashs.map((hash) =>
api.rpc.state.getRuntimeVersion(hash).catch((e) => {
logger.error(`failed to fetch RuntimeVersion at block ${hash}`);
throw ApiPromiseConnection.handleError(e);
}),
),
);
}
export async function fetchBlocksBatches(
api: ApiPromise,
blockArray: number[],
overallSpecVer?: number,
): Promise<IBlock<BlockContent>[]> {
const blocks = await fetchBlocksArray(api, blockArray);
const blockHashs = blocks.map((b) => b.block.header.hash);
const parentBlockHashs = blocks.map((b) => b.block.header.parentHash);
// If overallSpecVersion passed, we don't need to use api to get runtimeVersions
// wrap block with specVersion
// If specVersion changed, we also not guarantee in this batch contains multiple runtimes,
// therefore we better to fetch runtime over all blocks
const [blockEvents, runtimeVersions] = await Promise.all([
fetchEventsRange(api, blockHashs),
overallSpecVer !== undefined // note, we need to be careful if spec version is 0
? undefined
: fetchRuntimeVersionRange(api, parentBlockHashs),
]);
return blocks.map((block, idx) => {
const events = blockEvents[idx];
const parentSpecVersion =
overallSpecVer ?? runtimeVersions?.[idx].specVersion.toNumber();
assert(parentSpecVersion !== undefined, 'parentSpecVersion is undefined');
const wrappedBlock = wrapBlock(block, events.toArray(), parentSpecVersion);
const wrappedExtrinsics = wrapExtrinsics(wrappedBlock, events);
const wrappedEvents = wrapEvents(wrappedExtrinsics, events, wrappedBlock);
return {
getHeader: () => substrateBlockToHeader(wrappedBlock),
block: {
block: wrappedBlock,
extrinsics: wrappedExtrinsics,
events: wrappedEvents,
},
};
});
}
// TODO why is fetchBlocksBatches a breadth first funciton rather than depth?
export async function fetchLightBlock(
api: ApiPromise,
height: number,
): Promise<IBlock<LightBlockContent>> {
const blockHash = await api.rpc.chain.getBlockHash(height).catch((e) => {
logger.error(`failed to fetch BlockHash ${height}`);
throw ApiPromiseConnection.handleError(e);
});
const [header, events] = await Promise.all([
api.rpc.chain.getHeader(blockHash).catch((e) => {
logger.error(
`failed to fetch Block Header hash="${blockHash}" height="${height}"`,
);
throw ApiPromiseConnection.handleError(e);
}),
api.query.system.events.at(blockHash).catch((e) => {
logger.error(`failed to fetch events at block ${blockHash}`);
throw ApiPromiseConnection.handleError(e);
}),
]);
const blockHeader: BlockHeader = {
block: { header },
events: events.toArray(),
};
return {
block: {
block: blockHeader,
events: events.map((evt, idx) => merge(evt, { idx, block: blockHeader })),
},
getHeader: () => {
return substrateHeaderToHeader(blockHeader.block.header);
},
};
}
export async function fetchBlocksBatchesLight(
api: ApiPromise,
blockArray: number[],
): Promise<IBlock<LightBlockContent>[]> {
return Promise.all(blockArray.map((height) => fetchLightBlock(api, height)));
}
export function calcInterval(api: ApiPromise): BN {
return bnMin(
A_DAY,
api.consts.babe?.expectedBlockTime ||
(api.consts.difficulty?.targetBlockTime as any) ||
api.consts.subspace?.expectedBlockTime ||
(api.consts.timestamp?.minimumPeriod.gte(INTERVAL_THRESHOLD)
? api.consts.timestamp.minimumPeriod.mul(BN_TWO)
: api.query.parachainSystem
? DEFAULT_TIME.mul(BN_TWO)
: DEFAULT_TIME),
);
}
function getApiDecodeErrMsg(errMsg: string): string {
const decodedErrMsgs = [
'Unable to decode',
'failed decoding',
'unknown type',
];
if (!decodedErrMsgs.find((decodedErrMsg) => errMsg.includes(decodedErrMsg))) {
return '';
}
return (
`\nThis is because the block cannot be decoded. To solve this you can either:` +
'\n* Skip the block' +
'\n* Update the chain types. You can test this by viewing the block with https://polkadot.js.org/apps/' +
'\nFor further information please read the docs: https://academy.subquery.network/'
);
}