"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ShutdownNodePlugin = void 0;
const lisk_sdk_1 = require("lisk-sdk");
class ShutdownNodePlugin extends lisk_sdk_1.BasePlugin {
    get nodeModulePath() {
        return __filename;
    }
    async init(context) {
        await super.init(context);
    }
    async load() {
        this._shutdownHeight = this.appConfig.system.backup.height;
        if (this._shutdownHeight === 0)
            return;
        this._currentChainApiClient = this.apiClient;
        const posConstants = await this._currentChainApiClient.invoke('pos_getConstants');
        this._roundLength = posConstants.numberActiveValidators + posConstants.numberStandbyValidators;
        this._currentChainApiClient.subscribe('network_newBlock', async () => this._newBlockHandler());
        this._currentChainApiClient.subscribe('chain_newBlock', async () => this._newBlockHandler());
    }
    async unload() {
        if (this._currentChainApiClient) {
            await this._currentChainApiClient.disconnect();
        }
    }
    async _newBlockHandler() {
        const nodeInfo = await this._currentChainApiClient.invoke('system_getNodeInfo');
        const bufferLength = this._roundLength;
        if (nodeInfo.finalizedHeight >= this._shutdownHeight + bufferLength) {
            const errorMsg = `Triggering node shutdown from Shutdown plugin: current height: ${nodeInfo.height}; reason: `.concat(nodeInfo.finalizedHeight === this._shutdownHeight + bufferLength
                ? `finalized height ${nodeInfo.finalizedHeight} is equal to the given shutdown height ${nodeInfo.finalizedHeight}`
                : `finalized height ${nodeInfo.finalizedHeight} is greater than the given shutdown height ${this._shutdownHeight + bufferLength}`);
            throw new Error(`${errorMsg}`.concat(bufferLength
                ? ` (snapshot height: ${this._shutdownHeight} + buffer: ${bufferLength})`
                : ''));
        }
    }
}
exports.ShutdownNodePlugin = ShutdownNodePlugin;
//# sourceMappingURL=plugin.js.map