"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildObligationFilters = buildObligationFilters;
exports.listenToObligationChanges = listenToObligationChanges;
const accounts_1 = require("../@codegen/klend/accounts");
const programId_1 = require("../@codegen/klend/programId");
const obligation_1 = require("./obligation");
/** Anchor accounts are prefixed with an 8-byte discriminator */
const ANCHOR_DISCRIMINATOR_BYTES = 8;
const OBLIGATION_ACCOUNT_SIZE = BigInt(accounts_1.Obligation.layout.span + ANCHOR_DISCRIMINATOR_BYTES);
function buildObligationFilters(owner) {
    return [
        { dataSize: OBLIGATION_ACCOUNT_SIZE },
        { memcmp: { offset: 64n, bytes: owner.toString(), encoding: 'base58' } },
    ];
}
/**
 * Subscribe to all obligation account changes for a given owner.
 * Returns an unsubscribe function.
 */
function listenToObligationChanges(params) {
    const programId = params.programId ?? programId_1.PROGRAM_ID;
    const filters = buildObligationFilters(params.owner);
    const getMarkets = typeof params.markets === 'function' ? params.markets : () => params.markets;
    const options = {
        // Obligations are low-frequency — use 'processed' for instant delivery
        commitment: params.commitment ?? 'processed',
    };
    return params.manager.subscribeProgramAccounts(programId, filters, (addr, buffer, slot) => {
        try {
            const obligation = obligation_1.KaminoObligation.fromAccountData(getMarkets(), addr, buffer, slot);
            if (!obligation)
                return;
            params.onChange({ obligation, address: addr, slot });
        }
        catch (e) {
            params.onError?.(e);
        }
    }, options);
}
//# sourceMappingURL=obligationListener.js.map