# Omen quick start (/omen/quickstart)

> Stream pre-execution Solana transactions from Omen in Node.js, Rust or Go: raw-key filters, conn_seq gap checks, Resume on reconnect and backoff.



This gets you a working Omen transaction stream that survives disconnects. Every example does the same five things:

1. Connects over plaintext HTTP/2 with insecure channel credentials.
2. Subscribes `sub_id` 0 to transactions touching one account, passed as a **raw 32-byte key**.
3. Checks that `conn_seq` rises by exactly 1 on every frame.
4. On reconnect, sends `Resume{from_slot}` as the first message and drops the replayed transactions it already handled.
5. Backs off with jitter, never sooner than the server's `retry_after_ms`.

| You need                                                                                                                                            | Where it comes from                                                                                                   |
| --------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| Omen access for your server's public egress IP in the metro you connect to                                                                          | [Dashboard](https://dashboard.corvus-labs.io) (listed as aRPC v3); see [access and pricing](/omen#access-and-pricing) |
| The metro's endpoint                                                                                                                                | [Regions & endpoints](/omen/regions); the examples use `fra`                                                          |
| Node.js 20+, Rust with `protoc`, or Go 1.26+ with `protoc` (current gRPC-Go needs it; with the default `GOTOOLCHAIN=auto` an older `go` fetches it) | —                                                                                                                     |

