"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TreeMerger = void 0;
const logger_1 = require("../../ts/logger");
/**
 * @notice Tree merger keeps merging simple for hardhat task.
 * This class is using for merging signups and messages.
 */
class TreeMerger {
    /**
     * Initialize class properties
     *
     * @param {ITreeMergeParams} params - contracts and signer
     */
    constructor({ deployer, pollContract }) {
        this.pollContract = pollContract;
        this.deployer = deployer;
    }
    /**
     * Check if voting period is over. Otherwise, throw an error.
     */
    async checkPollDuration() {
        // check if it's time to merge the message AQ
        const deadline = await this.pollContract.endDate();
        const blockNumber = await this.deployer.provider.getBlockNumber();
        const block = await this.deployer.provider.getBlock(blockNumber);
        const now = Number(block?.timestamp);
        if (now < deadline) {
            throw new Error("Voting period is not over");
        }
    }
    /**
     * Merge user signup MACI state
     *
     * @param pollId - poll id
     */
    async mergeSignups() {
        // check if the state tree has been fully merged
        const isMerged = await this.pollContract.stateMerged();
        if (!isMerged) {
            // go and merge the state tree
            (0, logger_1.logMagenta)({ text: (0, logger_1.info)("Merging subroots to a main state root...") });
            const receipt = await this.pollContract.mergeState().then((tx) => tx.wait());
            if (receipt?.status !== 1) {
                throw new Error("Error merging signup state subroots");
            }
            (0, logger_1.logGreen)({ text: (0, logger_1.success)(`Merge state transaction hash: ${receipt.hash}`) });
            (0, logger_1.logMagenta)({ text: (0, logger_1.info)(`Gas used: ${receipt.gasUsed.toString()}`) });
        }
        else {
            (0, logger_1.logMagenta)({ text: (0, logger_1.info)("The state tree has already been merged.") });
        }
    }
}
exports.TreeMerger = TreeMerger;
//# sourceMappingURL=TreeMerger.js.map