
Loading...

Loading...
lightnode-sdk 0.6.x
Open any module for a focused page with live data, runnable snippets, and one-click sandboxes.
Top up a server wallet, let users pay in ETH, or move earnings back. Typed wrapper around the LightChain Hyperlane Warp Route - quote, approve, transfer LCAI both directions. Pair it with a Uniswap swap for a complete ETH-to-native-LCAI flow.
OpenRead + vote on LCAI Governor proposals on Ethereum. Real OZ Governor v5 wrapper. Cast votes, propose, queue, execute.
Opennew Conversation({ network, privateKey }).send('hi') keeps history client-side and runs one encrypted inference per turn. Optional system prompt + maxHistoryTurns cap.
OpenworkerPreflight submits ONE real test inference + returns verdict. workerWatch streams state-change events (registered, went-stale, jobs-completed) for any worker, no key required.
Openln.getJobStatus(jobId) classifies a job (submitted / in-flight / completed / stalled / disputed / resolved) and exposes a refundable flag.
OpenOn LightChain mainnet the official model registry is AIConfig - whitelisted models, fees, and output limits. ln.getModels() / ln.estimateFee() read it directly. The custom lcai_listSupportedModels RPC method returns the live whitelist.
OpenTwo higher-level abstractions on top of runInferenceWithKey. Same proof chain, same encrypted session - just less boilerplate for common patterns.
Fan out many prompts as parallel encrypted inferences with a capped concurrency. Stable result order, per-slot errors so one stalled worker does not kill the batch. Optional onSlotComplete for live progress UI, optional AbortSignal to cancel queued work.
import { runInferenceBatch } from "lightnode-sdk";
const results = await runInferenceBatch({
network: "testnet",
privateKey: process.env.PRIVATE_KEY!,
model: "llama3-8b",
system: "Reply in one short sentence.",
concurrency: 4,
prompts: [
"fact about the ocean",
"fact about the moon",
"fact about coffee",
],
onSlotComplete: ({ index, result, error }) => {
console.log(`#${index}`, error?.message ?? result?.answer);
},
});Fits: batch evals, content scoring, RAG re-ranking, parallel rewrites.
ReAct-style loop: model thinks, picks a tool, runs it, observes the result, iterates. Uses simple string markers (<tool> / <answer>) so it works on small open models like llama3-8b without native function-calling support.
import { Agent } from "lightnode-sdk";
const agent = new Agent({
network: "testnet",
privateKey: process.env.PRIVATE_KEY!,
model: "llama3-8b",
system: "You are a careful research assistant.",
tools: [{
name: "add",
description: "Add two integers, return the sum.",
args: { a: "int", b: "int" },
handler: ({ a, b }) => Number(a) + Number(b),
}],
maxIterations: 4,
});
const { answer, steps } = await agent.run("17 + 25?");Fits: autonomous tasks, search + summarize, lookup chains, multi-step reasoning with deterministic side-effects.
Plus AbortSignal support added to runInferenceWithKey for cancellable UI flows (in-flight on-chain txs still settle; the SDK just stops awaiting).
Pick the highest one that fits. Lower tiers exist for control, not for prestige.
runInferenceWithKeyKey in, answer out.Pass a network ID, a private key, a prompt. The SDK builds the viem clients, runs the SIWE handshake, opens the encrypted session, submits, decrypts. The example in the quickstart-inference folder is this.
Quickest possible builder onboarding. CLI tools, demos, scripts.
runInferenceBring your own viem clients + JWT.You already wire up wagmi or a server-side viem WalletClient. Pass the gateway client (with bearer) plus the wallet and public clients. Same retry, streaming, and proof chain as the high tier.
Production apps with their own auth/keystore. The /playground page uses this with a Reown wallet.
prepareSession + submitPrompt + decryptResponseDrive each step yourself.Call prepareSession to pick a worker and get a wrapped session key. Sign createSession yourself. Encrypt + upload with submitPrompt. Sign submitJob. Decrypt frames with decryptResponse. Plus the typed errors below if you want to recover differently than the default retry policy.
Multi-turn chat with session reuse, custom retry, batching, anything bespoke.
The architectural choice that catches builders by surprise. Both patterns use the same SDK.
You hold a hot wallet on the server, top it up, the user just hits your API. Build on runInferenceWithKey or the Next.js route in lightnode-examples. Your cost per call.
Examples: Next.js API route, Hono server, agent / cron, NFT mint endpoint
Wire wagmi (or Reown / RainbowKit / Web3Modal) into a React page. The user connects a wallet, runs the inference, signs createSession + submitJob. The user pays. You hold no keys.
Examples: lightnode.app/playground (open source, copy the source)
The SDK does not wrap everything in a generic catch. Four named errors so a builder can branch on them.
| Error | When it fires | How to recover |
|---|---|---|
StalledWorkerError | A worker acknowledged the job but never produced an answer. | Default retry policy assigns a different worker, up to maxRetries (2). Use isStalledWorker(e) to branch on it. The protocol times the stalled worker out and refunds the fee after the dispute window. |
OnChainRevertError | createSession or submitJob reverted on-chain (wrong network, insufficient gas, expired session). | Surfaces which tx reverted plus the tx hash so you can read the exact revert reason from the explorer. |
RelayTokenTimeoutError | The dispatcher never issued a relay-streaming token (gateway-side issue). | Almost always transient. Retry with a fresh prepareSession. Indicates the gateway, not your wallet or the worker. |
GatewayAuthError | SIWE challenge failed, verify rejected, or the JWT expired mid-flight. | Re-run the SIWE handshake. Cache the JWT in sessionStorage with the issued expiry minus a 30s safety margin to avoid this in long-lived UIs (see /playground source for the pattern). |
Plus isStalledWorker(e) as a type guard so a TS narrowing branch lights up without an instanceof check.