<Steps>
  <Step>
    ### Download the proto

    ```bash
    mkdir -p proto/omen

    curl -fsSLo proto/omen/arpc.proto \
      https://docs.corvus-labs.io/proto/omen/arpc.proto
    ```

    The file declares `package arpc`, like the legacy aRPC proto. Keep it out of any build that also compiles the legacy one ([package name](/omen/api#package-name)).
  </Step>

  <Step>
    ### Write the client

    <Tabs items={['Node.js', 'Rust', 'Go']}>
      <Tab value="Node.js">
        ```bash
        npm install @grpc/grpc-js@^1.13 @grpc/proto-loader
        ```

        Create `subscribe.js`. The proto loads at runtime, so there's no code-generation step.

        ```javascript
        const grpc = require('@grpc/grpc-js');
        const protoLoader = require('@grpc/proto-loader');

        const ENDPOINT = 'http://omen.fra.corvus-labs.io:30303';
        // Token program. Any base58 account address works.
        const ACCOUNT = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';

        const definition = protoLoader.loadSync('./proto/omen/arpc.proto', {
          keepCase: true,
          longs: String,
          enums: String,
          defaults: true,
          bytes: Buffer, // keys and signatures stay raw bytes
          oneofs: true, // msg.payload names the oneof arm that is set
        });
        const omen = grpc.loadPackageDefinition(definition).arpc;

        // Omen filters take raw 32-byte keys, not base58 strings.
        const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';

        function base58ToKey(text) {
          let n = 0n;
          for (const c of text) {
            const digit = ALPHABET.indexOf(c);
            if (digit < 0) throw new Error(`invalid base58 in ${text}`);
            n = n * 58n + BigInt(digit);
          }
          const hex = n.toString(16).padStart(64, '0');
          if (hex.length !== 64) throw new Error(`${text} is not a 32-byte key`);
          return Buffer.from(hex, 'hex');
        }

        function toBase58(bytes) {
          let n = BigInt('0x' + (bytes.toString('hex') || '0'));
          let out = '';
          while (n > 0n) {
            out = ALPHABET[Number(n % 58n)] + out;
            n /= 58n;
          }
          for (const b of bytes) {
            if (b !== 0) break;
            out = '1' + out;
          }
          return out;
        }

        const ACCOUNT_KEY = base58ToKey(ACCOUNT);

        // State kept across reconnects.
        let resumeSlot = null; // sent as Resume{from_slot} on the next connection
        const seen = new Map(); // slot -> Set of positions already handled
        let attempt = 0;

        // False for a transaction already handled (the replayed tail after a Resume).
        function firstTime(slot, position) {
          let positions = seen.get(slot);
          if (!positions) {
            positions = new Set();
            seen.set(slot, positions);
            for (const old of seen.keys()) {
              if (old < slot - 1000) seen.delete(old);
            }
          }
          if (positions.has(position)) return false;
          positions.add(position);
          return true;
        }

        // Jittered exponential backoff, never shorter than the server's retry_after_ms.
        function backoff(retryAfterMs) {
          const exp = Math.min(250 * 2 ** Math.min(attempt, 7), 30_000);
          return Math.max(exp / 2 + Math.random() * (exp / 2), retryAfterMs);
        }

        // A refusal's grpc-message is JSON and may carry retry_after_ms.
        function retryAfterFrom(details) {
          try {
            return Number(JSON.parse(details).retry_after_ms) || 0;
          } catch {
            return 0;
          }
        }

        // One connection. Resolves with a retry_after_ms floor for the next attempt.
        function session() {
          const { host } = new URL(ENDPOINT); // grpc-js dials host:port, no scheme
          const client = new omen.aRPC(host, grpc.credentials.createInsecure(), {
            // One Subscribe stream per connection: never share it with another client.
            'grpc.use_local_subchannel_pool': 1,
            // grpc-js's 64 KiB default window can starve a busy stream.
            'grpc-node.flow_control_window': 8 * 1024 * 1024,
          });

          return new Promise((resolve) => {
            let finished = false;
            let lastConnSeq = null;
            const call = client.Subscribe();

            const finish = (retryAfterMs = 0) => {
              if (finished) return;
              finished = true;
              call.cancel();
              grpc.closeClient(client);
              resolve(retryAfterMs);
            };

            // Resume, when present, must be the first message on the stream.
            if (resumeSlot !== null) {
              call.write({ resume: { from_slot: resumeSlot } });
            }
            // The default: a reader that falls behind is closed, then resumes.
            call.write({ config: { on_lag: 'ON_LAG_CLOSE' } });
            call.write({
              subscribe: {
                sub_id: 0,
                transactions: {
                  account_include: [ACCOUNT_KEY],
                  exclude_votes: true,
                  encoding: 'TRANSACTION_ENCODING_BINARY',
                },
              },
            });

            call.on('data', (msg) => {
              if (finished) return;

              // conn_seq rises by exactly 1 on every frame, control frames included.
              const connSeq = BigInt(msg.conn_seq);
              if (lastConnSeq !== null && connSeq !== lastConnSeq + 1n) {
                console.error(`conn_seq gap: expected ${lastConnSeq + 1n}, got ${connSeq}`);
                return finish();
              }
              lastConnSeq = connSeq;

              switch (msg.payload) {
                case 'binary_transaction': {
                  const tx = msg.binary_transaction;
                  resumeSlot = tx.slot;
                  const position = `${tx.batch_index}:${tx.entry_index}:${tx.tx_index}`;
                  if (!firstTime(Number(tx.slot), position)) break;
                  console.log('tx', {
                    slot: tx.slot,
                    signature: toBase58(tx.signature),
                    bytes: tx.transaction.length,
                    replayed: msg.replayed,
                  });
                  break;
                }
                case 'heartbeat':
                  // Nothing matched up to this slot; resume from here.
                  resumeSlot = msg.heartbeat.slot;
                  break;
                case 'retract':
                  console.log(`slot ${msg.retract.slot} retracted: ${msg.retract.reason}`);
                  break;
                case 'ack': {
                  const { sub_id, accepted, reason } = msg.ack;
                  if (!accepted) {
                    console.error(`subscription ${sub_id} rejected: ${reason}`);
                    process.exit(1);
                  }
                  attempt = 0;
                  console.log(`subscription ${sub_id} accepted`);
                  break;
                }
                case 'error': {
                  const { code, message, retry_after_ms } = msg.error;
                  if (code === 'ERROR_CODE_FLOW_CONTROL_LIMITED') {
                    console.warn('flow control: raise grpc-node.flow_control_window');
                    break;
                  }
                  console.error(`stream error ${code}: ${message}`);
                  if (code === 'ERROR_CODE_OUT_OF_RANGE') {
                    resumeSlot = null; // too old to replay: rejoin live, backfill via Solana RPC
                  }
                  return finish(retry_after_ms);
                }
                case 'replay_done':
                  console.log('replay complete, now live');
                  break;
                default:
                  break; // pong, gap, ... still count toward conn_seq
              }
            });

            call.on('error', (err) => {
              if (finished) return;
              if (err.code === grpc.status.UNAUTHENTICATED || err.code === grpc.status.PERMISSION_DENIED) {
                console.error(`access refused: ${err.details}`);
                process.exit(1);
              }
              console.error(`stream closed: ${grpc.status[err.code]} ${err.details}`);
              finish(retryAfterFrom(err.details));
            });
            call.on('end', () => finish());
          });
        }

        async function main() {
          for (;;) {
            const delay = backoff(await session());
            attempt += 1;
            console.error(`reconnecting in ${Math.round(delay)} ms`);
            await new Promise((r) => setTimeout(r, delay));
          }
        }

        main();
        ```

        Run it:

        ```bash
        node subscribe.js
        ```
      </Tab>

      <Tab value="Rust">
        `tonic-build` needs `protoc` on your `PATH`. Put the downloaded `proto/` directory in the crate root.

        `Cargo.toml`:

        ```toml
        [package]
        name = "omen-quickstart"
        version = "0.1.0"
        edition = "2021"

        [dependencies]
        bs58 = "0.5"
        prost = "0.13"
        rand = "0.8"
        serde_json = "1"
        tokio = { version = "1", features = ["macros", "rt-multi-thread", "time", "sync"] }
        tokio-stream = "0.1"
        tonic = "0.12"

        [build-dependencies]
        tonic-build = "0.12"
        ```

        `build.rs`:

        ```rust
        fn main() -> Result<(), Box<dyn std::error::Error>> {
            tonic_build::configure()
                .build_server(false)
                .compile_protos(&["proto/omen/arpc.proto"], &["proto/omen"])?;
            Ok(())
        }
        ```

        `src/main.rs`:

        ```rust
        use std::collections::{BTreeMap, HashSet};
        use std::time::Duration;

        use rand::Rng;
        use tokio::sync::mpsc;
        use tokio_stream::wrappers::ReceiverStream;
        use tonic::transport::Channel;
        use tonic::{Code, Status};

        pub mod omen {
            tonic::include_proto!("arpc");
        }
        use omen::a_rpc_client::ARpcClient;
        use omen::server_message::Payload;
        use omen::{
            client_message::Msg, subscription_request::Kind, AckReason, ClientMessage, ConnectionConfig,
            ErrorCode, OnLag, Resume, SubscriptionRequest, TransactionEncoding, TransactionSubscription,
        };

        const ENDPOINT: &str = "http://omen.fra.corvus-labs.io:30303";
        // Token program. Any base58 account address works.
        const ACCOUNT: &str = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";

        /// State kept across reconnects.
        #[derive(Default)]
        struct State {
            resume_slot: Option<u64>,
            seen: BTreeMap<u64, HashSet<(u32, u32, u32)>>,
            attempt: u32,
        }

        impl State {
            /// False for a transaction already handled (the replayed tail after a Resume).
            fn first_time(&mut self, slot: u64, position: (u32, u32, u32)) -> bool {
                while self.seen.len() > 1000 {
                    self.seen.pop_first();
                }
                self.seen.entry(slot).or_default().insert(position)
            }
        }

        enum End {
            Retry { after_ms: u64 },
            Fatal(String),
        }

        #[tokio::main]
        async fn main() {
            // Omen filters take raw 32-byte keys, not base58 strings.
            let key = bs58::decode(ACCOUNT).into_vec().expect("valid base58");
            assert_eq!(key.len(), 32, "account keys are 32 bytes");

            let mut state = State::default();
            loop {
                match session(&key, &mut state).await {
                    End::Fatal(why) => {
                        eprintln!("giving up: {why}");
                        return;
                    }
                    End::Retry { after_ms } => {
                        let delay = backoff(state.attempt, after_ms);
                        state.attempt += 1;
                        eprintln!("reconnecting in {delay:?}");
                        tokio::time::sleep(delay).await;
                    }
                }
            }
        }

        /// Jittered exponential backoff, never shorter than the server's retry_after_ms.
        fn backoff(attempt: u32, retry_after_ms: u64) -> Duration {
            let exp = (250u64 << attempt.min(7)).min(30_000);
            let jittered = exp / 2 + rand::thread_rng().gen_range(0..=exp / 2);
            Duration::from_millis(jittered.max(retry_after_ms))
        }

        fn on_status(status: Status) -> End {
            if matches!(status.code(), Code::Unauthenticated | Code::PermissionDenied) {
                return End::Fatal(format!("access refused: {}", status.message()));
            }
            eprintln!("stream closed: {:?} {}", status.code(), status.message());
            // A refusal's grpc-message is JSON and may carry retry_after_ms.
            let after_ms = serde_json::from_str::<serde_json::Value>(status.message())
                .ok()
                .and_then(|v| v["retry_after_ms"].as_u64())
                .unwrap_or(0);
            End::Retry { after_ms }
        }

        /// One connection.
        async fn session(key: &[u8], state: &mut State) -> End {
            // One Subscribe stream per connection: each session dials its own channel.
            let channel = match Channel::from_static(ENDPOINT).connect().await {
                Ok(channel) => channel,
                Err(e) => {
                    eprintln!("connect failed: {e}");
                    return End::Retry { after_ms: 0 };
                }
            };

            let (tx, rx) = mpsc::channel(16);
            let mut first = Vec::new();
            // Resume, when present, must be the first message on the stream.
            if let Some(from_slot) = state.resume_slot {
                first.push(Msg::Resume(Resume { from_slot }));
            }
            // The default: a reader that falls behind is closed, then resumes.
            first.push(Msg::Config(ConnectionConfig { on_lag: OnLag::Close as i32 }));
            first.push(Msg::Subscribe(SubscriptionRequest {
                sub_id: 0,
                kind: Some(Kind::Transactions(TransactionSubscription {
                    account_include: vec![key.to_vec()],
                    exclude_votes: true,
                    encoding: TransactionEncoding::Binary as i32,
                    ..Default::default()
                })),
                policy: None,
            }));
            for msg in first {
                tx.send(ClientMessage { msg: Some(msg) }).await.expect("queue has room");
            }
            // `tx` stays alive until this function returns, keeping the request side open.

            let mut stream = match ARpcClient::new(channel)
                .subscribe(ReceiverStream::new(rx))
                .await
            {
                Ok(response) => response.into_inner(),
                Err(status) => return on_status(status),
            };

            let mut last_conn_seq: Option<u64> = None;
            loop {
                let msg = match stream.message().await {
                    Ok(Some(msg)) => msg,
                    Ok(None) => return End::Retry { after_ms: 0 },
                    Err(status) => return on_status(status),
                };

                // conn_seq rises by exactly 1 on every frame, control frames included.
                if let Some(prev) = last_conn_seq {
                    if msg.conn_seq != prev + 1 {
                        eprintln!("conn_seq gap: expected {}, got {}", prev + 1, msg.conn_seq);
                        return End::Retry { after_ms: 0 };
                    }
                }
                last_conn_seq = Some(msg.conn_seq);

                match msg.payload {
                    Some(Payload::BinaryTransaction(t)) => {
                        state.resume_slot = Some(t.slot);
                        if !state.first_time(t.slot, (t.batch_index, t.entry_index, t.tx_index)) {
                            continue;
                        }
                        println!(
                            "tx slot={} sig={} bytes={} replayed={}",
                            t.slot,
                            bs58::encode(&t.signature).into_string(),
                            t.transaction.len(),
                            msg.replayed,
                        );
                    }
                    // Nothing matched up to this slot; resume from here.
                    Some(Payload::Heartbeat(h)) => state.resume_slot = Some(h.slot),
                    Some(Payload::Retract(r)) => println!("slot {} retracted: {:?}", r.slot, r.reason()),
                    Some(Payload::Ack(a)) => {
                        if !a.accepted {
                            return match a.reason() {
                                AckReason::ServerResources
                                | AckReason::FilterTooBroad
                                | AckReason::CuckooFilterLimit => End::Retry { after_ms: 0 },
                                reason => End::Fatal(format!("subscription {} rejected: {reason:?}", a.sub_id)),
                            };
                        }
                        state.attempt = 0;
                        println!("subscription {} accepted", a.sub_id);
                    }
                    Some(Payload::Error(e)) => match e.code() {
                        ErrorCode::FlowControlLimited => {
                            eprintln!("flow control: raise the HTTP/2 window");
                        }
                        code => {
                            eprintln!("stream error {code:?}: {}", e.message);
                            if code == ErrorCode::OutOfRange {
                                // Too old to replay: rejoin live, backfill via Solana RPC.
                                state.resume_slot = None;
                            }
                            return End::Retry { after_ms: u64::from(e.retry_after_ms) };
                        }
                    },
                    Some(Payload::ReplayDone(_)) => println!("replay complete, now live"),
                    _ => {} // pong, gap, ... still count toward conn_seq
                }
            }
        }
        ```

        Run it:

        ```bash
        cargo run --release
        ```
      </Tab>

      <Tab value="Go">
        Generate the stubs. The proto has no `go_package` option, so map it to your module on the command line with `M`:

        ```bash
        go mod init example.com/omen-quickstart

        go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
        go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
        export PATH="$PATH:$(go env GOPATH)/bin"

        protoc -I proto/omen \
          --go_out=. --go_opt=module=example.com/omen-quickstart \
          --go_opt=Marpc.proto=example.com/omen-quickstart/gen \
          --go-grpc_out=. --go-grpc_opt=module=example.com/omen-quickstart \
          --go-grpc_opt=Marpc.proto=example.com/omen-quickstart/gen \
          arpc.proto
        ```

        Create `main.go`:

        ```go
        package main

        import (
        	"context"
        	"encoding/json"
        	"fmt"
        	"math/rand"
        	"os"
        	"time"

        	"github.com/mr-tron/base58"
        	"google.golang.org/grpc"
        	"google.golang.org/grpc/codes"
        	"google.golang.org/grpc/credentials/insecure"
        	"google.golang.org/grpc/status"

        	pb "example.com/omen-quickstart/gen"
        )

        const (
        	target  = "omen.fra.corvus-labs.io:30303"                // grpc-go dials host:port, no scheme
        	account = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" // Token program
        )

        type position struct{ batch, entry, tx uint32 }

        // State kept across reconnects.
        var (
        	resumeSlot uint64
        	haveResume bool
        	seen       = map[uint64]map[position]bool{}
        	attempt    int
        )

        func main() {
        	// Omen filters take raw 32-byte keys, not base58 strings.
        	key, err := base58.Decode(account)
        	if err != nil || len(key) != 32 {
        		panic("account must be a base58 32-byte key")
        	}
        	for {
        		retryAfterMs, fatal := session(key)
        		if fatal != nil {
        			fmt.Fprintln(os.Stderr, "giving up:", fatal)
        			os.Exit(1)
        		}
        		delay := backoff(retryAfterMs)
        		attempt++
        		fmt.Fprintf(os.Stderr, "reconnecting in %v\n", delay)
        		time.Sleep(delay)
        	}
        }

        // Jittered exponential backoff, never shorter than the server's retry_after_ms.
        func backoff(retryAfterMs uint64) time.Duration {
        	exp := 250 << min(attempt, 7)
        	if exp > 30000 {
        		exp = 30000
        	}
        	ms := max(uint64(exp/2+rand.Intn(exp/2+1)), retryAfterMs)
        	return time.Duration(ms) * time.Millisecond
        }

        // firstTime is false for a transaction already handled (the replayed tail after a Resume).
        func firstTime(slot uint64, pos position) bool {
        	if seen[slot] == nil {
        		seen[slot] = map[position]bool{}
        		for s := range seen {
        			if s+1000 < slot {
        				delete(seen, s)
        			}
        		}
        	}
        	if seen[slot][pos] {
        		return false
        	}
        	seen[slot][pos] = true
        	return true
        }

        // A refusal's grpc-message is JSON and may carry retry_after_ms.
        func retryAfter(err error) uint64 {
        	var body struct {
        		RetryAfterMs uint64 `json:"retry_after_ms"`
        	}
        	_ = json.Unmarshal([]byte(status.Convert(err).Message()), &body)
        	return body.RetryAfterMs
        }

        // session runs one connection and returns a retry_after_ms floor, or a fatal error.
        func session(key []byte) (uint64, error) {
        	// One Subscribe stream per connection: each session dials its own client.
        	conn, err := grpc.NewClient(target, grpc.WithTransportCredentials(insecure.NewCredentials()))
        	if err != nil {
        		return 0, err
        	}
        	defer conn.Close()

        	ctx, cancel := context.WithCancel(context.Background())
        	defer cancel()
        	stream, err := pb.NewARPCClient(conn).Subscribe(ctx)
        	if err != nil {
        		return retryAfter(err), nil
        	}
        	send := func(m *pb.ClientMessage) { _ = stream.Send(m) } // a failed send surfaces on Recv

        	// Resume, when present, must be the first message on the stream.
        	if haveResume {
        		send(&pb.ClientMessage{Msg: &pb.ClientMessage_Resume{Resume: &pb.Resume{FromSlot: resumeSlot}}})
        	}
        	// The default: a reader that falls behind is closed, then resumes.
        	send(&pb.ClientMessage{Msg: &pb.ClientMessage_Config{Config: &pb.ConnectionConfig{OnLag: pb.OnLag_ON_LAG_CLOSE}}})
        	send(&pb.ClientMessage{Msg: &pb.ClientMessage_Subscribe{Subscribe: &pb.SubscriptionRequest{
        		SubId: 0,
        		Kind: &pb.SubscriptionRequest_Transactions{Transactions: &pb.TransactionSubscription{
        			AccountInclude: [][]byte{key},
        			ExcludeVotes:   true,
        			Encoding:       pb.TransactionEncoding_TRANSACTION_ENCODING_BINARY,
        		}},
        	}}})

        	var lastConnSeq uint64
        	first := true
        	for {
        		msg, err := stream.Recv()
        		if err != nil {
        			switch status.Code(err) {
        			case codes.Unauthenticated, codes.PermissionDenied:
        				return 0, fmt.Errorf("access refused: %s", status.Convert(err).Message())
        			}
        			fmt.Fprintln(os.Stderr, "stream closed:", err)
        			return retryAfter(err), nil
        		}

        		// conn_seq rises by exactly 1 on every frame, control frames included.
        		if !first && msg.ConnSeq != lastConnSeq+1 {
        			fmt.Fprintf(os.Stderr, "conn_seq gap: expected %d, got %d\n", lastConnSeq+1, msg.ConnSeq)
        			return 0, nil
        		}
        		first, lastConnSeq = false, msg.ConnSeq

        		switch p := msg.Payload.(type) {
        		case *pb.ServerMessage_BinaryTransaction:
        			t := p.BinaryTransaction
        			resumeSlot, haveResume = t.Slot, true
        			if !firstTime(t.Slot, position{t.BatchIndex, t.EntryIndex, t.TxIndex}) {
        				continue
        			}
        			fmt.Printf("tx slot=%d sig=%s bytes=%d replayed=%v\n",
        				t.Slot, base58.Encode(t.Signature), len(t.Transaction), msg.Replayed)
        		case *pb.ServerMessage_Heartbeat:
        			// Nothing matched up to this slot; resume from here.
        			resumeSlot, haveResume = p.Heartbeat.Slot, true
        		case *pb.ServerMessage_Retract:
        			fmt.Printf("slot %d retracted: %v\n", p.Retract.Slot, p.Retract.Reason)
        		case *pb.ServerMessage_Ack:
        			a := p.Ack
        			if !a.Accepted {
        				switch a.Reason {
        				case pb.AckReason_ACK_REASON_SERVER_RESOURCES,
        					pb.AckReason_ACK_REASON_FILTER_TOO_BROAD,
        					pb.AckReason_ACK_REASON_CUCKOO_FILTER_LIMIT:
        					return 0, nil
        				}
        				return 0, fmt.Errorf("subscription %d rejected: %v", a.SubId, a.Reason)
        			}
        			attempt = 0
        			fmt.Printf("subscription %d accepted\n", a.SubId)
        		case *pb.ServerMessage_Error:
        			e := p.Error
        			if e.Code == pb.ErrorCode_ERROR_CODE_FLOW_CONTROL_LIMITED {
        				fmt.Fprintln(os.Stderr, "flow control: raise the HTTP/2 window")
        				continue
        			}
        			fmt.Fprintf(os.Stderr, "stream error %v: %s\n", e.Code, e.Message)
        			if e.Code == pb.ErrorCode_ERROR_CODE_OUT_OF_RANGE {
        				haveResume = false // too old to replay: rejoin live, backfill via Solana RPC
        			}
        			return uint64(e.RetryAfterMs), nil
        		case *pb.ServerMessage_ReplayDone:
        			fmt.Println("replay complete, now live")
        		}
        		// pong, gap, ... still count toward conn_seq
        	}
        }
        ```

        Run it:

        ```bash
        go mod tidy
        go run .
        ```
      </Tab>
    </Tabs>
  </Step>
</Steps>

You should see `subscription 0 accepted`, then a line per Token-program transaction. With no matching traffic for 10 seconds, a `Heartbeat` keeps the stream alive.

## Verify the stream

| Symptom                                                                           | Cause                                                          | Fix                                                                                                              |
| --------------------------------------------------------------------------------- | -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `UNAUTHENTICATED` (16), detail `no authenticated identity for connection`         | Your egress IP isn't known in this metro                       | Register the IP your traffic actually leaves from, in this metro                                                 |
| `PERMISSION_DENIED` (7), detail `identity is not scoped to the requested service` | No Omen order or holder access for this IP in this metro       | Buy Omen for this metro and IP, or connect from a pass IP in a holder metro ([access](/omen#access-and-pricing)) |
| `FAILED_PRECONDITION` (9)                                                         | A second `Subscribe` on a connection that already has one      | One stream per connection; in grpc-js set `grpc.use_local_subchannel_pool`                                       |
| `UNIMPLEMENTED` (12)                                                              | gzip or zstd request compression                               | Turn compression off                                                                                             |
| `subscription 0 rejected: ACK_REASON_INVALID_FILTER`                              | A key that isn't 32 bytes, often a base58 string sent as bytes | Decode the address to its 32 raw bytes                                                                           |
| Accepted, then nothing but heartbeats                                             | The filter matches nothing                                     | Widen it, or try a busy program like the Token program above                                                     |
| `StreamError` `ERROR_CODE_FLOW_CONTROL_LIMITED`                                   | Your HTTP/2 receive window is too small                        | Raise it ([flow control](/omen/limits#flow-control))                                                             |

## Reconnect

The examples already do this. The rules behind it:

1. Each connection carries one `Subscribe` stream and starts with nothing: send your subscriptions again.
2. Send `Resume{from_slot}` **first**, with the last slot you handled. The server replays what it still holds from that slot (each replayed frame has `replayed = true`), sends `ReplayComplete`, then continues live.
3. Drop replayed transactions you already handled, keyed on `(slot, batch_index, entry_index, tx_index)`.
4. If the slot is older than the retention window (about two minutes), you get `ERROR_CODE_OUT_OF_RANGE`. Reconnect without `Resume` and backfill the gap through [Solana RPC](/solana-rpc).
5. Wait at least `retry_after_ms` when the server gives one, in a `StreamError` or in the JSON `grpc-message` of a refusal.

`conn_seq` restarts with every connection. Within one, it rises by exactly 1 per frame, so a gap is a transport bug: reconnect with `Resume` and tell us on [Discord](https://discord.gg/corvus-labs).

<Callout type="warn" title="Pre-execution data">
  A transaction on this stream hasn't executed yet. Confirm it by signature through Solana RPC before you treat it as done.
</Callout>

## Next

* [API reference](/omen/api)
* [Limits & operations](/omen/limits)
* [Migrate from aRPC](/omen/migrate)
