import { __assign, __awaiter, __extends, __generator, __spreadArray } from "tslib";
import { fillStatusArray, findDepositBlock, getMaxFillDeadlineInRange as getMaxFillDeadline, getTimeAt as _getTimeAt, relayFillStatus, getTimestampForBlock as _getTimestampForBlock, } from "../../arch/evm";
import { BigNumber, getNetworkName, InvalidFill, toBN, EvmAddress, unpackDepositEvent, } from "../../utils";
import { logToSortableEvent, paginatedEventQuery, sortEventsAscendingInPlace, spreadEventWithBlockNumber, } from "../../utils/EventUtils";
import { isUpdateFailureReason } from "../BaseAbstractClient";
import { knownEventNames, SpokePoolClient } from "./SpokePoolClient";
import { EVM_SPOKE_POOL_CLIENT_TYPE } from "./types";
/**
 * An EVM-specific SpokePoolClient.
 */
var EVMSpokePoolClient = /** @class */ (function (_super) {
    __extends(EVMSpokePoolClient, _super);
    function EVMSpokePoolClient(logger, spokePool, hubPoolClient, chainId, deploymentBlock, eventSearchConfig) {
        if (eventSearchConfig === void 0) { eventSearchConfig = { from: 0, maxLookBack: 0 }; }
        var _this = _super.call(this, logger, hubPoolClient, chainId, deploymentBlock, eventSearchConfig) || this;
        _this.spokePool = spokePool;
        _this.type = EVM_SPOKE_POOL_CLIENT_TYPE;
        _this.spokePoolAddress = EvmAddress.from(spokePool.address);
        return _this;
    }
    EVMSpokePoolClient.prototype.relayFillStatus = function (relayData, atHeight) {
        return relayFillStatus(this.spokePool, relayData, atHeight, this.chainId);
    };
    EVMSpokePoolClient.prototype.fillStatusArray = function (relayData, atHeight) {
        return fillStatusArray(this.spokePool, relayData, atHeight);
    };
    EVMSpokePoolClient.prototype.getMaxFillDeadlineInRange = function (startBlock, endBlock) {
        return getMaxFillDeadline(this.spokePool, startBlock, endBlock);
    };
    EVMSpokePoolClient.prototype._availableEventsOnSpoke = function (eventNames) {
        var _this = this;
        if (eventNames === void 0) { eventNames = knownEventNames; }
        return Object.fromEntries(this.spokePool.interface.fragments
            .filter(function (_a) {
            var name = _a.name, type = _a.type;
            return type === "event" && eventNames.includes(name);
        })
            .map(function (_a) {
            var name = _a.name;
            return [name, _this.spokePool.filters[name]()];
        }));
    };
    EVMSpokePoolClient.prototype._queryableEventNames = function () {
        return Object.keys(this._availableEventsOnSpoke(knownEventNames));
    };
    EVMSpokePoolClient.prototype._update = function (eventsToQuery) {
        return __awaiter(this, void 0, void 0, function () {
            var searchConfig, reason, eventSearchConfigs, spokePool, timerStart, multicallFunctions, _a, multicallOutput, events, currentTime, errMsg, eventsWithBlockNumber;
            var _this = this;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, this.updateSearchConfig(this.spokePool.provider)];
                    case 1:
                        searchConfig = _b.sent();
                        if (isUpdateFailureReason(searchConfig)) {
                            reason = searchConfig;
                            return [2 /*return*/, { success: false, reason: reason }];
                        }
                        eventSearchConfigs = eventsToQuery.map(function (eventName) {
                            if (!_this._queryableEventNames().includes(eventName)) {
                                throw new Error("SpokePoolClient: Cannot query unrecognised SpokePool event name: ".concat(eventName));
                            }
                            var _searchConfig = __assign({}, searchConfig); // shallow copy
                            // By default, an event's query range is controlled by the `eventSearchConfig` passed in during instantiation.
                            // However, certain events have special overriding requirements to their search ranges:
                            // - EnabledDepositRoute: The full history is always required, so override the requested fromBlock.
                            if (eventName === "EnabledDepositRoute" && !_this.isUpdated) {
                                _searchConfig.from = _this.deploymentBlock;
                            }
                            return {
                                filter: _this._availableEventsOnSpoke()[eventName],
                                searchConfig: _searchConfig,
                            };
                        });
                        spokePool = this.spokePool;
                        this.log("debug", "Updating SpokePool client for chain ".concat(this.chainId), {
                            eventsToQuery: eventsToQuery,
                            searchConfig: searchConfig,
                            spokePool: spokePool.address,
                        });
                        timerStart = Date.now();
                        multicallFunctions = ["getCurrentTime"];
                        return [4 /*yield*/, Promise.all(__spreadArray([
                                spokePool.callStatic.multicall(multicallFunctions.map(function (f) { return spokePool.interface.encodeFunctionData(f); }), { blockTag: searchConfig.to })
                            ], eventSearchConfigs.map(function (config) { return paginatedEventQuery(_this.spokePool, config.filter, config.searchConfig); }), true))];
                    case 2:
                        _a = _b.sent(), multicallOutput = _a[0], events = _a.slice(1);
                        this.log("debug", "Time to query new events from RPC for ".concat(this.chainId, ": ").concat(Date.now() - timerStart, " ms"));
                        currentTime = multicallFunctions.map(function (fn, idx) { return spokePool.interface.decodeFunctionResult(fn, multicallOutput[idx])[0]; })[0];
                        if (!BigNumber.isBigNumber(currentTime) || currentTime.lt(this.currentTime)) {
                            errMsg = BigNumber.isBigNumber(currentTime)
                                ? "currentTime: ".concat(currentTime, " < ").concat(toBN(this.currentTime))
                                : "currentTime is not a BigNumber: ".concat(JSON.stringify(currentTime));
                            throw new Error("EVMSpokePoolClient::update: ".concat(errMsg));
                        }
                        // Sort all events to ensure they are stored in a consistent order.
                        events.forEach(function (events) { return sortEventsAscendingInPlace(events.map(logToSortableEvent)); });
                        eventsWithBlockNumber = events.map(function (eventList) {
                            return eventList.map(function (event) { return spreadEventWithBlockNumber(event); });
                        });
                        return [2 /*return*/, {
                                success: true,
                                currentTime: currentTime.toNumber(), // uint32
                                searchEndBlock: searchConfig.to,
                                events: eventsWithBlockNumber,
                            }];
                }
            });
        });
    };
    EVMSpokePoolClient.prototype.getTimeAt = function (blockNumber) {
        return _getTimeAt(this.spokePool, blockNumber);
    };
    EVMSpokePoolClient.prototype.findDeposit = function (depositId) {
        return __awaiter(this, void 0, void 0, function () {
            var deposit, result, event, elapsedMs, partialDeposit, quoteBlockNumber, outputToken;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        deposit = this.getDeposit(depositId);
                        if (deposit) {
                            return [2 /*return*/, { found: true, deposit: deposit }];
                        }
                        return [4 /*yield*/, this.queryDepositEvents(depositId)];
                    case 1:
                        result = _a.sent();
                        if ("reason" in result) {
                            return [2 /*return*/, { found: false, code: InvalidFill.DepositIdNotFound, reason: result.reason }];
                        }
                        event = result.event, elapsedMs = result.elapsedMs;
                        partialDeposit = unpackDepositEvent(spreadEventWithBlockNumber(event), this.chainId);
                        return [4 /*yield*/, this.getBlockNumber(partialDeposit.quoteTimestamp)];
                    case 2:
                        quoteBlockNumber = _a.sent();
                        outputToken = partialDeposit.outputToken.isZeroAddress()
                            ? this.getDestinationTokenForDeposit(__assign(__assign({}, partialDeposit), { quoteBlockNumber: quoteBlockNumber }))
                            : partialDeposit.outputToken;
                        deposit = __assign(__assign({}, partialDeposit), { outputToken: outputToken, quoteBlockNumber: quoteBlockNumber, fromLiteChain: this.isOriginLiteChain(partialDeposit), toLiteChain: this.isDestinationLiteChain(partialDeposit) });
                        this.logger.debug({
                            at: "SpokePoolClient#findDeposit",
                            message: "Located deposit outside of SpokePoolClient's search range",
                            deposit: deposit,
                            elapsedMs: elapsedMs,
                        });
                        return [2 /*return*/, { found: true, deposit: deposit }];
                }
            });
        });
    };
    EVMSpokePoolClient.prototype.getTimestampForBlock = function (blockNumber) {
        return _getTimestampForBlock(this.spokePool.provider, blockNumber);
    };
    EVMSpokePoolClient.prototype.queryDepositEvents = function (depositId) {
        return __awaiter(this, void 0, void 0, function () {
            var tStart, upperBound, from, chain, to, maxLookBack, events, tStop, event;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        tStart = Date.now();
                        upperBound = this.latestHeightSearched || undefined;
                        return [4 /*yield*/, findDepositBlock(this.spokePool, depositId, this.deploymentBlock, upperBound)];
                    case 1:
                        from = _a.sent();
                        chain = getNetworkName(this.chainId);
                        if (!from) {
                            return [2 /*return*/, {
                                    reason: "Unable to find ".concat(chain, " depositId ").concat(depositId, " within blocks [").concat(this.deploymentBlock, ", ").concat(upperBound !== null && upperBound !== void 0 ? upperBound : "latest", "]."),
                                }];
                        }
                        to = from;
                        maxLookBack = this.eventSearchConfig.maxLookBack;
                        return [4 /*yield*/, Promise.all([
                                paginatedEventQuery(this.spokePool, this.spokePool.filters.V3FundsDeposited(null, null, null, null, null, depositId), { from: from, to: to, maxLookBack: maxLookBack }),
                                paginatedEventQuery(this.spokePool, this.spokePool.filters.FundsDeposited(null, null, null, null, null, depositId), { from: from, to: to, maxLookBack: maxLookBack }),
                            ])];
                    case 2:
                        events = (_a.sent())
                            .flat()
                            .filter(function (_a) {
                            var args = _a.args;
                            return args["depositId"].eq(depositId);
                        });
                        tStop = Date.now();
                        event = events[0];
                        if (!event) {
                            return [2 /*return*/, {
                                    reason: "Unable to find ".concat(chain, " depositId ").concat(depositId, " within blocks [").concat(from, ", ").concat(upperBound !== null && upperBound !== void 0 ? upperBound : "latest", "]."),
                                }];
                        }
                        return [2 /*return*/, { event: event, elapsedMs: tStop - tStart }];
                }
            });
        });
    };
    return EVMSpokePoolClient;
}(SpokePoolClient));
export { EVMSpokePoolClient };
//# sourceMappingURL=EVMSpokePoolClient.js.map