"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildReserveFilters = buildReserveFilters;
exports.listenToReserveChanges = listenToReserveChanges;
/**
 * Listen to real-time reserve changes via WebSocket.
 *
 * Returns raw {@link Reserve} (not KaminoReserve) — KaminoReserve needs
 * oracle prices and an RPC connection that aren't available from the WS
 * notification alone. The consumer hydrates using its market context.
 */
const kit_1 = require("@solana/kit");
const accounts_1 = require("../@codegen/klend/accounts");
const programId_1 = require("../@codegen/klend/programId");
const anchorConstants_1 = require("./anchorConstants");
const createManagerSubscription_1 = require("./createManagerSubscription");
const utils_1 = require("./utils");
const RESERVE_ACCOUNT_SIZE = BigInt(accounts_1.Reserve.layout.span + anchorConstants_1.ANCHOR_DISCRIMINATOR_BYTES);
const RESERVE_DISCRIMINATOR_BASE58 = (0, kit_1.getBase58Decoder)().decode(accounts_1.Reserve.discriminator);
function buildReserveFilters(marketAddress) {
    return [
        { dataSize: RESERVE_ACCOUNT_SIZE },
        { memcmp: { offset: 32n, bytes: marketAddress.toString(), encoding: 'base58' } },
        // Match Reserve's 8-byte Anchor discriminator so uninitialized klend-owned
        // accounts with the same 8624-byte layout (e.g. pre-allocated placeholders
        // awaiting init_reserve) don't trigger spurious decode errors.
        { memcmp: { offset: 0n, bytes: RESERVE_DISCRIMINATOR_BASE58, encoding: 'base58' } },
    ];
}
function listenToReserveChanges(params) {
    return (0, createManagerSubscription_1.createManagerSubscription)({
        manager: params.manager,
        programId: params.programId ?? programId_1.PROGRAM_ID,
        filters: buildReserveFilters(params.marketAddress),
        commitment: params.commitment ?? 'confirmed',
        throttleMs: params.throttleMs,
        scheduler: params.scheduler,
        decode: (address, buffer, slot) => ({
            reserve: accounts_1.Reserve.decode((0, utils_1.toBuffer)(buffer)),
            address,
            slot,
        }),
        onChange: params.onChange,
        onError: params.onError,
        errorPrefix: '[listenToReserveChanges]',
    });
}
//# sourceMappingURL=reserveListener.js.map