@thesight/sdk 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,14 +1,199 @@
1
- import { Connection, type ConnectionConfig, type Transaction, type VersionedTransaction, type SendOptions, type Commitment } from '@solana/web3.js';
2
- import { type Tracer } from '@opentelemetry/api';
3
- import type { AnchorIdl, DecodedError, CpiTree } from '@thesight/core';
4
- export interface SightConfig {
5
- /** OTel tracer. Get via trace.getTracer('your-service') */
1
+ import { TransactionSignature, Connection, Finality, ConnectionConfig, Commitment, SendOptions } from '@solana/web3.js';
2
+ import { Tracer } from '@opentelemetry/api';
3
+ import { IdlResolver, AnchorIdl } from '@thesight/core';
4
+ export { AnchorIdl, CpiTree, CuAttribution, DecodedError, FlamegraphItem, IdlResolver } from '@thesight/core';
5
+ import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
6
+ import { SpanExporter, ReadableSpan } from '@opentelemetry/sdk-trace-base';
7
+ import { ExportResult } from '@opentelemetry/core';
8
+
9
+ interface InitSightConfig {
10
+ /** Project API key (`sk_live_...`) from the Sight dashboard. */
11
+ apiKey: string;
12
+ /**
13
+ * Human-readable service name that shows up on every span. Pick something
14
+ * that identifies this process — `'swap-bot'`, `'market-maker'`,
15
+ * `'trade-settler'`, etc.
16
+ */
17
+ serviceName: string;
18
+ /** Optional version string for the service. Useful for correlating spans with a deploy. */
19
+ serviceVersion?: string;
20
+ /**
21
+ * Full ingest URL. Defaults to the hosted Sight ingest. Override for
22
+ * local development (e.g. `http://localhost:3001/ingest`) or self-hosted
23
+ * deployments.
24
+ */
25
+ ingestUrl?: string;
26
+ /** BatchSpanProcessor flush interval, in ms. Defaults to 5s. */
27
+ batchDelayMs?: number;
28
+ /** Max spans per HTTP POST. Clamped to 100 by the exporter. */
29
+ maxBatchSize?: number;
30
+ /** Inject a fetch implementation for tests. Defaults to global fetch. */
31
+ fetchImpl?: typeof fetch;
32
+ }
33
+ interface SightTracerHandle {
34
+ provider: NodeTracerProvider;
35
+ /** Flush any pending spans and release the batch processor. */
36
+ shutdown: () => Promise<void>;
37
+ }
38
+ /**
39
+ * Initialize Sight tracing. Call this **once** near the top of your
40
+ * process entry point — typically in the same file that boots your
41
+ * HTTP server or worker.
42
+ *
43
+ * import { initSight, InstrumentedConnection } from '@thesight/sdk';
44
+ *
45
+ * initSight({
46
+ * apiKey: process.env.SIGHT_API_KEY!,
47
+ * serviceName: 'swap-bot',
48
+ * ingestUrl: process.env.SIGHT_INGEST_URL, // optional, defaults to prod
49
+ * });
50
+ *
51
+ * const connection = new InstrumentedConnection(process.env.RPC_URL!);
52
+ * const { signature } = await connection.sendAndConfirmInstrumented(tx);
53
+ *
54
+ * Registers a NodeTracerProvider as the global OTel tracer, so any call to
55
+ * `trace.getTracer(...)` (including the ones inside `InstrumentedConnection`)
56
+ * routes spans through the Sight exporter. Context propagation uses the
57
+ * Node async hooks manager so spans nest correctly across await boundaries.
58
+ *
59
+ * Returns a handle with a `shutdown()` method. Call it at graceful shutdown
60
+ * time so pending spans are flushed before the process exits:
61
+ *
62
+ * const sight = initSight({ ... });
63
+ * process.on('SIGTERM', async () => {
64
+ * await sight.shutdown();
65
+ * process.exit(0);
66
+ * });
67
+ */
68
+ declare function initSight(config: InitSightConfig): SightTracerHandle;
69
+
70
+ interface SightExporterConfig {
71
+ /** Project API key (`sk_live_...`). Sent as Bearer auth on every POST. */
72
+ apiKey: string;
73
+ /**
74
+ * Full ingest URL including the path (e.g. `https://ingest.thesight.dev/ingest`
75
+ * or `http://localhost:3001/ingest` for local dev).
76
+ */
77
+ ingestUrl: string;
78
+ /** Inject a fake fetch in tests. Defaults to `globalThis.fetch`. */
79
+ fetchImpl?: typeof fetch;
80
+ /** Max spans per POST. Ingest enforces an upper bound of 100. */
81
+ maxBatchSize?: number;
82
+ }
83
+ /**
84
+ * An OTel `SpanExporter` that translates OTel spans to Sight's custom
85
+ * ingest payload shape and POSTs them to `/ingest`.
86
+ *
87
+ * Each span becomes one object in the `spans` array. Solana-specific
88
+ * attributes flow through as-is (the set that `InstrumentedConnection`
89
+ * already populates — `solana.tx.signature`, `solana.tx.cu_used`,
90
+ * `solana.tx.program`, etc). The exporter intentionally does not attempt
91
+ * to translate span events or links — the ingest schema doesn't have
92
+ * slots for those, and we prefer dropping silently over guessing.
93
+ *
94
+ * The BatchSpanProcessor upstream handles retries, timeouts, and batching;
95
+ * this exporter stays a thin wire-format translator.
96
+ */
97
+ declare class SightSpanExporter implements SpanExporter {
98
+ private readonly apiKey;
99
+ private readonly ingestUrl;
100
+ private readonly fetchImpl;
101
+ private readonly maxBatchSize;
102
+ private shuttingDown;
103
+ constructor(config: SightExporterConfig);
104
+ export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): Promise<void>;
105
+ shutdown(): Promise<void>;
106
+ forceFlush(): Promise<void>;
107
+ private sendChunk;
108
+ private convertSpan;
109
+ }
110
+
111
+ interface TrackTransactionOptions {
112
+ /** The signature returned from a prior `sendRawTransaction` / `sendTransaction` call. */
113
+ signature: TransactionSignature;
114
+ /**
115
+ * Any `@solana/web3.js` Connection — plain or instrumented. Used to fetch
116
+ * the on-chain transaction via `getTransaction` for enrichment. Does
117
+ * **not** need to be an `InstrumentedConnection`; this helper intentionally
118
+ * never touches the transaction-send path.
119
+ */
120
+ connection: Connection;
121
+ /**
122
+ * Service name used for the span. Falls back to the service name
123
+ * configured by `initSight`. Useful when you want a different service
124
+ * name for a specific subsystem's spans.
125
+ */
126
+ serviceName?: string;
127
+ /** OTel tracer override. Defaults to `trace.getTracer('@thesight/sdk')`. */
128
+ tracer?: Tracer;
129
+ /** Optional IDL resolver for program/error decoding. A fresh one is built if omitted. */
130
+ idlResolver?: IdlResolver;
131
+ /**
132
+ * Pre-registered IDLs to hand to a freshly-built resolver. Ignored when
133
+ * `idlResolver` is provided.
134
+ */
135
+ idls?: Record<string, AnchorIdl>;
136
+ /** Finality commitment used for the enrichment fetch. Default 'confirmed'. */
137
+ commitment?: Finality;
138
+ /** Max wall-time before the span is ended with status=timeout. Default 30000ms. */
139
+ timeoutMs?: number;
140
+ /** Base poll interval for retrying getTransaction. Default 500ms. */
141
+ pollIntervalMs?: number;
142
+ }
143
+ /**
144
+ * **Non-wrapping observation helper.** Given a transaction signature that
145
+ * was already sent through any `Connection`, fetch the on-chain record,
146
+ * parse the logs, and emit a single OpenTelemetry span describing the
147
+ * transaction.
148
+ *
149
+ * Unlike `InstrumentedConnection`, this helper **never touches the send
150
+ * path** — it only observes after the fact via `getTransaction(signature)`.
151
+ * Use this when:
152
+ *
153
+ * - You want observability for wallet-adapter flows where the send path
154
+ * goes through the wallet and you can't easily override the Connection
155
+ * - You're security-conscious and don't want any SDK code on the critical
156
+ * transaction path
157
+ * - You want to instrument a handful of high-value transactions rather
158
+ * than every call a Connection makes
159
+ *
160
+ * Usage:
161
+ *
162
+ * import { trackSolanaTransaction } from '@thesight/sdk';
163
+ * import { Connection } from '@solana/web3.js';
164
+ *
165
+ * const connection = new Connection(rpcUrl);
166
+ * const signature = await wallet.sendTransaction(tx, connection);
167
+ *
168
+ * // Fire-and-forget. Span flushes on its own.
169
+ * void trackSolanaTransaction({
170
+ * signature,
171
+ * connection,
172
+ * serviceName: 'checkout',
173
+ * idls: { [programId]: idl },
174
+ * });
175
+ *
176
+ * Returns a `Promise<void>` — typically not awaited, but callers who want
177
+ * to wait for the span to export (e.g. short-lived scripts) can await it.
178
+ */
179
+ declare function trackSolanaTransaction(opts: TrackTransactionOptions): Promise<void>;
180
+
181
+ interface SightConfig {
182
+ /** OTel tracer. Defaults to `trace.getTracer('@thesight/sdk')`. */
6
183
  tracer?: Tracer;
7
184
  /** Override RPC endpoint for IDL fetching (defaults to same as connection) */
8
185
  idlRpcEndpoint?: string;
9
- /** Commitment to use when fetching confirmed tx details */
186
+ /**
187
+ * Commitment used when fetching confirmed tx details for enrichment.
188
+ * Defaults to 'confirmed'.
189
+ */
10
190
  commitment?: Commitment;
11
- /** Skip IDL resolution (faster, no program names or error decoding) */
191
+ /**
192
+ * Skip IDL resolution entirely. Spans will still emit with signature and
193
+ * timing attributes, but program names, instruction names, CPI trees, and
194
+ * decoded errors will all be omitted. Useful when you want minimal
195
+ * overhead and don't care about the richer observability.
196
+ */
12
197
  skipIdlResolution?: boolean;
13
198
  /**
14
199
  * Pre-register IDLs at construction time. Keys are program IDs, values are
@@ -19,18 +204,35 @@ export interface SightConfig {
19
204
  /**
20
205
  * Opt into reading Anchor IDL accounts from the on-chain PDA as a fallback
21
206
  * when a program is not explicitly registered. Defaults to **false** —
22
- * Sight's model is that IDLs are explicitly provided by the application
23
- * (via this option or `registerIdl`), not silently guessed from chain.
207
+ * Sight's model is that IDLs are explicitly provided by the application,
208
+ * not silently guessed from chain.
24
209
  */
25
210
  allowOnChainIdlFetch?: boolean;
211
+ /**
212
+ * Max wall-time the background enrichment task will wait for a
213
+ * transaction to show up in `getTransaction`. After this expires the
214
+ * span is ended with `solana.tx.status = 'timeout'`. Default 30000 (30s).
215
+ */
216
+ enrichmentTimeoutMs?: number;
217
+ /**
218
+ * How often the enrichment task polls `getTransaction`. Each retry backs
219
+ * off by 1.5x up to a cap. Default 500ms base.
220
+ */
221
+ enrichmentPollIntervalMs?: number;
222
+ /**
223
+ * Disable automatic span creation in the overridden `sendRawTransaction`.
224
+ * When true, InstrumentedConnection behaves like a plain Connection. You
225
+ * probably don't want this — it's here as an escape hatch for tests and
226
+ * rare cases where you need the class hierarchy but not the tracing.
227
+ */
228
+ disableAutoSpan?: boolean;
26
229
  }
