impl: simplify header chronology
import { EventEmitter } from 'events'
import { ApiPromise, WsProvider } from '@polkadot/api'
-import { JustificationNotification, Header } from '@polkadot/types/interfaces'
+import {
+ JustificationNotification,
+ Header,
+ BlockHash,
+} from '@polkadot/types/interfaces'
import createDebug from 'debug'
import 'dotenv/config'
@@ -16,9 +20,6 @@ export default class Listener extends EventEmitter {
offset: number = 0
// block number of the last enqueued header
last: number = 0
- // tmp cache holding early bird headers
- // i.e. if last #1, curr #3, then it would cache #3 until we got #2
- cache: Map<number, Header> = new Map<number, Header>()
// last known grandpa set id
grandpaSetId: number = 0
@@ -56,31 +57,20 @@ export default class Listener extends EventEmitter {
}
async handleHeader(header: Header) {
- if (this.last !== 0 && header.number.toNumber() > this.last + 1) {
- // out of sequence early bird header
- this.cache.set(header.number.toNumber(), header)
- Listener.debug(`header#${header.number.toNumber()} out of sequence`)
- } else if (this.last === 0 || header.number.toNumber() === this.last + 1) {
- // in sequence
+ while (this.last !== 0 && header.number.toNumber() !== this.last + 1) {
+ const missingHeader: Header = await this.kusama.rpc.chain.getHeader(
+ await this.kusama.rpc.chain.getBlockHash(this.last + 1)
+ )
+ this.headers.push(missingHeader)
+ this.last = missingHeader.number.toNumber()
+ }
+
this.headers.push(header)
this.last = header.number.toNumber()
- Listener.debug(`header#${header.number.toNumber()} in sequence`)
- // if it is now a cached header's turn push it
- const cached: Header | undefined = this.cache.get(this.last + 1)
- if (cached) {
- this.headers.push(cached)
- this.cache.delete(this.last + 1)
- this.last = cached.number.toNumber()
- Listener.debug(`pushed cached header#${cached.number.toNumber()}`)
- }
- } else {
- // old header we already got
- }
+ Listener.debug(`#${this.last}`)
}
async emitRange() {
- Listener.debug('emitting range...')
-
const range: Header[] = this.headers.slice(
this.offset,
this.offset + this.rangeSize
