From 140edb0f3a69704d66d6ac81619dc4eb56864654 Mon Sep 17 00:00:00 2001 From: nagdahimanshu Date: Tue, 19 Sep 2023 11:49:50 +0200 Subject: [PATCH] Subscribe to new block event --- src/client.ts | 20 ++++++++++++++++++++ src/index.ts | 4 +++- src/utils/fs.ts | 10 ++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/client.ts b/src/client.ts index 6158709a..366bf94a 100644 --- a/src/client.ts +++ b/src/client.ts @@ -11,9 +11,29 @@ * * Removal or modification of this copyright notice is prohibited. */ +import { resolve } from 'path'; import { createIPCClient, APIClient } from '@liskhq/lisk-api-client'; +import { Block } from '@liskhq/lisk-chain'; +import { NEW_BLOCK_EVENT_NAME } from './constants'; +import { write } from './utils/fs'; export const getAPIClient = async (liskCorePath: string): Promise => { const client = await createIPCClient(liskCorePath); return client; }; + +export const subscribeToNewBlockEvent = ( + client: APIClient, + snapshotHeight: number, + outputDir: string, +) => { + client.subscribe(NEW_BLOCK_EVENT_NAME, async data => { + const { block: encodedBlock } = (data as unknown) as Record; + const newBlock = client.block.decode(Buffer.from(encodedBlock, 'hex')) as Block; + if (newBlock.header.height !== snapshotHeight) { + const forgingStatus = await client.invoke('app:getForgingStatus'); + const forgingStatusJsonFilepath = resolve(outputDir, 'forgingStatus.json'); + await write(forgingStatusJsonFilepath, JSON.stringify(forgingStatus)); + } + }); +}; diff --git a/src/index.ts b/src/index.ts index 8c0f0495..463688f9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -29,7 +29,7 @@ import { SNAPSHOT_TIME_GAP, LEGACY_DB_PATH, } from './constants'; -import { getAPIClient } from './client'; +import { getAPIClient, subscribeToNewBlockEvent } from './client'; import { getConfig, migrateUserConfig, @@ -140,6 +140,8 @@ class LiskMigrator extends Command { const networkConstant = NETWORK_CONSTANT[networkIdentifier] as NetworkConfigLocal; const outputDir = `${outputPath}/${networkIdentifier}`; + subscribeToNewBlockEvent(client, snapshotHeight, outputDir); + if (autoStartLiskCoreV4) { if (!networkConstant) { this.error( diff --git a/src/utils/fs.ts b/src/utils/fs.ts index ef3cd78d..7d89dd4e 100644 --- a/src/utils/fs.ts +++ b/src/utils/fs.ts @@ -67,3 +67,13 @@ export const copyDir = async (src: string, dest: string) => { : await fs.promises.copyFile(srcPath, destPath); } }; + +export const write = async (filePath: string, content: string): Promise => + new Promise((resolve, reject) => { + fs.writeFile(filePath, content, err => { + if (err) { + return reject(err); + } + return resolve(true); + }); + });