"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpokePoolClient = exports.knownEventNames = void 0;
var tslib_1 = require("tslib");
var ethers_1 = require("ethers");
var utils_1 = require("../../utils");
var EventUtils_1 = require("../../utils/EventUtils");
var constants_1 = require("../../constants");
var BaseAbstractClient_1 = require("../BaseAbstractClient");
var BundleDataClient_1 = require("../BundleDataClient");
exports.knownEventNames = [
    "EnabledDepositRoute",
    "TokensBridged",
    "RelayedRootBundle",
    "ExecutedRelayerRefundRoot",
    "V3FundsDeposited",
    "FundsDeposited",
    "RequestedSpeedUpV3Deposit",
    "RequestedSpeedUpDeposit",
    "RequestedV3SlowFill",
    "RequestedSlowFill",
    "FilledV3Relay",
    "FilledRelay",
    "BridgedToHubPool",
    "ClaimedRelayerRefund",
];
var SpokePoolClient = (function (_super) {
    tslib_1.__extends(SpokePoolClient, _super);
    function SpokePoolClient(logger, hubPoolClient, chainId, deploymentBlock, eventSearchConfig) {
        if (eventSearchConfig === void 0) { eventSearchConfig = { from: 0, maxLookBack: 0 }; }
        var _this = _super.call(this, eventSearchConfig) || this;
        _this.logger = logger;
        _this.hubPoolClient = hubPoolClient;
        _this.chainId = chainId;
        _this.deploymentBlock = deploymentBlock;
        _this.currentTime = 0;
        _this.duplicateDepositHashes = {};
        _this.depositHashesToFills = {};
        _this.speedUps = {};
        _this.slowFillRequests = {};
        _this.depositRoutes = {};
        _this.tokensBridged = [];
        _this.rootBundleRelays = [];
        _this.relayerRefundExecutions = [];
        _this.claimedRelayerRefunds = [];
        _this.bridgedToHubPool = [];
        _this.invalidFills = new Set();
        _this.depositHashes = {};
        _this.fills = {};
        _this.firstHeightToSearch = eventSearchConfig.from;
        _this.latestHeightSearched = 0;
        _this.configStoreClient = hubPoolClient === null || hubPoolClient === void 0 ? void 0 : hubPoolClient.configStoreClient;
        return _this;
    }
    SpokePoolClient.prototype.getDepositsForDestinationChain = function (destinationChainId) {
        return Object.values(this.depositHashes).filter(function (deposit) { return deposit.destinationChainId === destinationChainId; });
    };
    SpokePoolClient.prototype._getDuplicateDeposits = function (deposit) {
        var _a;
        var depositHash = (0, utils_1.getRelayEventKey)(deposit);
        return (_a = this.duplicateDepositHashes[depositHash]) !== null && _a !== void 0 ? _a : [];
    };
    SpokePoolClient.prototype.getDepositsForDestinationChainWithDuplicates = function (destinationChainId) {
        var _this = this;
        var deposits = this.getDepositsForDestinationChain(destinationChainId);
        var duplicateDeposits = deposits.reduce(function (acc, deposit) {
            var duplicates = _this._getDuplicateDeposits(deposit);
            return acc.concat(duplicates);
        }, []);
        return (0, EventUtils_1.sortEventsAscendingInPlace)(deposits.concat(duplicateDeposits.flat()));
    };
    SpokePoolClient.prototype.getDeposits = function (filter) {
        var deposits = Object.values(this.depositHashes);
        if ((0, utils_1.isDefined)(filter)) {
            var fromBlock_1 = filter.fromBlock, toBlock_1 = filter.toBlock;
            deposits = deposits.filter(function (_a) {
                var blockNumber = _a.blockNumber;
                return blockNumber >= fromBlock_1 && toBlock_1 >= blockNumber;
            });
        }
        return (0, EventUtils_1.sortEventsAscendingInPlace)(deposits);
    };
    SpokePoolClient.prototype.getTokensBridged = function () {
        return this.tokensBridged;
    };
    SpokePoolClient.prototype.getDepositRoutes = function () {
        return this.depositRoutes;
    };
    SpokePoolClient.prototype.getFills = function () {
        return (0, EventUtils_1.sortEventsAscendingInPlace)(Object.values(this.fills).flat());
    };
    SpokePoolClient.prototype.getFillsForOriginChain = function (originChainId) {
        return this.fills[originChainId] || [];
    };
    SpokePoolClient.prototype.getFillsForRelayer = function (relayer) {
        return this.getFills().filter(function (fill) { return fill.relayer.eq(relayer); });
    };
    SpokePoolClient.prototype.getFillsWithBlockInRange = function (startingBlock, endingBlock) {
        return this.getFills().filter(function (fill) { return fill.blockNumber >= startingBlock && fill.blockNumber <= endingBlock; });
    };
    SpokePoolClient.prototype.getRootBundleRelays = function () {
        return this.rootBundleRelays;
    };
    SpokePoolClient.prototype.getLatestRootBundleId = function () {
        var _a;
        return this.rootBundleRelays.length > 0
            ? ((_a = this.rootBundleRelays[this.rootBundleRelays.length - 1]) === null || _a === void 0 ? void 0 : _a.rootBundleId) + 1
            : 0;
    };
    SpokePoolClient.prototype.getRelayerRefundExecutions = function () {
        return this.relayerRefundExecutions;
    };
    SpokePoolClient.prototype.getClaimedRelayerRefunds = function () {
        return this.claimedRelayerRefunds;
    };
    SpokePoolClient.prototype.getBridgedToHubPoolEvents = function () {
        return this.bridgedToHubPool;
    };
    SpokePoolClient.prototype.appendMaxSpeedUpSignatureToDeposit = function (deposit) {
        var _a;
        var depositId = deposit.depositId, depositor = deposit.depositor;
        var speedups = (_a = this.speedUps[depositor.toEvmAddress()]) === null || _a === void 0 ? void 0 : _a[depositId.toString()];
        if (!(0, utils_1.isDefined)(speedups) || speedups.length === 0) {
            return deposit;
        }
        var maxSpeedUp = speedups.reduce(function (prev, current) {
            return prev.updatedOutputAmount.lt(current.updatedOutputAmount) ? prev : current;
        });
        if (maxSpeedUp.updatedOutputAmount.gte(deposit.outputAmount)) {
            return deposit;
        }
        var updatedDeposit = tslib_1.__assign(tslib_1.__assign({}, deposit), { speedUpSignature: maxSpeedUp.depositorSignature, updatedOutputAmount: maxSpeedUp.updatedOutputAmount, updatedRecipient: maxSpeedUp.updatedRecipient, updatedMessage: maxSpeedUp.updatedMessage });
        return updatedDeposit;
    };
    SpokePoolClient.prototype.getDeposit = function (depositId) {
        return Object.values(this.depositHashes).find(function (_a) {
            var _depositId = _a.depositId;
            return _depositId.eq(depositId);
        });
    };
    SpokePoolClient.prototype.getSlowFillRequests = function () {
        return (0, EventUtils_1.sortEventsAscendingInPlace)(Object.values(this.slowFillRequests));
    };
    SpokePoolClient.prototype.getSlowFillRequest = function (relayData) {
        var hash = (0, utils_1.getRelayEventKey)(tslib_1.__assign(tslib_1.__assign({}, relayData), { destinationChainId: this.chainId }));
        return this.slowFillRequests[hash];
    };
    SpokePoolClient.prototype.getSlowFillRequestsForOriginChain = function (originChainId) {
        return Object.values(this.slowFillRequests).filter(function (e) { return e.originChainId === originChainId; });
    };
    SpokePoolClient.prototype.getSpeedUps = function () {
        return this.speedUps;
    };
    SpokePoolClient.prototype.getDepositForFill = function (fill) {
        var deposit = this.depositHashes[(0, utils_1.getRelayEventKey)(fill)];
        var match = (0, utils_1.validateFillForDeposit)(fill, deposit);
        return match.valid ? deposit : undefined;
    };
    SpokePoolClient.prototype.getFillsForDeposit = function (deposit) {
        var _a;
        return (_a = this.depositHashesToFills[this.getDepositHash(deposit)]) !== null && _a !== void 0 ? _a : [];
    };
    SpokePoolClient.prototype.isDepositFilled = function (deposit) {
        var _a;
        var depositHash = this.getDepositHash(deposit);
        var fills = (_a = this.depositHashesToFills[depositHash]) !== null && _a !== void 0 ? _a : [];
        return fills.some(function (fill) { return (0, utils_1.validateFillForDeposit)(fill, deposit).valid; });
    };
    SpokePoolClient.prototype.getValidUnfilledAmountForDeposit = function (deposit) {
        var _this = this;
        var outputAmount = deposit.outputAmount, originChainId = deposit.originChainId;
        var fillsForDeposit = this.depositHashesToFills[this.getDepositHash(deposit)];
        if (fillsForDeposit === undefined || fillsForDeposit.length === 0) {
            return { unfilledAmount: outputAmount, fillCount: 0, invalidFills: [] };
        }
        var _a = fillsForDeposit.reduce(function (groupedFills, fill) {
            if ((0, utils_1.validateFillForDeposit)(fill, deposit).valid) {
                var fillRepaymentData = tslib_1.__assign(tslib_1.__assign({}, fill), { fromLiteChain: deposit.fromLiteChain });
                var repaymentChainId = (0, BundleDataClient_1.getRefundInformationFromFill)(fillRepaymentData, _this.hubPoolClient, _this.hubPoolClient.latestHeightSearched).chainToSendRefundTo;
                if (_this.hubPoolClient && !(0, utils_1.isSlowFill)(fill) && !fill.relayer.isValidOn(repaymentChainId)) {
                    groupedFills.unrepayableFills.push(fill);
                }
                groupedFills.validFills.push(fill);
            }
            else {
                groupedFills.invalidFills.push(fill);
            }
            return groupedFills;
        }, { validFills: [], invalidFills: [], unrepayableFills: [] }), validFills = _a.validFills, invalidFills = _a.invalidFills, unrepayableFills = _a.unrepayableFills;
        var logLevel = (0, utils_1.chainIsProd)(originChainId) ? "warn" : "debug";
        var unrepayableFillsForDeposit = unrepayableFills.filter(function (x) { return x.depositId.eq(deposit.depositId); });
        if (unrepayableFillsForDeposit.length > 0) {
            this.logger[logLevel]({
                at: "SpokePoolClient",
                chainId: this.chainId,
                message: "Unrepayable fills found where we need to switch repayment address and or chain",
                deposit: deposit,
                unrepayableFills: Object.fromEntries(unrepayableFillsForDeposit.map(function (x) { return [x.relayer.toNative(), x]; })),
                notificationPath: "across-unrepayable-fills",
            });
        }
        if (validFills.length === 0) {
            return { unfilledAmount: outputAmount, fillCount: 0, invalidFills: invalidFills };
        }
        return {
            unfilledAmount: utils_1.bnZero,
            fillCount: validFills.length,
            invalidFills: invalidFills,
        };
    };
    SpokePoolClient.prototype.getDepositHash = function (event) {
        return "".concat(event.depositId.toString(), "-").concat(event.originChainId);
    };
    SpokePoolClient.prototype.canResolveZeroAddressOutputToken = function (deposit) {
        var _a, _b;
        if (!((_a = this.hubPoolClient) === null || _a === void 0 ? void 0 : _a.l2TokenHasPoolRebalanceRoute(deposit.inputToken, deposit.originChainId, deposit.quoteBlockNumber))) {
            return false;
        }
        else {
            var l1Token = (_b = this.hubPoolClient) === null || _b === void 0 ? void 0 : _b.getL1TokenForL2TokenAtBlock(deposit.inputToken, deposit.originChainId, deposit.quoteBlockNumber);
            return this.hubPoolClient.l2TokenEnabledForL1TokenAtBlock(l1Token, deposit.destinationChainId, deposit.quoteBlockNumber);
        }
    };
    SpokePoolClient.prototype.update = function (eventsToQuery) {
        var _a, _b;
        if (eventsToQuery === void 0) { eventsToQuery = this._queryableEventNames(); }
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var duplicateEvents, update, queryResults, currentTime, searchEndBlock, _i, _c, _event, event_1, queryDepositEvents, _d, _e, event_2, querySpeedUpDepositEvents, queryRequestedSlowFillEvents, queryFilledRelayEvents, enableDepositsEvents, _f, enableDepositsEvents_1, event_3, relayedRootBundleEvents, _g, relayedRootBundleEvents_1, event_4, refundEvents, _h, refundEvents_1, _event, event_5, claimedRelayerRefundEvents, _j, claimedRelayerRefundEvents_1, event_6, bridgedToHubPoolEvents, _k, bridgedToHubPoolEvents_1, event_7;
            var _this = this;
            return tslib_1.__generator(this, function (_l) {
                switch (_l.label) {
                    case 0:
                        duplicateEvents = [];
                        if (this.hubPoolClient !== null && !this.hubPoolClient.isUpdated) {
                            throw new Error("HubPoolClient not updated");
                        }
                        return [4, this._update(eventsToQuery)];
                    case 1:
                        update = _l.sent();
                        if (!update.success) {
                            return [2];
                        }
                        queryResults = update.events, currentTime = update.currentTime, searchEndBlock = update.searchEndBlock;
                        if (eventsToQuery.includes("TokensBridged")) {
                            for (_i = 0, _c = queryResults[eventsToQuery.indexOf("TokensBridged")]; _i < _c.length; _i++) {
                                _event = _c[_i];
                                event_1 = _event;
                                this.tokensBridged.push(tslib_1.__assign(tslib_1.__assign({}, event_1), { l2TokenAddress: (0, utils_1.toAddressType)(event_1.l2TokenAddress, this.chainId) }));
                            }
                        }
                        queryDepositEvents = function (eventName) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
                            var depositEvents, quoteBlockNumbers, _loop_1, this_1, _i, depositEvents_1, event_8;
                            var _this = this;
                            var _a;
                            return tslib_1.__generator(this, function (_b) {
                                switch (_b.label) {
                                    case 0:
                                        depositEvents = ((_a = queryResults[eventsToQuery.indexOf(eventName)]) !== null && _a !== void 0 ? _a : []).map(function (_event) {
                                            var event = _event;
                                            return tslib_1.__assign(tslib_1.__assign({}, event), { depositor: (0, utils_1.toAddressType)(event.depositor, _this.chainId), recipient: (0, utils_1.toAddressType)(event.recipient, event.destinationChainId), inputToken: (0, utils_1.toAddressType)(event.inputToken, _this.chainId), outputToken: (0, utils_1.toAddressType)(event.outputToken, event.destinationChainId), exclusiveRelayer: (0, utils_1.toAddressType)(event.exclusiveRelayer, event.destinationChainId) });
                                        });
                                        if (depositEvents.length > 0) {
                                            this.log("debug", "Using ".concat(depositEvents.length, " newly queried ").concat(eventName, " deposit events for chain ").concat(this.chainId), {
                                                earliestEvent: depositEvents[0].blockNumber,
                                            });
                                        }
                                        return [4, this.getBlockNumbers(depositEvents.map(function (e) { return e.quoteTimestamp; }))];
                                    case 1:
                                        quoteBlockNumbers = _b.sent();
                                        _loop_1 = function (event_8) {
                                            var quoteBlockNumber = quoteBlockNumbers[Number(event_8.quoteTimestamp)];
                                            var deposit = tslib_1.__assign(tslib_1.__assign({}, event_8), { messageHash: (0, utils_1.getMessageHash)(event_8.message), quoteBlockNumber: quoteBlockNumber, originChainId: this_1.chainId, fromLiteChain: true, toLiteChain: true });
                                            deposit.fromLiteChain = this_1.isOriginLiteChain(deposit);
                                            deposit.toLiteChain = this_1.isDestinationLiteChain(deposit);
                                            if (deposit.outputToken.isZeroAddress()) {
                                                deposit.outputToken = this_1.getDestinationTokenForDeposit(deposit);
                                            }
                                            if (this_1.depositHashes[(0, utils_1.getRelayEventKey)(deposit)] !== undefined) {
                                                var allDeposits = this_1._getDuplicateDeposits(deposit).concat(this_1.depositHashes[(0, utils_1.getRelayEventKey)(deposit)]);
                                                if (allDeposits.some(function (e) { return (0, EventUtils_1.duplicateEvent)(deposit, e); })) {
                                                    duplicateEvents.push(event_8);
                                                    return "continue";
                                                }
                                                (0, utils_1.assign)(this_1.duplicateDepositHashes, [(0, utils_1.getRelayEventKey)(deposit)], [deposit]);
                                                return "continue";
                                            }
                                            (0, utils_1.assign)(this_1.depositHashes, [(0, utils_1.getRelayEventKey)(deposit)], deposit);
                                        };
                                        this_1 = this;
                                        for (_i = 0, depositEvents_1 = depositEvents; _i < depositEvents_1.length; _i++) {
                                            event_8 = depositEvents_1[_i];
                                            _loop_1(event_8);
                                        }
                                        return [2];
                                }
                            });
                        }); };
                        _d = 0, _e = ["FundsDeposited"];
                        _l.label = 2;
                    case 2:
                        if (!(_d < _e.length)) return [3, 5];
                        event_2 = _e[_d];
                        if (!eventsToQuery.includes(event_2)) return [3, 4];
                        return [4, queryDepositEvents(event_2)];
                    case 3:
                        _l.sent();
                        _l.label = 4;
                    case 4:
                        _d++;
                        return [3, 2];
                    case 5:
                        querySpeedUpDepositEvents = function (eventName) {
                            var _a;
                            var speedUpEvents = ((_a = queryResults[eventsToQuery.indexOf(eventName)]) !== null && _a !== void 0 ? _a : [])
                                .map(function (_event) {
                                var event = _event;
                                var invalid = [event.depositor, event.updatedRecipient].some(function (addr) { return !utils_1.EvmAddress.validate(ethers_1.utils.arrayify(addr)); });
                                if (invalid) {
                                    return;
                                }
                                return tslib_1.__assign(tslib_1.__assign({}, event), { depositor: utils_1.EvmAddress.from(event.depositor), updatedRecipient: utils_1.EvmAddress.from(event.updatedRecipient) });
                            })
                                .filter(utils_1.isDefined);
                            for (var _i = 0, speedUpEvents_1 = speedUpEvents; _i < speedUpEvents_1.length; _i++) {
                                var event_9 = speedUpEvents_1[_i];
                                var speedUp = tslib_1.__assign(tslib_1.__assign({}, event_9), { originChainId: _this.chainId });
                                (0, utils_1.assign)(_this.speedUps, [speedUp.depositor.toEvmAddress(), speedUp.depositId.toString()], [speedUp]);
                                var deposit = _this.getDeposit(speedUp.depositId);
                                if ((0, utils_1.isDefined)(deposit) && (0, utils_1.chainIsEvm)(deposit.destinationChainId) && deposit.depositor.eq(speedUp.depositor)) {
                                    var eventKey = (0, utils_1.getRelayEventKey)(deposit);
                                    _this.depositHashes[eventKey] = _this.appendMaxSpeedUpSignatureToDeposit(deposit);
                                }
                            }
                        };
                        ["RequestedSpeedUpDeposit"].forEach(function (event) {
                            if (eventsToQuery.includes(event)) {
                                querySpeedUpDepositEvents(event);
                            }
                        });
                        queryRequestedSlowFillEvents = function (eventName) {
                            var _a, _b;
                            var _c;
                            var slowFillRequests = ((_a = queryResults[eventsToQuery.indexOf(eventName)]) !== null && _a !== void 0 ? _a : []).map(function (_event) {
                                var event = _event;
                                return tslib_1.__assign(tslib_1.__assign({}, event), { depositor: (0, utils_1.toAddressType)(event.depositor, event.originChainId), recipient: (0, utils_1.toAddressType)(event.recipient, _this.chainId), inputToken: (0, utils_1.toAddressType)(event.inputToken, event.originChainId), outputToken: (0, utils_1.toAddressType)(event.outputToken, _this.chainId), exclusiveRelayer: (0, utils_1.toAddressType)(event.exclusiveRelayer, _this.chainId) });
                            });
                            for (var _i = 0, slowFillRequests_1 = slowFillRequests; _i < slowFillRequests_1.length; _i++) {
                                var event_10 = slowFillRequests_1[_i];
                                var slowFillRequest = tslib_1.__assign(tslib_1.__assign({}, event_10), { destinationChainId: _this.chainId });
                                var depositHash = (0, utils_1.getRelayEventKey)(tslib_1.__assign(tslib_1.__assign({}, slowFillRequest), { destinationChainId: _this.chainId }));
                                if (_this.slowFillRequests[depositHash] !== undefined) {
                                    duplicateEvents.push(event_10);
                                    continue;
                                }
                                (_b = (_c = _this.slowFillRequests)[depositHash]) !== null && _b !== void 0 ? _b : (_c[depositHash] = slowFillRequest);
                            }
                        };
                        ["RequestedSlowFill"].forEach(function (event) {
                            if (eventsToQuery.includes(event)) {
                                queryRequestedSlowFillEvents(event);
                            }
                        });
                        queryFilledRelayEvents = function (eventName) {
                            var _a, _b;
                            var fillEvents = ((_a = queryResults[eventsToQuery.indexOf(eventName)]) !== null && _a !== void 0 ? _a : []).map(function (_event) {
                                var event = _event;
                                return tslib_1.__assign(tslib_1.__assign({}, event), { depositor: (0, utils_1.toAddressType)(event.depositor, event.originChainId), recipient: (0, utils_1.toAddressType)(event.recipient, _this.chainId), inputToken: (0, utils_1.toAddressType)(event.inputToken, event.originChainId), outputToken: (0, utils_1.toAddressType)(event.outputToken, _this.chainId), exclusiveRelayer: (0, utils_1.toAddressType)(event.exclusiveRelayer, _this.chainId), relayer: (0, utils_1.toAddressType)(event.relayer, _this.chainId), relayExecutionInfo: tslib_1.__assign(tslib_1.__assign({}, event.relayExecutionInfo), { updatedRecipient: (0, utils_1.toAddressType)(event.relayExecutionInfo.updatedRecipient, _this.chainId) }) });
                            });
                            if (fillEvents.length > 0) {
                                _this.log("debug", "Using ".concat(fillEvents.length, " newly queried ").concat(eventName, " events for chain ").concat(_this.chainId), {
                                    earliestEvent: fillEvents[0].blockNumber,
                                });
                            }
                            var _loop_2 = function (event_11) {
                                var fill = tslib_1.__assign(tslib_1.__assign({}, event_11), { destinationChainId: _this.chainId });
                                var duplicateFill = (_b = _this.fills[fill.originChainId]) === null || _b === void 0 ? void 0 : _b.find(function (f) { return (0, EventUtils_1.duplicateEvent)(fill, f); });
                                if (duplicateFill) {
                                    duplicateEvents.push(event_11);
                                    return "continue";
                                }
                                (0, utils_1.assign)(_this.fills, [fill.originChainId], [fill]);
                                (0, utils_1.assign)(_this.depositHashesToFills, [_this.getDepositHash(fill)], [fill]);
                            };
                            for (var _i = 0, fillEvents_1 = fillEvents; _i < fillEvents_1.length; _i++) {
                                var event_11 = fillEvents_1[_i];
                                _loop_2(event_11);
                            }
                        };
                        ["FilledRelay"].forEach(function (event) {
                            if (eventsToQuery.includes(event)) {
                                queryFilledRelayEvents(event);
                            }
                        });
                        if (eventsToQuery.includes("EnabledDepositRoute")) {
                            enableDepositsEvents = queryResults[eventsToQuery.indexOf("EnabledDepositRoute")].map(function (_event) {
                                var event = _event;
                                return tslib_1.__assign(tslib_1.__assign({}, event), { originToken: (0, utils_1.toAddressType)(event.originToken, constants_1.CHAIN_IDs.MAINNET) });
                            });
                            for (_f = 0, enableDepositsEvents_1 = enableDepositsEvents; _f < enableDepositsEvents_1.length; _f++) {
                                event_3 = enableDepositsEvents_1[_f];
                                (0, utils_1.assign)(this.depositRoutes, [event_3.originToken.toBytes32(), event_3.destinationChainId], event_3.enabled);
                            }
                        }
                        if (eventsToQuery.includes("RelayedRootBundle")) {
                            relayedRootBundleEvents = queryResults[eventsToQuery.indexOf("RelayedRootBundle")];
                            for (_g = 0, relayedRootBundleEvents_1 = relayedRootBundleEvents; _g < relayedRootBundleEvents_1.length; _g++) {
                                event_4 = relayedRootBundleEvents_1[_g];
                                this.rootBundleRelays.push(event_4);
                            }
                        }
                        if (eventsToQuery.includes("ExecutedRelayerRefundRoot")) {
                            refundEvents = queryResults[eventsToQuery.indexOf("ExecutedRelayerRefundRoot")];
                            for (_h = 0, refundEvents_1 = refundEvents; _h < refundEvents_1.length; _h++) {
                                _event = refundEvents_1[_h];
                                event_5 = _event;
                                this.relayerRefundExecutions.push(tslib_1.__assign(tslib_1.__assign({}, event_5), { l2TokenAddress: (0, utils_1.toAddressType)(event_5.l2TokenAddress, this.chainId), refundAddresses: event_5.refundAddresses.map(function (addr) { return (0, utils_1.toAddressType)(addr, _this.chainId); }) }));
                            }
                        }
                        if (eventsToQuery.includes("ClaimedRelayerRefund")) {
                            claimedRelayerRefundEvents = ((_a = queryResults[eventsToQuery.indexOf("ClaimedRelayerRefund")]) !== null && _a !== void 0 ? _a : []);
                            for (_j = 0, claimedRelayerRefundEvents_1 = claimedRelayerRefundEvents; _j < claimedRelayerRefundEvents_1.length; _j++) {
                                event_6 = claimedRelayerRefundEvents_1[_j];
                                this.claimedRelayerRefunds.push(tslib_1.__assign(tslib_1.__assign({}, event_6), { amount: event_6.amount || event_6.claimAmount }));
                            }
                        }
                        if (eventsToQuery.includes("BridgedToHubPool")) {
                            bridgedToHubPoolEvents = ((_b = queryResults[eventsToQuery.indexOf("BridgedToHubPool")]) !== null && _b !== void 0 ? _b : []);
                            for (_k = 0, bridgedToHubPoolEvents_1 = bridgedToHubPoolEvents; _k < bridgedToHubPoolEvents_1.length; _k++) {
                                event_7 = bridgedToHubPoolEvents_1[_k];
                                this.bridgedToHubPool.push(event_7);
                            }
                        }
                        if (duplicateEvents.length > 0) {
                            this.log("debug", "Duplicate events listed", {
                                duplicateEvents: duplicateEvents,
                            });
                            this.log("error", "Duplicate events detected, check debug logs");
                        }
                        this.currentTime = currentTime;
                        this.latestHeightSearched = searchEndBlock;
                        this.firstHeightToSearch = searchEndBlock + 1;
                        this.eventSearchConfig.to = undefined;
                        this.isUpdated = true;
                        this.log("debug", "SpokePool client for chain ".concat(this.chainId, " updated!"), {
                            nextFirstHeightToSearch: this.firstHeightToSearch,
                        });
                        return [2];
                }
            });
        });
    };
    SpokePoolClient.prototype.getBlockNumber = function (timestamp) {
        var _a, _b;
        return (_b = (_a = this.hubPoolClient) === null || _a === void 0 ? void 0 : _a.getBlockNumber(timestamp)) !== null && _b !== void 0 ? _b : Promise.resolve(utils_1.MAX_BIG_INT.toNumber());
    };
    SpokePoolClient.prototype.getBlockNumbers = function (timestamps) {
        var _a, _b;
        return ((_b = (_a = this.hubPoolClient) === null || _a === void 0 ? void 0 : _a.getBlockNumbers(timestamps)) !== null && _b !== void 0 ? _b : Promise.resolve(Object.fromEntries(timestamps.map(function (timestamp) { return [timestamp, utils_1.MAX_BIG_INT.toNumber()]; }))));
    };
    SpokePoolClient.prototype.getDestinationTokenForDeposit = function (deposit) {
        if (!this.canResolveZeroAddressOutputToken(deposit)) {
            return (0, utils_1.toAddressType)(constants_1.ZERO_ADDRESS, constants_1.CHAIN_IDs.MAINNET);
        }
        var l1Token = this.hubPoolClient.getL1TokenForL2TokenAtBlock(deposit.inputToken, deposit.originChainId, deposit.quoteBlockNumber);
        var counterpartToken = this.hubPoolClient.getL2TokenForL1TokenAtBlock(l1Token, deposit.destinationChainId, deposit.quoteBlockNumber);
        return counterpartToken !== null && counterpartToken !== void 0 ? counterpartToken : (0, utils_1.toAddressType)(constants_1.ZERO_ADDRESS, constants_1.CHAIN_IDs.MAINNET);
    };
    SpokePoolClient.prototype.log = function (level, message, data) {
        this.logger[level](tslib_1.__assign({ at: "SpokePoolClient", chainId: this.chainId, message: message }, data));
    };
    SpokePoolClient.prototype.getCurrentTime = function () {
        return this.currentTime;
    };
    SpokePoolClient.prototype.isOriginLiteChain = function (deposit) {
        var _a, _b;
        return (_b = (_a = this.configStoreClient) === null || _a === void 0 ? void 0 : _a.isChainLiteChainAtTimestamp(deposit.originChainId, deposit.quoteTimestamp)) !== null && _b !== void 0 ? _b : false;
    };
    SpokePoolClient.prototype.isDestinationLiteChain = function (deposit) {
        var _a, _b;
        return ((_b = (_a = this.configStoreClient) === null || _a === void 0 ? void 0 : _a.isChainLiteChainAtTimestamp(deposit.destinationChainId, deposit.quoteTimestamp)) !== null && _b !== void 0 ? _b : false);
    };
    return SpokePoolClient;
}(BaseAbstractClient_1.BaseAbstractClient));
exports.SpokePoolClient = SpokePoolClient;
//# sourceMappingURL=SpokePoolClient.js.map