27
- export interface SightSpanAttributes {
230
+ interface SightSpanAttributes {
28
231
  'solana.tx.signature': string;
29
- 'solana.tx.status': 'confirmed' | 'failed' | 'timeout';
232
+ 'solana.tx.status': 'submitted' | 'confirmed' | 'failed' | 'timeout';
30
233
  'solana.tx.slot'?: number;
31
234
  'solana.tx.fee_lamports'?: number;
32
235
  'solana.tx.submit_ms': number;
33
- 'solana.tx.confirmation_ms'?: number;
34
236
  'solana.tx.enrichment_ms'?: number;
35
237
  'solana.tx.cu_used'?: number;
36
238
  'solana.tx.cu_budget'?: number;
@@ -43,19 +245,43 @@ export interface SightSpanAttributes {
43
245
  'solana.tx.error_msg'?: string;
44
246
  }
45
247
  /**
46
- * Drop-in replacement for @solana/web3.js Connection that instruments
47
- * every transaction with OpenTelemetry spans.
248
+ * Drop-in replacement for `@solana/web3.js`'s `Connection` that emits an
249
+ * OpenTelemetry span for **every** call to `sendRawTransaction`
250
+ * regardless of whether the caller is your own code, an Anchor provider's
251
+ * `sendAndConfirm`, `@solana/web3.js`'s top-level `sendAndConfirmTransaction`,
252
+ * a wallet adapter, or anything else.
253
+ *
254
+ * Internally it overrides the parent class's `sendRawTransaction`, so the
255
+ * span covers the same surface web3.js already mediates. No mutation of
256
+ * the transaction bytes — we call `super.sendRawTransaction(rawTx, opts)`
257
+ * verbatim and observe the signature it returns.
258
+ *
259
+ * After the signature is returned (synchronously from the caller's point
260
+ * of view), a background task polls `getTransaction` until the on-chain
261
+ * record is available, parses the program logs via `@thesight/core`, and
262
+ * enriches the span with CU attribution, per-CPI events, program + instruction
263
+ * names, and decoded error details. The background task never blocks the
264
+ * caller — if it fails or times out, the span ends with status=timeout and
265
+ * whatever partial data was collected.
48
266
  *
49
267
  * Usage:
50
- * const connection = new InstrumentedConnection(rpcUrl, {
51
- * tracer: trace.getTracer('my-service'),
52
- * });
53
268
  *
54
- * The Solana transaction becomes a child span of whatever OTel context
55
- * is active when sendAndConfirmTransaction is called — so it automatically
56
- * nests inside your HTTP handler or background job span.
269
+ * import { initSight, InstrumentedConnection } from '@thesight/sdk';
270
+ *
271
+ * initSight({ apiKey, serviceName: 'swap-bot' });
272
+ *
273
+ * // Anywhere you currently construct a Connection, construct this instead:
274
+ * const connection = new InstrumentedConnection(rpcUrl, {
275
+ * commitment: 'confirmed',
276
+ * });
277
+ *
278
+ * // All of the following now emit spans automatically:
279
+ * await connection.sendRawTransaction(tx.serialize());
280
+ * await sendAndConfirmTransaction(connection, tx, signers); // web3.js
281
+ * await program.methods.foo().rpc(); // Anchor
282
+ * await wallet.sendTransaction(tx, connection); // wallet adapter
57
283
  */
58
- export declare class InstrumentedConnection extends Connection {
284
+ declare class InstrumentedConnection extends Connection {
59
285
  private sightConfig;
60
286
  private idlResolver;
61
287
  private tracer;
@@ -72,21 +298,41 @@ export declare class InstrumentedConnection extends Connection {
72
298
  /** Bulk-register multiple IDLs. */
73
299
  registerIdls(idls: Record<string, AnchorIdl>): void;
74
300
  /**
75
- * Sends and confirms a transaction, wrapped in an OTel span.
76
- * The span is a child of the current active context.
301
+ * Overrides the parent `Connection.sendRawTransaction` so every submit
302
+ * including those made by Anchor's `provider.sendAndConfirm`, web3.js's
303
+ * top-level `sendAndConfirmTransaction`, and wallet adapter flows — is
304
+ * observed by an OTel span automatically.
305
+ *
306
+ * The span is a child of whatever OTel context is active when the call
307
+ * fires, so app-level parent spans (HTTP handlers, job runs, wallet flow
308
+ * spans from another SDK) nest the Sight span correctly.
309
+ */
310
+ sendRawTransaction(rawTransaction: Buffer | Uint8Array | Array<number>, options?: SendOptions): Promise<TransactionSignature>;
311
+ /**
312
+ * Poll `getTransaction` until the on-chain record is available, then
313
+ * enrich the span with CU attribution, program names, decoded errors,
314
+ * and per-CPI events.
315
+ *
316
+ * This runs async and is never awaited by callers of `sendRawTransaction`.
317
+ * Failures inside this method attach to the span via recordException
318
+ * rather than throwing.
319
+ */
320
+ private enrichSpanInBackground;
321
+ /**
322
+ * Poll `getTransaction(signature)` until either the on-chain record is
323
+ * returned or the deadline passes. Exponential backoff (1.5x) capped at
324
+ * 2 seconds to balance responsiveness against RPC load.
325
+ */
326
+ private pollForTransaction;
327
+ /** Attach the flat fields (slot, fee, CU, status) from a tx response to a span. */
328
+ private attachTxDetailsToSpan;
329
+ /**
330
+ * Parse program logs into a CPI tree, enrich with registered IDLs, and
331
+ * emit one `cpi.invoke` event per invocation onto the span. Root
332
+ * program/instruction names are copied onto span attributes so dashboards
333
+ * can filter by them without walking events.
77
334
  */
78
- sendAndConfirmInstrumented(transaction: Transaction | VersionedTransaction, options?: SendOptions & {
79
- commitment?: Commitment;
80
- }): Promise<{
81
- signature: string;
82
- cpiTree?: CpiTree;
83
- error?: DecodedError;
84
- }>;
335
+ private attachParsedLogsToSpan;
85
336
  }
86
- export { IdlResolver } from '@thesight/core';
87
- export type { CpiTree, CuAttribution, FlamegraphItem, DecodedError, AnchorIdl } from '@thesight/core';
88
- export { initSight } from './init.js';
89
- export type { InitSightConfig, SightTracerHandle } from './init.js';
90
- export { SightSpanExporter } from './exporter.js';
91
- export type { SightExporterConfig } from './exporter.js';
92
- //# sourceMappingURL=index.d.ts.map
337
+
338
+ export { type InitSightConfig, InstrumentedConnection, type SightConfig, type SightExporterConfig, type SightSpanAttributes, SightSpanExporter, type SightTracerHandle, type TrackTransactionOptions, initSight, trackSolanaTransaction };