> ## Documentation Index
> Fetch the complete documentation index at: https://docs.orbitflare.com/llms.txt
> Use this file to discover all available pages before exploring further.

# JetStream-клиент

> Декодированные шреды OrbitFlare как gRPC-стримы с фильтрами транзакций и аккаунтов.

## Установка

```bash theme={null}
npm install @orbitflare/sdk @grpc/grpc-js yaml
```

`@grpc/grpc-js` и `yaml` - опциональные peer-зависимости. Устанавливайте их, только если используете JetStream (или YAML-конфиг).

## Сборка клиента

```ts theme={null}
import { JetstreamClientBuilder } from '@orbitflare/sdk/jetstream';
import type { RetryPolicy } from '@orbitflare/sdk';

const client = new JetstreamClientBuilder()
  .url('http://ny.jetstream.orbitflare.com')
  .fallbackUrl('http://fra.jetstream.orbitflare.com')
  .retry({
    initialDelayMs: 100,
    maxDelayMs: 30_000,
    multiplier: 2.0,
    maxAttempts: 0,
  })
  .timeoutSecs(30)
  .keepaliveSecs(60)
  .pingIntervalSecs(10)
  .maxMissedPongs(3)
  .channelCapacity(4096)
  .build();
```

Минимально:

```ts theme={null}
const client = new JetstreamClientBuilder()
  .url('http://ny.jetstream.orbitflare.com')
  .build();
```

URL по умолчанию берётся из `ORBITFLARE_JETSTREAM_URL`. Все методы билдера те же, что у [gRPC-клиента](/ru/sdk/typescript-grpc) - те же дефолты и поведение.

## Написание YAML-конфига

JetStream поддерживает фильтры транзакций и аккаунтов. Слоты, блоки и commitment - специфичны для Yellowstone, здесь их нет.

```yaml theme={null}
# jetstream.yml
transactions:
  raydium:
    account_include:
      - "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"
  pumpfun:
    account_include:
      - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"

accounts:
  my_wallet:
    account:
      - "YOUR_WALLET_ADDRESS"
    owner:
      - "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
```

### Справочник фильтров YAML

**`transactions`** - именованные фильтры. `account_include` совпадает с транзакциями, где задействованы эти адреса. `account_exclude` исключает. `account_required` - все перечисленные адреса должны быть в транзакции.

**`accounts`** - следить за конкретными адресами через `account` или за всеми аккаунтами программы через `owner`.

Поддерживается подстановка `${ENV_VAR}`.

## Подписка и чтение событий

### Из YAML

```ts theme={null}
const stream = client.subscribeYaml('jetstream.yml');
```

### Программно

```ts theme={null}
import { proto } from '@orbitflare/sdk/proto';

const request: proto.jetstream.SubscribeRequest = {
  transactions: {
    target: {
      accountInclude: [someAddress],
      accountExclude: [],
      accountRequired: [],
    },
  },
  accounts: {},
  ping: { id: 1 },
};

const stream = client.subscribe(request);
```

### Чтение потока

```ts theme={null}
for await (const update of stream) {
  if (update.transaction) {
    // update.transaction.slot - the slot number
    // update.transaction.transaction - transaction info with signature, accountKeys,
    //   instructions, addressTableLookups
  } else if (update.account) {
    // update.account.slot - the slot
    // update.account.account - account info (pubkey, lamports, owner, data)
    // update.account.isStartup - true during initial snapshot
  }
}
```

Закрытие, несколько потоков, переподключение и ping/pong работают так же, как у [gRPC-клиента](/ru/sdk/typescript-grpc).

## Полный пример

Поток следит за свопами Raydium AMM и выводит подпись и число инструкций каждой транзакции.

```ts theme={null}
import bs58 from 'bs58';
import { JetstreamClientBuilder } from '@orbitflare/sdk/jetstream';

async function main() {
  const client = new JetstreamClientBuilder()
    .url('http://ny.jetstream.orbitflare.com')
    .build();

  const stream = client.subscribeYaml('jetstream.yml');
  let count = 0;

  console.log('streaming raydium txs...');

  for await (const update of stream) {
    if (update.transaction) {
      count += 1;
      const info = update.transaction.transaction;
      if (info?.signature) {
        const sig = bs58.encode(info.signature);
        const numIx = info.instructions.length;
        const numAccounts = info.accountKeys.length;
        console.log(
          `#${count} slot=${update.transaction.slot} sig=${sig.slice(0, 16)}... ix=${numIx} accounts=${numAccounts}`,
        );
      }
    }
  }
}

void main();
```

С этим `jetstream.yml`:

```yaml theme={null}
transactions:
  raydium:
    account_include:
      - "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"
```
