@thesight/sdk 0.1.1 → 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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/init.ts","../src/exporter.ts"],"sourcesContent":["import {\n Connection,\n type ConnectionConfig,\n type Transaction,\n type VersionedTransaction,\n type SendOptions,\n type Commitment,\n type Finality,\n type RpcResponseAndContext,\n type SignatureResult,\n} from '@solana/web3.js';\nimport { trace, context, SpanStatusCode, type Tracer } from '@opentelemetry/api';\nimport { parseLogs, IdlResolver, enrichTree, flatAttributions } from '@thesight/core';\nimport type { AnchorIdl, DecodedError, CpiTree } from '@thesight/core';\n\nexport interface SightConfig {\n /** OTel tracer. Get via trace.getTracer('your-service') */\n tracer?: Tracer;\n /** Override RPC endpoint for IDL fetching (defaults to same as connection) */\n idlRpcEndpoint?: string;\n /** Commitment to use when fetching confirmed tx details */\n commitment?: Commitment;\n /** Skip IDL resolution (faster, no program names or error decoding) */\n skipIdlResolution?: boolean;\n /**\n * Pre-register IDLs at construction time. Keys are program IDs, values are\n * full Anchor IDL objects. Anchor users can pass `program.idl` directly off\n * their `Program` instance — zero setup friction.\n */\n idls?: Record<string, AnchorIdl>;\n /**\n * Opt into reading Anchor IDL accounts from the on-chain PDA as a fallback\n * when a program is not explicitly registered. Defaults to **false** —\n * Sight's model is that IDLs are explicitly provided by the application\n * (via this option or `registerIdl`), not silently guessed from chain.\n */\n allowOnChainIdlFetch?: boolean;\n}\n\nexport interface SightSpanAttributes {\n 'solana.tx.signature': string;\n 'solana.tx.status': 'confirmed' | 'failed' | 'timeout';\n 'solana.tx.slot'?: number;\n 'solana.tx.fee_lamports'?: number;\n 'solana.tx.submit_ms': number;\n 'solana.tx.confirmation_ms'?: number;\n 'solana.tx.enrichment_ms'?: number;\n 'solana.tx.cu_used'?: number;\n 'solana.tx.cu_budget'?: number;\n 'solana.tx.cu_utilization'?: number;\n 'solana.tx.program'?: string;\n 'solana.tx.instruction'?: string;\n 'solana.tx.error'?: string;\n 'solana.tx.error_code'?: number;\n 'solana.tx.error_program'?: string;\n 'solana.tx.error_msg'?: string;\n}\n\n/**\n * Drop-in replacement for @solana/web3.js Connection that instruments\n * every transaction with OpenTelemetry spans.\n *\n * Usage:\n * const connection = new InstrumentedConnection(rpcUrl, {\n * tracer: trace.getTracer('my-service'),\n * });\n *\n * The Solana transaction becomes a child span of whatever OTel context\n * is active when sendAndConfirmTransaction is called — so it automatically\n * nests inside your HTTP handler or background job span.\n */\nexport class InstrumentedConnection extends Connection {\n private sightConfig: SightConfig;\n private idlResolver: IdlResolver;\n private tracer: Tracer;\n\n constructor(endpoint: string, config?: ConnectionConfig & SightConfig) {\n const {\n tracer,\n idlRpcEndpoint,\n skipIdlResolution,\n idls,\n allowOnChainIdlFetch,\n ...connectionConfig\n } = config ?? {};\n super(endpoint, connectionConfig);\n this.sightConfig = { tracer, idlRpcEndpoint, skipIdlResolution, allowOnChainIdlFetch };\n this.idlResolver = new IdlResolver({\n rpcEndpoint: idlRpcEndpoint ?? endpoint,\n allowOnChainFetch: allowOnChainIdlFetch ?? false,\n });\n if (idls) this.idlResolver.registerMany(idls);\n this.tracer = tracer ?? trace.getTracer('@thesight/sdk');\n }\n\n /**\n * Register an IDL for a single program. Convenience forwarder for the\n * underlying resolver. Anchor users typically call this right after\n * constructing a `Program`:\n *\n * const program = new Program(idl, programId, provider);\n * connection.registerIdl(program.programId.toBase58(), program.idl);\n */\n registerIdl(programId: string, idl: AnchorIdl): void {\n this.idlResolver.register(programId, idl);\n }\n\n /** Bulk-register multiple IDLs. */\n registerIdls(idls: Record<string, AnchorIdl>): void {\n this.idlResolver.registerMany(idls);\n }\n\n /**\n * Sends and confirms a transaction, wrapped in an OTel span.\n * The span is a child of the current active context.\n */\n async sendAndConfirmInstrumented(\n transaction: Transaction | VersionedTransaction,\n options?: SendOptions & { commitment?: Commitment },\n ): Promise<{ signature: string; cpiTree?: CpiTree; error?: DecodedError }> {\n const commitment = options?.commitment ?? this.sightConfig.commitment ?? 'confirmed';\n const finality: Finality = commitment === 'processed' ? 'confirmed' : commitment as Finality;\n const span = this.tracer.startSpan('solana.sendAndConfirmTransaction', {}, context.active());\n\n const submitStart = Date.now();\n\n try {\n // Submit the transaction\n const signature = await this.sendRawTransaction(\n 'serialize' in transaction\n ? transaction.serialize()\n : (transaction as VersionedTransaction).serialize(),\n { skipPreflight: false, ...options },\n );\n\n span.setAttribute('solana.tx.signature', signature);\n const submitMs = Date.now() - submitStart;\n span.setAttribute('solana.tx.submit_ms', submitMs);\n\n // Await confirmation\n const confirmStart = Date.now();\n const { value: result } = await this.confirmTransaction(\n { signature, ...(await this.getLatestBlockhash(commitment)) },\n commitment,\n ) as RpcResponseAndContext<SignatureResult>;\n\n const confirmMs = Date.now() - confirmStart;\n span.setAttribute('solana.tx.confirmation_ms', confirmMs);\n\n if (result.err) {\n span.setAttribute('solana.tx.status', 'failed');\n span.setStatus({ code: SpanStatusCode.ERROR });\n\n if (!this.sightConfig.skipIdlResolution) {\n // Enrich error with IDL decoding\n const txDetails = await this.getParsedTransaction(signature, {\n commitment: finality,\n maxSupportedTransactionVersion: 0,\n });\n const accountKeys = txDetails?.transaction.message.accountKeys.map(\n (k: { pubkey?: { toBase58(): string }; toBase58?(): string }) =>\n k.pubkey ? k.pubkey.toBase58() : k.toBase58!()\n ) ?? [];\n const programIds = txDetails?.transaction.message.instructions.map(\n (ix: { programId?: { toBase58(): string }; programIdIndex?: number }) =>\n ix.programId ? ix.programId.toBase58() : accountKeys[ix.programIdIndex!] ?? ''\n ) ?? [];\n\n const decoded = await this.idlResolver.decodeError(\n result.err as never,\n accountKeys,\n programIds,\n );\n\n if (decoded.errorName) {\n span.setAttribute('solana.tx.error', decoded.errorName);\n }\n if (decoded.errorCode !== undefined) {\n span.setAttribute('solana.tx.error_code', decoded.errorCode);\n }\n if (decoded.programName) {\n span.setAttribute('solana.tx.error_program', decoded.programName);\n }\n if (decoded.errorMsg) {\n span.setAttribute('solana.tx.error_msg', decoded.errorMsg);\n }\n\n span.end();\n return { signature, error: decoded };\n }\n\n span.end();\n return { signature };\n }\n\n span.setAttribute('solana.tx.status', 'confirmed');\n\n // Enrich with on-chain details\n if (!this.sightConfig.skipIdlResolution) {\n const enrichStart = Date.now();\n const txDetails = await this.getTransaction(signature, {\n commitment: finality,\n maxSupportedTransactionVersion: 0,\n });\n\n if (txDetails) {\n const slot = txDetails.slot;\n const fee = txDetails.meta?.fee;\n const logs = txDetails.meta?.logMessages ?? [];\n const cuUsed = txDetails.meta?.computeUnitsConsumed;\n\n span.setAttribute('solana.tx.slot', slot);\n if (fee !== undefined) span.setAttribute('solana.tx.fee_lamports', fee);\n if (cuUsed !== undefined) {\n span.setAttribute('solana.tx.cu_used', cuUsed);\n span.setAttribute('solana.tx.cu_budget', 200_000);\n span.setAttribute('solana.tx.cu_utilization', parseFloat((cuUsed / 200_000 * 100).toFixed(1)));\n }\n\n // Parse logs into CPI tree\n const { cpiTree } = parseLogs({ logs });\n\n if (!this.sightConfig.skipIdlResolution) {\n await enrichTree(cpiTree, this.idlResolver);\n }\n\n // Emit one span event per CPI invocation\n const attributions = flatAttributions(cpiTree);\n for (const attr of attributions) {\n span.addEvent('cpi.invoke', {\n 'cpi.program': attr.programName ?? attr.programId,\n 'cpi.instruction': attr.instructionName ?? 'unknown',\n 'cpi.depth': attr.depth,\n 'cpi.cu_consumed': attr.cuConsumed,\n 'cpi.cu_self': attr.cuSelf,\n 'cpi.percentage': parseFloat(attr.percentage.toFixed(2)),\n });\n }\n\n // Top-level instruction info\n const root = cpiTree.roots[0];\n if (root) {\n if (root.programName) span.setAttribute('solana.tx.program', root.programName);\n if (root.instructionName) span.setAttribute('solana.tx.instruction', root.instructionName);\n }\n\n span.setAttribute('solana.tx.enrichment_ms', Date.now() - enrichStart);\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n\n return { signature, cpiTree };\n }\n }\n\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n return { signature };\n\n } catch (err) {\n span.setAttribute('solana.tx.status', 'failed');\n span.setAttribute('solana.tx.submit_ms', Date.now() - submitStart);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err instanceof Error ? err.message : String(err),\n });\n span.end();\n throw err;\n }\n }\n}\n\nexport { IdlResolver } from '@thesight/core';\nexport type { CpiTree, CuAttribution, FlamegraphItem, DecodedError, AnchorIdl } from '@thesight/core';\n\n// ─── Tracing initialization ──────────────────────────────────────────────────\n// One-call setup that wires a NodeTracerProvider + SightSpanExporter as the\n// global OTel tracer. After calling initSight, every InstrumentedConnection\n// span routes to Sight ingest automatically — no separate OTel setup needed.\n\nexport { initSight } from './init.js';\nexport type { InitSightConfig, SightTracerHandle } from './init.js';\nexport { SightSpanExporter } from './exporter.js';\nexport type { SightExporterConfig } from './exporter.js';\n","import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';\nimport { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';\nimport { Resource } from '@opentelemetry/resources';\nimport { SEMRESATTRS_SERVICE_NAME, SEMRESATTRS_SERVICE_VERSION } from '@opentelemetry/semantic-conventions';\nimport { SightSpanExporter } from './exporter.js';\n\n// ─── Config ──────────────────────────────────────────────────────────────────\n\nexport interface InitSightConfig {\n /** Project API key (`sk_live_...`) from the Sight dashboard. */\n apiKey: string;\n\n /**\n * Human-readable service name that shows up on every span. Pick something\n * that identifies this process — `'swap-bot'`, `'market-maker'`,\n * `'trade-settler'`, etc.\n */\n serviceName: string;\n\n /** Optional version string for the service. Useful for correlating spans with a deploy. */\n serviceVersion?: string;\n\n /**\n * Full ingest URL. Defaults to the hosted Sight ingest. Override for\n * local development (e.g. `http://localhost:3001/ingest`) or self-hosted\n * deployments.\n */\n ingestUrl?: string;\n\n /** BatchSpanProcessor flush interval, in ms. Defaults to 5s. */\n batchDelayMs?: number;\n\n /** Max spans per HTTP POST. Clamped to 100 by the exporter. */\n maxBatchSize?: number;\n\n /** Inject a fetch implementation for tests. Defaults to global fetch. */\n fetchImpl?: typeof fetch;\n}\n\nexport interface SightTracerHandle {\n provider: NodeTracerProvider;\n /** Flush any pending spans and release the batch processor. */\n shutdown: () => Promise<void>;\n}\n\n// ─── Entry point ────────────────────────────────────────────────────────────\n\nconst DEFAULT_INGEST_URL = 'https://ingest.thesight.dev/ingest';\n\n/**\n * Initialize Sight tracing. Call this **once** near the top of your\n * process entry point — typically in the same file that boots your\n * HTTP server or worker.\n *\n * import { initSight, InstrumentedConnection } from '@thesight/sdk';\n *\n * initSight({\n * apiKey: process.env.SIGHT_API_KEY!,\n * serviceName: 'swap-bot',\n * ingestUrl: process.env.SIGHT_INGEST_URL, // optional, defaults to prod\n * });\n *\n * const connection = new InstrumentedConnection(process.env.RPC_URL!);\n * const { signature } = await connection.sendAndConfirmInstrumented(tx);\n *\n * Registers a NodeTracerProvider as the global OTel tracer, so any call to\n * `trace.getTracer(...)` (including the ones inside `InstrumentedConnection`)\n * routes spans through the Sight exporter. Context propagation uses the\n * Node async hooks manager so spans nest correctly across await boundaries.\n *\n * Returns a handle with a `shutdown()` method. Call it at graceful shutdown\n * time so pending spans are flushed before the process exits:\n *\n * const sight = initSight({ ... });\n * process.on('SIGTERM', async () => {\n * await sight.shutdown();\n * process.exit(0);\n * });\n */\nexport function initSight(config: InitSightConfig): SightTracerHandle {\n if (!config.apiKey) {\n throw new Error('initSight: `apiKey` is required');\n }\n if (!config.serviceName) {\n throw new Error('initSight: `serviceName` is required');\n }\n\n const resource = new Resource({\n [SEMRESATTRS_SERVICE_NAME]: config.serviceName,\n ...(config.serviceVersion\n ? { [SEMRESATTRS_SERVICE_VERSION]: config.serviceVersion }\n : {}),\n });\n\n const provider = new NodeTracerProvider({ resource });\n\n const exporter = new SightSpanExporter({\n apiKey: config.apiKey,\n ingestUrl: config.ingestUrl ?? DEFAULT_INGEST_URL,\n fetchImpl: config.fetchImpl,\n maxBatchSize: config.maxBatchSize,\n });\n\n // BatchSpanProcessor buffers spans and flushes on an interval. This is the\n // right default for production — simple span processor is one HTTP round\n // trip per span, which is fine for tests and dev but nasty at scale.\n const processor = new BatchSpanProcessor(exporter, {\n scheduledDelayMillis: config.batchDelayMs ?? 5_000,\n maxExportBatchSize: config.maxBatchSize ?? 100,\n maxQueueSize: 2048,\n });\n\n provider.addSpanProcessor(processor);\n\n // Register as the global OTel tracer provider. After this call,\n // `trace.getTracer('anything')` returns a tracer from our provider,\n // which routes spans to SightSpanExporter.\n provider.register();\n\n return {\n provider,\n shutdown: async () => {\n await provider.shutdown();\n },\n };\n}\n","import type { SpanAttributes } from '@opentelemetry/api';\nimport type { SpanExporter, ReadableSpan } from '@opentelemetry/sdk-trace-base';\nimport {\n hrTimeToMilliseconds,\n ExportResultCode,\n type ExportResult,\n} from '@opentelemetry/core';\n\n// ─── Config ──────────────────────────────────────────────────────────────────\n\nexport interface SightExporterConfig {\n /** Project API key (`sk_live_...`). Sent as Bearer auth on every POST. */\n apiKey: string;\n /**\n * Full ingest URL including the path (e.g. `https://ingest.thesight.dev/ingest`\n * or `http://localhost:3001/ingest` for local dev).\n */\n ingestUrl: string;\n /** Inject a fake fetch in tests. Defaults to `globalThis.fetch`. */\n fetchImpl?: typeof fetch;\n /** Max spans per POST. Ingest enforces an upper bound of 100. */\n maxBatchSize?: number;\n}\n\n// ─── Exporter ────────────────────────────────────────────────────────────────\n\n/**\n * An OTel `SpanExporter` that translates OTel spans to Sight's custom\n * ingest payload shape and POSTs them to `/ingest`.\n *\n * Each span becomes one object in the `spans` array. Solana-specific\n * attributes flow through as-is (the set that `InstrumentedConnection`\n * already populates — `solana.tx.signature`, `solana.tx.cu_used`,\n * `solana.tx.program`, etc). The exporter intentionally does not attempt\n * to translate span events or links — the ingest schema doesn't have\n * slots for those, and we prefer dropping silently over guessing.\n *\n * The BatchSpanProcessor upstream handles retries, timeouts, and batching;\n * this exporter stays a thin wire-format translator.\n */\nexport class SightSpanExporter implements SpanExporter {\n private readonly apiKey: string;\n private readonly ingestUrl: string;\n private readonly fetchImpl: typeof fetch;\n private readonly maxBatchSize: number;\n private shuttingDown = false;\n\n constructor(config: SightExporterConfig) {\n this.apiKey = config.apiKey;\n this.ingestUrl = config.ingestUrl;\n this.fetchImpl = config.fetchImpl ?? (globalThis.fetch as typeof fetch);\n // Ingest's IngestPayload schema caps at 100 spans per POST. Allow\n // operators to lower the batch size for tighter latency, but never\n // raise it above the server's limit.\n this.maxBatchSize = Math.min(100, config.maxBatchSize ?? 100);\n\n if (!this.fetchImpl) {\n throw new Error(\n 'SightSpanExporter: globalThis.fetch is not available. Node >= 18 ships ' +\n 'with fetch built in, or pass `fetchImpl` explicitly.',\n );\n }\n }\n\n async export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void,\n ): Promise<void> {\n if (this.shuttingDown) {\n resultCallback({ code: ExportResultCode.FAILED, error: new Error('Exporter is shut down') });\n return;\n }\n\n // Split into chunks if the upstream processor handed us a larger\n // batch than ingest will accept. Uncommon with a well-configured\n // BatchSpanProcessor but cheap to handle defensively.\n const chunks: ReadableSpan[][] = [];\n for (let i = 0; i < spans.length; i += this.maxBatchSize) {\n chunks.push(spans.slice(i, i + this.maxBatchSize));\n }\n\n try {\n for (const chunk of chunks) {\n await this.sendChunk(chunk);\n }\n resultCallback({ code: ExportResultCode.SUCCESS });\n } catch (err) {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: err instanceof Error ? err : new Error(String(err)),\n });\n }\n }\n\n async shutdown(): Promise<void> {\n this.shuttingDown = true;\n }\n\n async forceFlush(): Promise<void> {\n // The exporter is stateless — BatchSpanProcessor's own forceFlush\n // drains the queue before calling export(). Nothing to do here.\n }\n\n // ─── Internal ──────────────────────────────────────────────────────────────\n\n private async sendChunk(spans: ReadableSpan[]): Promise<void> {\n const payload = {\n spans: spans.map((span) => this.convertSpan(span)),\n };\n\n const response = await this.fetchImpl(this.ingestUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`,\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const body = await safeReadText(response);\n throw new Error(\n `Sight ingest returned ${response.status} ${response.statusText}: ${body}`,\n );\n }\n }\n\n private convertSpan(span: ReadableSpan): IngestSpan {\n const attr = span.attributes;\n const resource = span.resource.attributes;\n const serviceName = typeof resource['service.name'] === 'string'\n ? resource['service.name']\n : undefined;\n const startTimeMs = hrTimeToMilliseconds(span.startTime);\n const endTimeMs = hrTimeToMilliseconds(span.endTime);\n const durationMs = Math.max(0, endTimeMs - startTimeMs);\n\n const out: IngestSpan = {\n traceId: span.spanContext().traceId,\n spanId: span.spanContext().spanId,\n spanName: span.name,\n startTimeMs,\n durationMs,\n };\n\n const parentSpanId = (span as { parentSpanId?: string }).parentSpanId;\n if (parentSpanId) out.parentSpanId = parentSpanId;\n if (serviceName) out.serviceName = serviceName;\n\n copyIfString(attr, 'solana.tx.signature', out);\n copyIfEnum(attr, 'solana.tx.status', out, ['confirmed', 'failed', 'timeout']);\n copyIfNumber(attr, 'solana.tx.slot', out);\n copyIfNumber(attr, 'solana.tx.cu_used', out);\n copyIfNumber(attr, 'solana.tx.cu_budget', out);\n copyIfNumber(attr, 'solana.tx.cu_utilization', out);\n copyIfString(attr, 'solana.tx.program', out);\n copyIfString(attr, 'solana.tx.instruction', out);\n copyIfString(attr, 'solana.tx.error', out);\n copyIfNumber(attr, 'solana.tx.error_code', out);\n copyIfString(attr, 'solana.tx.error_program', out);\n copyIfNumber(attr, 'solana.tx.submit_ms', out);\n copyIfNumber(attr, 'solana.tx.confirmation_ms', out);\n copyIfNumber(attr, 'solana.tx.fee_lamports', out);\n\n return out;\n }\n}\n\n// ─── Wire format (narrow, matches ingest's zod schema) ──────────────────────\n\ninterface IngestSpan {\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n serviceName?: string;\n spanName: string;\n startTimeMs: number;\n durationMs: number;\n\n 'solana.tx.signature'?: string;\n 'solana.tx.status'?: 'confirmed' | 'failed' | 'timeout';\n 'solana.tx.slot'?: number;\n 'solana.tx.cu_used'?: number;\n 'solana.tx.cu_budget'?: number;\n 'solana.tx.cu_utilization'?: number;\n 'solana.tx.program'?: string;\n 'solana.tx.instruction'?: string;\n 'solana.tx.error'?: string;\n 'solana.tx.error_code'?: number;\n 'solana.tx.error_program'?: string;\n 'solana.tx.submit_ms'?: number;\n 'solana.tx.confirmation_ms'?: number;\n 'solana.tx.fee_lamports'?: number;\n}\n\n// ─── Helpers ────────────────────────────────────────────────────────────────\n\nfunction copyIfString(\n attr: SpanAttributes,\n key: keyof IngestSpan & string,\n out: IngestSpan,\n): void {\n const v = attr[key];\n if (typeof v === 'string') {\n (out as unknown as Record<string, unknown>)[key] = v;\n }\n}\n\nfunction copyIfNumber(\n attr: SpanAttributes,\n key: keyof IngestSpan & string,\n out: IngestSpan,\n): void {\n const v = attr[key];\n if (typeof v === 'number' && Number.isFinite(v)) {\n (out as unknown as Record<string, unknown>)[key] = v;\n }\n}\n\nfunction copyIfEnum<T extends string>(\n attr: SpanAttributes,\n key: keyof IngestSpan & string,\n out: IngestSpan,\n allowed: readonly T[],\n): void {\n const v = attr[key];\n if (typeof v === 'string' && (allowed as readonly string[]).includes(v)) {\n (out as unknown as Record<string, unknown>)[key] = v;\n }\n}\n\nasync function safeReadText(res: Response): Promise<string> {\n try {\n return (await res.text()).slice(0, 500);\n } catch {\n return '<no body>';\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAUO;AACP,iBAA4D;AAC5D,IAAAA,eAAqE;AAmQrE,IAAAA,eAA4B;;;AC/Q5B,4BAAmC;AACnC,4BAAmC;AACnC,uBAAyB;AACzB,kCAAsE;;;ACDtE,kBAIO;AAkCA,IAAM,oBAAN,MAAgD;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACT,eAAe;AAAA,EAEvB,YAAY,QAA6B;AACvC,SAAK,SAAY,OAAO;AACxB,SAA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AmB,KAAK,mBAAmB;AAAA,cAC3C,aAAa,KAAK;AAAA,cAClB,mBAAmB,KAAK;AAAA,cACxB,eAAe,KAAK;AAAA,cACpB,kBAAkB,WAAW,KAAK,WAAW,QAAQ,CAAC,CAAC;AAAA,YACzD,CAAC;AAAA,UACH;AAGA,gBAAM,OAAO,QAAQ,MAAM,CAAC;AAC5B,cAAI,MAAM;AACR,gBAAI,KAAK,YAAa,MAAK,aAAa,qBAAqB,KAAK,WAAW;AAC7E,gBAAI,KAAK,gBAAiB,MAAK,aAAa,yBAAyB,KAAK,eAAe;AAAA,UAC3F;AAEA,eAAK,aAAa,2BAA2B,KAAK,IAAI,IAAI,WAAW;AACrE,eAAK,UAAU,EAAE,MAAM,0BAAe,GAAG,CAAC;AAC1C,eAAK,IAAI;AAET,iBAAO,EAAE,WAAW,QAAQ;AAAA,QAC9B;AAAA,MACF;AAEA,WAAK,UAAU,EAAE,MAAM,0BAAe,GAAG,CAAC;AAC1C,WAAK,IAAI;AACT,aAAO,EAAE,UAAU;AAAA,IAErB,SAAS,KAAK;AACZ,WAAK,aAAa,oBAAoB,QAAQ;AAC9C,WAAK,aAAa,uBAAuB,KAAK,IAAI,IAAI,WAAW;AACjE,WAAK,UAAU;AAAA,QACb,MAAM,0BAAe;AAAA,QACrB,SAAS,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,MAC1D,CAAC;AACD,WAAK,IAAI;AACT,YAAM;AAAA,IACR;AAAA,EACF;AACF;","names":["import_core"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/init.ts","../src/exporter.ts","../src/track.ts"],"sourcesContent":["import {\n Connection,\n type ConnectionConfig,\n type SendOptions,\n type Commitment,\n type Finality,\n type TransactionSignature,\n type VersionedTransactionResponse,\n} from '@solana/web3.js';\nimport {\n trace,\n context,\n SpanStatusCode,\n type Span,\n type Tracer,\n} from '@opentelemetry/api';\nimport { parseLogs, IdlResolver, enrichTree, flatAttributions } from '@thesight/core';\nimport type { AnchorIdl, CpiTree } from '@thesight/core';\n\n// ─── Config ────────────────────────────────────────────────────────────────\n\nexport interface SightConfig {\n /** OTel tracer. Defaults to `trace.getTracer('@thesight/sdk')`. */\n tracer?: Tracer;\n\n /** Override RPC endpoint for IDL fetching (defaults to same as connection) */\n idlRpcEndpoint?: string;\n\n /**\n * Commitment used when fetching confirmed tx details for enrichment.\n * Defaults to 'confirmed'.\n */\n commitment?: Commitment;\n\n /**\n * Skip IDL resolution entirely. Spans will still emit with signature and\n * timing attributes, but program names, instruction names, CPI trees, and\n * decoded errors will all be omitted. Useful when you want minimal\n * overhead and don't care about the richer observability.\n */\n skipIdlResolution?: boolean;\n\n /**\n * Pre-register IDLs at construction time. Keys are program IDs, values are\n * full Anchor IDL objects. Anchor users can pass `program.idl` directly off\n * their `Program` instance — zero setup friction.\n */\n idls?: Record<string, AnchorIdl>;\n\n /**\n * Opt into reading Anchor IDL accounts from the on-chain PDA as a fallback\n * when a program is not explicitly registered. Defaults to **false** —\n * Sight's model is that IDLs are explicitly provided by the application,\n * not silently guessed from chain.\n */\n allowOnChainIdlFetch?: boolean;\n\n /**\n * Max wall-time the background enrichment task will wait for a\n * transaction to show up in `getTransaction`. After this expires the\n * span is ended with `solana.tx.status = 'timeout'`. Default 30000 (30s).\n */\n enrichmentTimeoutMs?: number;\n\n /**\n * How often the enrichment task polls `getTransaction`. Each retry backs\n * off by 1.5x up to a cap. Default 500ms base.\n */\n enrichmentPollIntervalMs?: number;\n\n /**\n * Disable automatic span creation in the overridden `sendRawTransaction`.\n * When true, InstrumentedConnection behaves like a plain Connection. You\n * probably don't want this — it's here as an escape hatch for tests and\n * rare cases where you need the class hierarchy but not the tracing.\n */\n disableAutoSpan?: boolean;\n}\n\n// ─── Span attribute shape (documented, for downstream consumers) ──────────\n\nexport interface SightSpanAttributes {\n 'solana.tx.signature': string;\n 'solana.tx.status': 'submitted' | 'confirmed' | 'failed' | 'timeout';\n 'solana.tx.slot'?: number;\n 'solana.tx.fee_lamports'?: number;\n 'solana.tx.submit_ms': number;\n 'solana.tx.enrichment_ms'?: number;\n 'solana.tx.cu_used'?: number;\n 'solana.tx.cu_budget'?: number;\n 'solana.tx.cu_utilization'?: number;\n 'solana.tx.program'?: string;\n 'solana.tx.instruction'?: string;\n 'solana.tx.error'?: string;\n 'solana.tx.error_code'?: number;\n 'solana.tx.error_program'?: string;\n 'solana.tx.error_msg'?: string;\n}\n\n// ─── InstrumentedConnection ────────────────────────────────────────────────\n\n/**\n * Drop-in replacement for `@solana/web3.js`'s `Connection` that emits an\n * OpenTelemetry span for **every** call to `sendRawTransaction` —\n * regardless of whether the caller is your own code, an Anchor provider's\n * `sendAndConfirm`, `@solana/web3.js`'s top-level `sendAndConfirmTransaction`,\n * a wallet adapter, or anything else.\n *\n * Internally it overrides the parent class's `sendRawTransaction`, so the\n * span covers the same surface web3.js already mediates. No mutation of\n * the transaction bytes — we call `super.sendRawTransaction(rawTx, opts)`\n * verbatim and observe the signature it returns.\n *\n * After the signature is returned (synchronously from the caller's point\n * of view), a background task polls `getTransaction` until the on-chain\n * record is available, parses the program logs via `@thesight/core`, and\n * enriches the span with CU attribution, per-CPI events, program + instruction\n * names, and decoded error details. The background task never blocks the\n * caller — if it fails or times out, the span ends with status=timeout and\n * whatever partial data was collected.\n *\n * Usage:\n *\n * import { initSight, InstrumentedConnection } from '@thesight/sdk';\n *\n * initSight({ apiKey, serviceName: 'swap-bot' });\n *\n * // Anywhere you currently construct a Connection, construct this instead:\n * const connection = new InstrumentedConnection(rpcUrl, {\n * commitment: 'confirmed',\n * });\n *\n * // All of the following now emit spans automatically:\n * await connection.sendRawTransaction(tx.serialize());\n * await sendAndConfirmTransaction(connection, tx, signers); // web3.js\n * await program.methods.foo().rpc(); // Anchor\n * await wallet.sendTransaction(tx, connection); // wallet adapter\n */\nexport class InstrumentedConnection extends Connection {\n private sightConfig: SightConfig;\n private idlResolver: IdlResolver;\n private tracer: Tracer;\n\n constructor(endpoint: string, config?: ConnectionConfig & SightConfig) {\n const {\n tracer,\n idlRpcEndpoint,\n skipIdlResolution,\n idls,\n allowOnChainIdlFetch,\n enrichmentTimeoutMs,\n enrichmentPollIntervalMs,\n disableAutoSpan,\n commitment,\n ...connectionConfig\n } = config ?? {};\n\n super(endpoint, connectionConfig);\n\n this.sightConfig = {\n tracer,\n idlRpcEndpoint,\n skipIdlResolution,\n allowOnChainIdlFetch,\n enrichmentTimeoutMs: enrichmentTimeoutMs ?? 30_000,\n enrichmentPollIntervalMs: enrichmentPollIntervalMs ?? 500,\n disableAutoSpan,\n commitment,\n };\n this.idlResolver = new IdlResolver({\n rpcEndpoint: idlRpcEndpoint ?? endpoint,\n allowOnChainFetch: allowOnChainIdlFetch ?? false,\n });\n if (idls) this.idlResolver.registerMany(idls);\n this.tracer = tracer ?? trace.getTracer('@thesight/sdk');\n }\n\n /**\n * Register an IDL for a single program. Convenience forwarder for the\n * underlying resolver. Anchor users typically call this right after\n * constructing a `Program`:\n *\n * const program = new Program(idl, programId, provider);\n * connection.registerIdl(program.programId.toBase58(), program.idl);\n */\n registerIdl(programId: string, idl: AnchorIdl): void {\n this.idlResolver.register(programId, idl);\n }\n\n /** Bulk-register multiple IDLs. */\n registerIdls(idls: Record<string, AnchorIdl>): void {\n this.idlResolver.registerMany(idls);\n }\n\n // ─── Overridden method ────────────────────────────────────────────────────\n\n /**\n * Overrides the parent `Connection.sendRawTransaction` so every submit —\n * including those made by Anchor's `provider.sendAndConfirm`, web3.js's\n * top-level `sendAndConfirmTransaction`, and wallet adapter flows — is\n * observed by an OTel span automatically.\n *\n * The span is a child of whatever OTel context is active when the call\n * fires, so app-level parent spans (HTTP handlers, job runs, wallet flow\n * spans from another SDK) nest the Sight span correctly.\n */\n override async sendRawTransaction(\n rawTransaction: Buffer | Uint8Array | Array<number>,\n options?: SendOptions,\n ): Promise<TransactionSignature> {\n if (this.sightConfig.disableAutoSpan) {\n return super.sendRawTransaction(rawTransaction, options);\n }\n\n const span = this.tracer.startSpan('solana.sendRawTransaction', {}, context.active());\n const submitStart = Date.now();\n\n let signature: TransactionSignature;\n try {\n signature = await super.sendRawTransaction(rawTransaction, options);\n } catch (err) {\n const submitMs = Date.now() - submitStart;\n span.setAttribute('solana.tx.submit_ms', submitMs);\n span.setAttribute('solana.tx.status', 'failed');\n span.recordException(err instanceof Error ? err : new Error(String(err)));\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err instanceof Error ? err.message : String(err),\n });\n span.end();\n throw err;\n }\n\n span.setAttribute('solana.tx.signature', signature);\n span.setAttribute('solana.tx.submit_ms', Date.now() - submitStart);\n span.setAttribute('solana.tx.status', 'submitted');\n\n // Fire-and-forget background enrichment. The returned Promise is\n // intentionally discarded — we don't want to couple the caller's\n // transaction-send latency to our observation machinery. Any enrichment\n // error is caught inside enrichSpanInBackground and attached to the\n // span, not bubbled up.\n void this.enrichSpanInBackground(span, signature, submitStart);\n\n return signature;\n }\n\n // ─── Background enrichment ───────────────────────────────────────────────\n\n /**\n * Poll `getTransaction` until the on-chain record is available, then\n * enrich the span with CU attribution, program names, decoded errors,\n * and per-CPI events.\n *\n * This runs async and is never awaited by callers of `sendRawTransaction`.\n * Failures inside this method attach to the span via recordException\n * rather than throwing.\n */\n private async enrichSpanInBackground(\n span: Span,\n signature: TransactionSignature,\n submitStart: number,\n ): Promise<void> {\n const enrichStart = Date.now();\n const deadline = enrichStart + (this.sightConfig.enrichmentTimeoutMs ?? 30_000);\n const commitment = (this.sightConfig.commitment ?? 'confirmed') as Finality;\n const basePollMs = this.sightConfig.enrichmentPollIntervalMs ?? 500;\n\n try {\n const txDetails = await this.pollForTransaction(signature, commitment, deadline, basePollMs);\n\n if (!txDetails) {\n span.setAttribute('solana.tx.status', 'timeout');\n span.setAttribute('solana.tx.enrichment_ms', Date.now() - submitStart);\n span.end();\n return;\n }\n\n this.attachTxDetailsToSpan(span, txDetails);\n\n if (!this.sightConfig.skipIdlResolution) {\n const logs = txDetails.meta?.logMessages ?? [];\n if (logs.length > 0) {\n await this.attachParsedLogsToSpan(span, logs);\n }\n }\n\n span.setAttribute('solana.tx.enrichment_ms', Date.now() - submitStart);\n\n if (txDetails.meta?.err) {\n span.setStatus({ code: SpanStatusCode.ERROR });\n } else {\n span.setStatus({ code: SpanStatusCode.OK });\n }\n } catch (err) {\n span.recordException(err instanceof Error ? err : new Error(String(err)));\n span.setAttribute(\n 'solana.tx.enrichment_error',\n err instanceof Error ? err.message : String(err),\n );\n } finally {\n span.end();\n }\n }\n\n /**\n * Poll `getTransaction(signature)` until either the on-chain record is\n * returned or the deadline passes. Exponential backoff (1.5x) capped at\n * 2 seconds to balance responsiveness against RPC load.\n */\n private async pollForTransaction(\n signature: TransactionSignature,\n commitment: Finality,\n deadline: number,\n basePollMs: number,\n ): Promise<VersionedTransactionResponse | null> {\n let attempt = 0;\n while (Date.now() < deadline) {\n try {\n const tx = await super.getTransaction(signature, {\n commitment,\n maxSupportedTransactionVersion: 0,\n });\n if (tx) return tx;\n } catch {\n // Ignore — retry with backoff. Transient RPC errors are common\n // during the seconds immediately after submission.\n }\n attempt++;\n const waitMs = Math.min(basePollMs * Math.pow(1.5, attempt - 1), 2_000);\n await sleep(waitMs);\n }\n return null;\n }\n\n /** Attach the flat fields (slot, fee, CU, status) from a tx response to a span. */\n private attachTxDetailsToSpan(span: Span, txDetails: VersionedTransactionResponse): void {\n span.setAttribute('solana.tx.status', txDetails.meta?.err ? 'failed' : 'confirmed');\n span.setAttribute('solana.tx.slot', txDetails.slot);\n\n const fee = txDetails.meta?.fee;\n if (fee !== undefined) span.setAttribute('solana.tx.fee_lamports', fee);\n\n const cuUsed = txDetails.meta?.computeUnitsConsumed;\n if (cuUsed !== undefined && cuUsed !== null) {\n span.setAttribute('solana.tx.cu_used', Number(cuUsed));\n span.setAttribute('solana.tx.cu_budget', 200_000);\n span.setAttribute(\n 'solana.tx.cu_utilization',\n parseFloat((Number(cuUsed) / 200_000 * 100).toFixed(1)),\n );\n }\n }\n\n /**\n * Parse program logs into a CPI tree, enrich with registered IDLs, and\n * emit one `cpi.invoke` event per invocation onto the span. Root\n * program/instruction names are copied onto span attributes so dashboards\n * can filter by them without walking events.\n */\n private async attachParsedLogsToSpan(span: Span, logs: string[]): Promise<CpiTree | undefined> {\n const { cpiTree } = parseLogs({ logs });\n await enrichTree(cpiTree, this.idlResolver);\n\n const attributions = flatAttributions(cpiTree);\n for (const attr of attributions) {\n span.addEvent('cpi.invoke', {\n 'cpi.program': attr.programName ?? attr.programId,\n 'cpi.instruction': attr.instructionName ?? 'unknown',\n 'cpi.depth': attr.depth,\n 'cpi.cu_consumed': attr.cuConsumed,\n 'cpi.cu_self': attr.cuSelf,\n 'cpi.percentage': parseFloat(attr.percentage.toFixed(2)),\n });\n }\n\n const root = cpiTree.roots[0];\n if (root) {\n if (root.programName) span.setAttribute('solana.tx.program', root.programName);\n if (root.instructionName) span.setAttribute('solana.tx.instruction', root.instructionName);\n }\n\n return cpiTree;\n }\n}\n\n// ─── Utilities ────────────────────────────────────────────────────────────\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n// ─── Re-exports ────────────────────────────────────────────────────────────\n\nexport { IdlResolver } from '@thesight/core';\nexport type {\n CpiTree,\n CuAttribution,\n FlamegraphItem,\n DecodedError,\n AnchorIdl,\n} from '@thesight/core';\n\n// ─── Tracing initialization ──────────────────────────────────────────────────\n\nexport { initSight } from './init.js';\nexport type { InitSightConfig, SightTracerHandle } from './init.js';\nexport { SightSpanExporter } from './exporter.js';\nexport type { SightExporterConfig } from './exporter.js';\n\n// ─── Non-wrapping observation helper ─────────────────────────────────────\n\nexport { trackSolanaTransaction } from './track.js';\nexport type { TrackTransactionOptions } from './track.js';\n","import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';\nimport { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';\nimport { Resource } from '@opentelemetry/resources';\nimport { SEMRESATTRS_SERVICE_NAME, SEMRESATTRS_SERVICE_VERSION } from '@opentelemetry/semantic-conventions';\nimport { SightSpanExporter } from './exporter.js';\n\n// ─── Config ──────────────────────────────────────────────────────────────────\n\nexport interface InitSightConfig {\n /** Project API key (`sk_live_...`) from the Sight dashboard. */\n apiKey: string;\n\n /**\n * Human-readable service name that shows up on every span. Pick something\n * that identifies this process — `'swap-bot'`, `'market-maker'`,\n * `'trade-settler'`, etc.\n */\n serviceName: string;\n\n /** Optional version string for the service. Useful for correlating spans with a deploy. */\n serviceVersion?: string;\n\n /**\n * Full ingest URL. Defaults to the hosted Sight ingest. Override for\n * local development (e.g. `http://localhost:3001/ingest`) or self-hosted\n * deployments.\n */\n ingestUrl?: string;\n\n /** BatchSpanProcessor flush interval, in ms. Defaults to 5s. */\n batchDelayMs?: number;\n\n /** Max spans per HTTP POST. Clamped to 100 by the exporter. */\n maxBatchSize?: number;\n\n /** Inject a fetch implementation for tests. Defaults to global fetch. */\n fetchImpl?: typeof fetch;\n}\n\nexport interface SightTracerHandle {\n provider: NodeTracerProvider;\n /** Flush any pending spans and release the batch processor. */\n shutdown: () => Promise<void>;\n}\n\n// ─── Entry point ────────────────────────────────────────────────────────────\n\nconst DEFAULT_INGEST_URL = 'https://ingest.thesight.dev/ingest';\n\n/**\n * Initialize Sight tracing. Call this **once** near the top of your\n * process entry point — typically in the same file that boots your\n * HTTP server or worker.\n *\n * import { initSight, InstrumentedConnection } from '@thesight/sdk';\n *\n * initSight({\n * apiKey: process.env.SIGHT_API_KEY!,\n * serviceName: 'swap-bot',\n * ingestUrl: process.env.SIGHT_INGEST_URL, // optional, defaults to prod\n * });\n *\n * const connection = new InstrumentedConnection(process.env.RPC_URL!);\n * const { signature } = await connection.sendAndConfirmInstrumented(tx);\n *\n * Registers a NodeTracerProvider as the global OTel tracer, so any call to\n * `trace.getTracer(...)` (including the ones inside `InstrumentedConnection`)\n * routes spans through the Sight exporter. Context propagation uses the\n * Node async hooks manager so spans nest correctly across await boundaries.\n *\n * Returns a handle with a `shutdown()` method. Call it at graceful shutdown\n * time so pending spans are flushed before the process exits:\n *\n * const sight = initSight({ ... });\n * process.on('SIGTERM', async () => {\n * await sight.shutdown();\n * process.exit(0);\n * });\n */\nexport function initSight(config: InitSightConfig): SightTracerHandle {\n if (!config.apiKey) {\n throw new Error('initSight: `apiKey` is required');\n }\n if (!config.serviceName) {\n throw new Error('initSight: `serviceName` is required');\n }\n\n const resource = new Resource({\n [SEMRESATTRS_SERVICE_NAME]: config.serviceName,\n ...(config.serviceVersion\n ? { [SEMRESATTRS_SERVICE_VERSION]: config.serviceVersion }\n : {}),\n });\n\n const provider = new NodeTracerProvider({ resource });\n\n const exporter = new SightSpanExporter({\n apiKey: config.apiKey,\n ingestUrl: config.ingestUrl ?? DEFAULT_INGEST_URL,\n fetchImpl: config.fetchImpl,\n maxBatchSize: config.maxBatchSize,\n });\n\n // BatchSpanProcessor buffers spans and flushes on an interval. This is the\n // right default for production — simple span processor is one HTTP round\n // trip per span, which is fine for tests and dev but nasty at scale.\n const processor = new BatchSpanProcessor(exporter, {\n scheduledDelayMillis: config.batchDelayMs ?? 5_000,\n maxExportBatchSize: config.maxBatchSize ?? 100,\n maxQueueSize: 2048,\n });\n\n provider.addSpanProcessor(processor);\n\n // Register as the global OTel tracer provider. After this call,\n // `trace.getTracer('anything')` returns a tracer from our provider,\n // which routes spans to SightSpanExporter.\n provider.register();\n\n return {\n provider,\n shutdown: async () => {\n await provider.shutdown();\n },\n };\n}\n","import type { SpanAttributes } from '@opentelemetry/api';\nimport type { SpanExporter, ReadableSpan } from '@opentelemetry/sdk-trace-base';\nimport {\n hrTimeToMilliseconds,\n ExportResultCode,\n type ExportResult,\n} from '@opentelemetry/core';\n\n// ─── Config ──────────────────────────────────────────────────────────────────\n\nexport interface SightExporterConfig {\n /** Project API key (`sk_live_...`). Sent as Bearer auth on every POST. */\n apiKey: string;\n /**\n * Full ingest URL including the path (e.g. `https://ingest.thesight.dev/ingest`\n * or `http://localhost:3001/ingest` for local dev).\n */\n ingestUrl: string;\n /** Inject a fake fetch in tests. Defaults to `globalThis.fetch`. */\n fetchImpl?: typeof fetch;\n /** Max spans per POST. Ingest enforces an upper bound of 100. */\n maxBatchSize?: number;\n}\n\n// ─── Exporter ────────────────────────────────────────────────────────────────\n\n/**\n * An OTel `SpanExporter` that translates OTel spans to Sight's custom\n * ingest payload shape and POSTs them to `/ingest`.\n *\n * Each span becomes one object in the `spans` array. Solana-specific\n * attributes flow through as-is (the set that `InstrumentedConnection`\n * already populates — `solana.tx.signature`, `solana.tx.cu_used`,\n * `solana.tx.program`, etc). The exporter intentionally does not attempt\n * to translate span events or links — the ingest schema doesn't have\n * slots for those, and we prefer dropping silently over guessing.\n *\n * The BatchSpanProcessor upstream handles retries, timeouts, and batching;\n * this exporter stays a thin wire-format translator.\n */\nexport class SightSpanExporter implements SpanExporter {\n private readonly apiKey: string;\n private readonly ingestUrl: string;\n private readonly fetchImpl: typeof fetch;\n private readonly maxBatchSize: number;\n private shuttingDown = false;\n\n constructor(config: SightExporterConfig) {\n this.apiKey = config.apiKey;\n this.ingestUrl = config.ingestUrl;\n this.fetchImpl = config.fetchImpl ?? (globalThis.fetch as typeof fetch);\n // Ingest's IngestPayload schema caps at 100 spans per POST. Allow\n // operators to lower the batch size for tighter latency, but never\n // raise it above the server's limit.\n this.maxBatchSize = Math.min(100, config.maxBatchSize ?? 100);\n\n if (!this.fetchImpl) {\n throw new Error(\n 'SightSpanExporter: globalThis.fetch is not available. Node >= 18 ships ' +\n 'with fetch built in, or pass `fetchImpl` explicitly.',\n );\n }\n }\n\n async export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void,\n ): Promise<void> {\n if (this.shuttingDown) {\n resultCallback({ code: ExportResultCode.FAILED, error: new Error('Exporter is shut down') });\n return;\n }\n\n // Split into chunks if the upstream processor handed us a larger\n // batch than ingest will accept. Uncommon with a well-configured\n // BatchSpanProcessor but cheap to handle defensively.\n const chunks: ReadableSpan[][] = [];\n for (let i = 0; i < spans.length; i += this.maxBatchSize) {\n chunks.push(spans.slice(i, i + this.maxBatchSize));\n }\n\n try {\n for (const chunk of chunks) {\n await this.sendChunk(chunk);\n }\n resultCallback({ code: ExportResultCode.SUCCESS });\n } catch (err) {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: err instanceof Error ? err : new Error(String(err)),\n });\n }\n }\n\n async shutdown(): Promise<void> {\n this.shuttingDown = true;\n }\n\n async forceFlush(): Promise<void> {\n // The exporter is stateless — BatchSpanProcessor's own forceFlush\n // drains the queue before calling export(). Nothing to do here.\n }\n\n // ─── Internal ──────────────────────────────────────────────────────────────\n\n private async sendChunk(spans: ReadableSpan[]): Promise<void> {\n const payload = {\n spans: spans.map((span) => this.convertSpan(span)),\n };\n\n const response = await this.fetchImpl(this.ingestUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`,\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const body = await safeReadText(response);\n throw new Error(\n `Sight ingest returned ${response.status} ${response.statusText}: ${body}`,\n );\n }\n }\n\n private convertSpan(span: ReadableSpan): IngestSpan {\n const attr = span.attributes;\n const resource = span.resource.attributes;\n const serviceName = typeof resource['service.name'] === 'string'\n ? resource['service.name']\n : undefined;\n const startTimeMs = hrTimeToMilliseconds(span.startTime);\n const endTimeMs = hrTimeToMilliseconds(span.endTime);\n const durationMs = Math.max(0, endTimeMs - startTimeMs);\n\n const out: IngestSpan = {\n traceId: span.spanContext().traceId,\n spanId: span.spanContext().spanId,\n spanName: span.name,\n startTimeMs,\n durationMs,\n };\n\n const parentSpanId = (span as { parentSpanId?: string }).parentSpanId;\n if (parentSpanId) out.parentSpanId = parentSpanId;\n if (serviceName) out.serviceName = serviceName;\n\n copyIfString(attr, 'solana.tx.signature', out);\n copyIfEnum(attr, 'solana.tx.status', out, ['confirmed', 'failed', 'timeout']);\n copyIfNumber(attr, 'solana.tx.slot', out);\n copyIfNumber(attr, 'solana.tx.cu_used', out);\n copyIfNumber(attr, 'solana.tx.cu_budget', out);\n copyIfNumber(attr, 'solana.tx.cu_utilization', out);\n copyIfString(attr, 'solana.tx.program', out);\n copyIfString(attr, 'solana.tx.instruction', out);\n copyIfString(attr, 'solana.tx.error', out);\n copyIfNumber(attr, 'solana.tx.error_code', out);\n copyIfString(attr, 'solana.tx.error_program', out);\n copyIfNumber(attr, 'solana.tx.submit_ms', out);\n copyIfNumber(attr, 'solana.tx.confirmation_ms', out);\n copyIfNumber(attr, 'solana.tx.fee_lamports', out);\n\n return out;\n }\n}\n\n// ─── Wire format (narrow, matches ingest's zod schema) ──────────────────────\n\ninterface IngestSpan {\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n serviceName?: string;\n spanName: string;\n startTimeMs: number;\n durationMs: number;\n\n 'solana.tx.signature'?: string;\n 'solana.tx.status'?: 'confirmed' | 'failed' | 'timeout';\n 'solana.tx.slot'?: number;\n 'solana.tx.cu_used'?: number;\n 'solana.tx.cu_budget'?: number;\n 'solana.tx.cu_utilization'?: number;\n 'solana.tx.program'?: string;\n 'solana.tx.instruction'?: string;\n 'solana.tx.error'?: string;\n 'solana.tx.error_code'?: number;\n 'solana.tx.error_program'?: string;\n 'solana.tx.submit_ms'?: number;\n 'solana.tx.confirmation_ms'?: number;\n 'solana.tx.fee_lamports'?: number;\n}\n\n// ─── Helpers ────────────────────────────────────────────────────────────────\n\nfunction copyIfString(\n attr: SpanAttributes,\n key: keyof IngestSpan & string,\n out: IngestSpan,\n): void {\n const v = attr[key];\n if (typeof v === 'string') {\n (out as unknown as Record<string, unknown>)[key] = v;\n }\n}\n\nfunction copyIfNumber(\n attr: SpanAttributes,\n key: keyof IngestSpan & string,\n out: IngestSpan,\n): void {\n const v = attr[key];\n if (typeof v === 'number' && Number.isFinite(v)) {\n (out as unknown as Record<string, unknown>)[key] = v;\n }\n}\n\nfunction copyIfEnum<T extends string>(\n attr: SpanAttributes,\n key: keyof IngestSpan & string,\n out: IngestSpan,\n allowed: readonly T[],\n): void {\n const v = attr[key];\n if (typeof v === 'string' && (allowed as readonly string[]).includes(v)) {\n (out as unknown as Record<string, unknown>)[key] = v;\n }\n}\n\nasync function safeReadText(res: Response): Promise<string> {\n try {\n return (await res.text()).slice(0, 500);\n } catch {\n return '<no body>';\n }\n}\n","import type { Connection, Finality, TransactionSignature, VersionedTransactionResponse } from '@solana/web3.js';\nimport { trace, context, SpanStatusCode, type Tracer } from '@opentelemetry/api';\nimport { parseLogs, IdlResolver, enrichTree, flatAttributions } from '@thesight/core';\nimport type { AnchorIdl } from '@thesight/core';\n\n// ─── Options ──────────────────────────────────────────────────────────────\n\nexport interface TrackTransactionOptions {\n /** The signature returned from a prior `sendRawTransaction` / `sendTransaction` call. */\n signature: TransactionSignature;\n\n /**\n * Any `@solana/web3.js` Connection — plain or instrumented. Used to fetch\n * the on-chain transaction via `getTransaction` for enrichment. Does\n * **not** need to be an `InstrumentedConnection`; this helper intentionally\n * never touches the transaction-send path.\n */\n connection: Connection;\n\n /**\n * Service name used for the span. Falls back to the service name\n * configured by `initSight`. Useful when you want a different service\n * name for a specific subsystem's spans.\n */\n serviceName?: string;\n\n /** OTel tracer override. Defaults to `trace.getTracer('@thesight/sdk')`. */\n tracer?: Tracer;\n\n /** Optional IDL resolver for program/error decoding. A fresh one is built if omitted. */\n idlResolver?: IdlResolver;\n\n /**\n * Pre-registered IDLs to hand to a freshly-built resolver. Ignored when\n * `idlResolver` is provided.\n */\n idls?: Record<string, AnchorIdl>;\n\n /** Finality commitment used for the enrichment fetch. Default 'confirmed'. */\n commitment?: Finality;\n\n /** Max wall-time before the span is ended with status=timeout. Default 30000ms. */\n timeoutMs?: number;\n\n /** Base poll interval for retrying getTransaction. Default 500ms. */\n pollIntervalMs?: number;\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────\n\n/**\n * **Non-wrapping observation helper.** Given a transaction signature that\n * was already sent through any `Connection`, fetch the on-chain record,\n * parse the logs, and emit a single OpenTelemetry span describing the\n * transaction.\n *\n * Unlike `InstrumentedConnection`, this helper **never touches the send\n * path** — it only observes after the fact via `getTransaction(signature)`.\n * Use this when:\n *\n * - You want observability for wallet-adapter flows where the send path\n * goes through the wallet and you can't easily override the Connection\n * - You're security-conscious and don't want any SDK code on the critical\n * transaction path\n * - You want to instrument a handful of high-value transactions rather\n * than every call a Connection makes\n *\n * Usage:\n *\n * import { trackSolanaTransaction } from '@thesight/sdk';\n * import { Connection } from '@solana/web3.js';\n *\n * const connection = new Connection(rpcUrl);\n * const signature = await wallet.sendTransaction(tx, connection);\n *\n * // Fire-and-forget. Span flushes on its own.\n * void trackSolanaTransaction({\n * signature,\n * connection,\n * serviceName: 'checkout',\n * idls: { [programId]: idl },\n * });\n *\n * Returns a `Promise<void>` — typically not awaited, but callers who want\n * to wait for the span to export (e.g. short-lived scripts) can await it.\n */\nexport async function trackSolanaTransaction(opts: TrackTransactionOptions): Promise<void> {\n const tracerName = opts.serviceName ?? '@thesight/sdk';\n const tracer = opts.tracer ?? trace.getTracer(tracerName);\n\n const span = tracer.startSpan('solana.trackTransaction', {}, context.active());\n span.setAttribute('solana.tx.signature', opts.signature);\n\n const start = Date.now();\n const deadline = start + (opts.timeoutMs ?? 30_000);\n const commitment = opts.commitment ?? ('confirmed' as Finality);\n const basePoll = opts.pollIntervalMs ?? 500;\n\n const resolver = opts.idlResolver ?? buildResolverFromIdls(opts.idls);\n\n try {\n const txDetails = await pollGetTransaction(opts.connection, opts.signature, commitment, deadline, basePoll);\n if (!txDetails) {\n span.setAttribute('solana.tx.status', 'timeout');\n span.setAttribute('solana.tx.enrichment_ms', Date.now() - start);\n return;\n }\n\n span.setAttribute('solana.tx.status', txDetails.meta?.err ? 'failed' : 'confirmed');\n span.setAttribute('solana.tx.slot', txDetails.slot);\n\n const fee = txDetails.meta?.fee;\n if (fee !== undefined) span.setAttribute('solana.tx.fee_lamports', fee);\n\n const cuUsed = txDetails.meta?.computeUnitsConsumed;\n if (cuUsed !== undefined && cuUsed !== null) {\n span.setAttribute('solana.tx.cu_used', Number(cuUsed));\n span.setAttribute('solana.tx.cu_budget', 200_000);\n span.setAttribute(\n 'solana.tx.cu_utilization',\n parseFloat((Number(cuUsed) / 200_000 * 100).toFixed(1)),\n );\n }\n\n const logs = txDetails.meta?.logMessages ?? [];\n if (logs.length > 0) {\n const { cpiTree } = parseLogs({ logs });\n await enrichTree(cpiTree, resolver);\n\n for (const attr of flatAttributions(cpiTree)) {\n span.addEvent('cpi.invoke', {\n 'cpi.program': attr.programName ?? attr.programId,\n 'cpi.instruction': attr.instructionName ?? 'unknown',\n 'cpi.depth': attr.depth,\n 'cpi.cu_consumed': attr.cuConsumed,\n 'cpi.cu_self': attr.cuSelf,\n 'cpi.percentage': parseFloat(attr.percentage.toFixed(2)),\n });\n }\n\n const root = cpiTree.roots[0];\n if (root) {\n if (root.programName) span.setAttribute('solana.tx.program', root.programName);\n if (root.instructionName) span.setAttribute('solana.tx.instruction', root.instructionName);\n }\n }\n\n span.setAttribute('solana.tx.enrichment_ms', Date.now() - start);\n\n if (txDetails.meta?.err) {\n span.setStatus({ code: SpanStatusCode.ERROR });\n } else {\n span.setStatus({ code: SpanStatusCode.OK });\n }\n } catch (err) {\n span.recordException(err instanceof Error ? err : new Error(String(err)));\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err instanceof Error ? err.message : String(err),\n });\n } finally {\n span.end();\n }\n}\n\n// ─── Helpers ──────────────────────────────────────────────────────────────\n\nfunction buildResolverFromIdls(idls?: Record<string, AnchorIdl>): IdlResolver {\n const resolver = new IdlResolver();\n if (idls) resolver.registerMany(idls);\n return resolver;\n}\n\nasync function pollGetTransaction(\n connection: Connection,\n signature: TransactionSignature,\n commitment: Finality,\n deadline: number,\n basePollMs: number,\n): Promise<VersionedTransactionResponse | null> {\n let attempt = 0;\n while (Date.now() < deadline) {\n try {\n const tx = await connection.getTransaction(signature, {\n commitment,\n maxSupportedTransactionVersion: 0,\n });\n if (tx) return tx;\n } catch {\n // Ignore — retry with backoff\n }\n attempt++;\n const waitMs = Math.min(basePollMs * Math.pow(1.5, attempt - 1), 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,QAAI,wBAAU,EAAE,KAAK,CAAC;AACtC,cAAM,yBAAW,SAAS,KAAK,WAAW;AAE1C,UAAM,mBAAe,+BAAiB,OAAO;AAC7C,eAAW,QAAQ,cAAc;AAC/B,WAAK,SAAS,cAAc;AAAA,QAC1B,eAAoB,KAAK,eAAe,KAAK;AAAA,QAC7C,mBAAoB,KAAK,mBAAmB;AAAA,QAC5C,aAAoB,KAAK;AAAA,QACzB,mBAAoB,KAAK;AAAA,QACzB,eAAoB,KAAK;AAAA,QACzB,kBAAoB,WAAW,KAAK,WAAW,QAAQ,CAAC,CAAC;AAAA,MAC3D,CAAC;AAAA,IACH;AAEA,UAAM,OAAO,QAAQ,MAAM,CAAC;AAC5B,QAAI,MAAM;AACR,UAAI,KAAK,YAAiB,MAAK,aAAa,qBAAyB,KAAK,WAAW;AACrF,UAAI,KAAK,gBAAiB,MAAK,aAAa,yBAAyB,KAAK,eAAe;AAAA,IAC3F;AAEA,WAAO;AAAA,EACT;AACF;AAIA,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;","names":["import_api","import_core","import_core"]}
package/dist/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
- import { Connection, ConnectionConfig, Commitment, Transaction, VersionedTransaction, SendOptions } from '@solana/web3.js';
1
+ import { TransactionSignature, Connection, Finality, ConnectionConfig, Commitment, SendOptions } from '@solana/web3.js';
2
2
  import { Tracer } from '@opentelemetry/api';
3
- import { AnchorIdl, CpiTree, DecodedError } from '@thesight/core';
3
+ import { IdlResolver, AnchorIdl } from '@thesight/core';
4
4
  export { AnchorIdl, CpiTree, CuAttribution, DecodedError, FlamegraphItem, IdlResolver } from '@thesight/core';
5
5
  import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
6
6
  import { SpanExporter, ReadableSpan } from '@opentelemetry/sdk-trace-base';
@@ -108,14 +108,92 @@ declare class SightSpanExporter implements SpanExporter {
108
108
  private convertSpan;
109
109
  }
110
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
+
111
181
  interface SightConfig {
112
- /** OTel tracer. Get via trace.getTracer('your-service') */
182
+ /** OTel tracer. Defaults to `trace.getTracer('@thesight/sdk')`. */
113
183
  tracer?: Tracer;
114
184
  /** Override RPC endpoint for IDL fetching (defaults to same as connection) */
115
185
  idlRpcEndpoint?: string;
116
- /** Commitment to use when fetching confirmed tx details */
186
+ /**
187
+ * Commitment used when fetching confirmed tx details for enrichment.
188
+ * Defaults to 'confirmed'.
189
+ */
117
190
  commitment?: Commitment;
118
- /** 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
+ */
119
197
  skipIdlResolution?: boolean;
120
198
  /**
121
199
  * Pre-register IDLs at construction time. Keys are program IDs, values are
@@ -126,18 +204,35 @@ interface SightConfig {
126
204
  /**
127
205
  * Opt into reading Anchor IDL accounts from the on-chain PDA as a fallback
128
206
  * when a program is not explicitly registered. Defaults to **false** —
129
- * Sight's model is that IDLs are explicitly provided by the application
130
- * (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.
131
209
  */
132
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;
133
229
  }
134
230
  interface SightSpanAttributes {
135
231
  'solana.tx.signature': string;
136
- 'solana.tx.status': 'confirmed' | 'failed' | 'timeout';
232
+ 'solana.tx.status': 'submitted' | 'confirmed' | 'failed' | 'timeout';
137
233
  'solana.tx.slot'?: number;
138
234
  'solana.tx.fee_lamports'?: number;
139
235
  'solana.tx.submit_ms': number;
140
- 'solana.tx.confirmation_ms'?: number;
141
236
  'solana.tx.enrichment_ms'?: number;
142
237
  'solana.tx.cu_used'?: number;
143
238
  'solana.tx.cu_budget'?: number;
@@ -150,17 +245,41 @@ interface SightSpanAttributes {
150
245
  'solana.tx.error_msg'?: string;
151
246
  }
152
247
  /**
153
- * Drop-in replacement for @solana/web3.js Connection that instruments
154
- * 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.
155
266
  *
156
267
  * Usage:
157
- * const connection = new InstrumentedConnection(rpcUrl, {
158
- * tracer: trace.getTracer('my-service'),
159
- * });
160
268
  *
161
- * The Solana transaction becomes a child span of whatever OTel context
162
- * is active when sendAndConfirmTransaction is called — so it automatically
163
- * 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
164
283
  */
165
284
  declare class InstrumentedConnection extends Connection {
166
285
  private sightConfig;
@@ -179,16 +298,41 @@ declare class InstrumentedConnection extends Connection {
179
298
  /** Bulk-register multiple IDLs. */
180
299
  registerIdls(idls: Record<string, AnchorIdl>): void;
181
300
  /**
182
- * Sends and confirms a transaction, wrapped in an OTel span.
183
- * 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.
184
334
  */
185
- sendAndConfirmInstrumented(transaction: Transaction | VersionedTransaction, options?: SendOptions & {
186
- commitment?: Commitment;
187
- }): Promise<{
188
- signature: string;
189
- cpiTree?: CpiTree;
190
- error?: DecodedError;
191
- }>;
335
+ private attachParsedLogsToSpan;
192
336
  }
193
337
 
194
- export { type InitSightConfig, InstrumentedConnection, type SightConfig, type SightExporterConfig, type SightSpanAttributes, SightSpanExporter, type SightTracerHandle, initSight };
338
+ export { type InitSightConfig, InstrumentedConnection, type SightConfig, type SightExporterConfig, type SightSpanAttributes, SightSpanExporter, type SightTracerHandle, type TrackTransactionOptions, initSight, trackSolanaTransaction };