createAsyncGeneratorWithInitialValueAndSlotTracking

function createAsyncGeneratorWithInitialValueAndSlotTracking<
    TRpcValue,
    TSubscriptionValue,
    TItem,
>(
    config,
): AsyncGenerator<
    Readonly<{
        context: Readonly<{
            slot: Slot;
        }>;
        value: TItem;
    }>
>;

Creates an async generator that combines an initial RPC fetch with an ongoing subscription, yielding values as they arrive from either source.

The generator uses slot-based comparison to ensure that only the most recent values are yielded. Any value at a slot older than a previously yielded value is silently dropped. This prevents stale data from appearing when the RPC response and subscription notifications arrive out of order.

Things to note:

  • The generator yields SolanaRpcResponse values from both the RPC response and subscription notifications, each containing the slot context and the mapped value.
  • Out-of-order values (by slot) are silently dropped — they are never yielded.
  • On error from either source, the generator throws the error.
  • Triggering the caller's abort signal causes the generator to return (complete without error).
  • The generator completes when the subscription ends, an error occurs, or the abort signal fires.

Type Parameters

Type Parameter
TRpcValue
TSubscriptionValue
TItem

Parameters

ParameterTypeDescription
configCreateAsyncGeneratorWithInitialValueAndSlotTrackingConfig<TRpcValue, TSubscriptionValue, TItem>-

Returns

AsyncGenerator<Readonly<{ context: Readonly<{ slot: Slot; }>; value: TItem; }>>

Example

import {
    address,
    createAsyncGeneratorWithInitialValueAndSlotTracking,
    createSolanaRpc,
    createSolanaRpcSubscriptions,
} from '@solana/kit';
 
const rpc = createSolanaRpc('http://127.0.0.1:8899');
const rpcSubscriptions = createSolanaRpcSubscriptions('ws://127.0.0.1:8900');
const myAddress = address('FnHyam9w4NZoWR6mKN1CuGBritdsEWZQa4Z4oawLZGxa');
 
const abortController = new AbortController();
for await (const balance of createAsyncGeneratorWithInitialValueAndSlotTracking({
    abortSignal: abortController.signal,
    rpcRequest: rpc.getBalance(myAddress, { commitment: 'confirmed' }),
    rpcValueMapper: lamports => lamports,
    rpcSubscriptionRequest: rpcSubscriptions.accountNotifications(myAddress),
    rpcSubscriptionValueMapper: ({ lamports }) => lamports,
})) {
    console.log(`Balance at slot ${balance.context.slot}:`, balance.value);
}

On this page