"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.decodeTokenAccountAmount = decodeTokenAccountAmount;
exports.extractTokenAccountMintBytes = extractTokenAccountMintBytes;
exports.buildTokenBalanceFilters = buildTokenBalanceFilters;
exports.listenToTokenBalanceChanges = listenToTokenBalanceChanges;
exports.listenToNativeSolBalance = listenToNativeSolBalance;
const createManagerSubscription_1 = require("./createManagerSubscription");
const createStandaloneSubscription_1 = require("./createStandaloneSubscription");
/** u64 amount at SPL Token offset 64. */
function decodeTokenAccountAmount(data) {
    const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
    return view.getBigUint64(64, true);
}
/** 32-byte mint at SPL Token offset 0. */
function extractTokenAccountMintBytes(data) {
    return data.slice(0, 32);
}
/**
 * Owner memcmp only (no dataSize) so this matches both standard SPL Token
 * accounts (165 bytes) and Token-2022 accounts with extensions. Owner is at
 * offset 32 in both layouts.
 */
function buildTokenBalanceFilters(owner) {
    return [{ memcmp: { offset: 32n, bytes: owner.toString(), encoding: 'base58' } }];
}
/**
 * TODO: Monitor whether programSubscribe on the Token Program causes
 * connection instability under high server-side write volume — if so,
 * fall back to per-ATA accountSubscribe.
 */
function listenToTokenBalanceChanges(params) {
    return (0, createManagerSubscription_1.createManagerSubscription)({
        manager: params.manager,
        programId: params.tokenProgramId,
        filters: buildTokenBalanceFilters(params.owner),
        commitment: 'confirmed',
        onReconnect: params.onReconnect,
        throttleMs: params.throttleMs,
        scheduler: params.scheduler,
        decode: (ataAddress, buffer, slot) => ({
            ataAddress,
            amount: decodeTokenAccountAmount(buffer),
            mintBytes: extractTokenAccountMintBytes(buffer),
            slot,
        }),
        onChange: params.onBalanceChange,
        onError: params.onError,
        errorPrefix: '[listenToTokenBalanceChanges]',
    });
}
function listenToNativeSolBalance(params) {
    const commitment = params.commitment ?? 'confirmed';
    return (0, createStandaloneSubscription_1.createStandaloneSubscription)({
        ...params,
        onChange: params.onBalanceChange,
        subscribe: (wsRpc, abortSignal) => wsRpc.accountNotifications(params.owner, { commitment, encoding: 'base64' }).subscribe({ abortSignal }),
        toEvent: ({ context, value }) => ({ lamports: value.lamports, slot: context.slot }),
        errorPrefix: '[listenToNativeSolBalance]',
        callSiteName: 'listenToNativeSolBalance',
    });
}
//# sourceMappingURL=balanceListener.js.map