lightnode-sdk 0.7.0 → 0.7.2

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/README.md CHANGED
@@ -5,9 +5,10 @@
5
5
 
6
6
  **The community SDK for LightChain AI.** Encrypted on-chain inference, network
7
7
  analytics, multi-turn chat, an Ethereum bridge wrapper, an LCAI Governor
8
- client, an on-chain model registry reader, worker preflight + watch, and a
9
- bundled `lightnode` CLI. Non-custodial. Pure JS (works in Node 18+, browsers,
10
- StackBlitz, Cloudflare Workers, Bun). Single peer dep: `viem`.
8
+ client, an on-chain model registry reader, worker preflight + watch, a full
9
+ worker-operator surface (register, stake, settle, stuck-job recovery, exit),
10
+ and a bundled `lightnode` CLI. Non-custodial. Pure JS (works in Node 18+,
11
+ browsers, StackBlitz, Cloudflare Workers, Bun). Single peer dep: `viem`.
11
12
 
12
13
  ```bash
13
14
  npm install lightnode-sdk viem
@@ -255,6 +256,29 @@ await op.withdraw(); // pull earned balance into the worker wallet
255
256
  await op.unstickAndDeregister([974, 976, 978, 979]);
256
257
  ```
257
258
 
259
+ Full method reference (`jobIds` are the worker's IDs from
260
+ `LightNode.getWorkerJobs` or the subgraph):
261
+
262
+ | Method | Wallet | What it does |
263
+ |---|---|---|
264
+ | `status()` | no | registration, stake, claimable balance, below-floor flag |
265
+ | `config()` | no | live AIConfig: minStake, timeouts, slash bps, fee split |
266
+ | `getJob(id)` | no | one job as a typed `OnchainJob` struct |
267
+ | `stuckJobs(jobIds)` | no | the acked, past-deadline jobs (with seconds past deadline) |
268
+ | `canDeregister(jobIds)` | no | `{ ok, blockedBy, reason }` without sending a tx |
269
+ | `earnings({ ... })` | no | claimable now vs lifetime vs pending-release |
270
+ | `profitability({ ... })` | no | per-job worker fee net of gas, from the live fee split |
271
+ | `claimTimeout(id)` | yes | time out one stuck job (mainnet: realizes a slash) |
272
+ | `clearStuck(jobIds)` | yes | claimTimeout every past-deadline acked job; returns cleared + skipped |
273
+ | `releaseJob(id)` | yes | settle one completed job past its window |
274
+ | `releaseAll(jobIds)` | yes | settle all releasable completed jobs; skips not-ready ones |
275
+ | `withdraw()` | yes | pull the earned balance into the worker wallet |
276
+ | `topUpStake(lcai)` | yes | add stake |
277
+ | `withdrawStake(lcai)` | yes | remove stake above the floor |
278
+ | `reinstate()` | yes | reactivate a suspended worker |
279
+ | `deregister()` | yes | exit and release stake (reverts if in-flight jobs remain) |
280
+ | `unstickAndDeregister(jobIds)` | yes | clear stuck + release + withdraw + deregister, in one call |
281
+
258
282
  > **Mainnet slashing.** `claimTimeout` / `clearStuck` / `unstickAndDeregister`
259
283
  > finalize a stuck job as `TimedOut`, which **realizes the completion-timeout
260
284
  > slash** on mainnet (`config().slashBps.completionTimeout`, 5% of stake per job
@@ -402,12 +426,30 @@ npx lightnode dao config # live voting delay / period / threshol
402
426
 
403
427
  ```bash
404
428
  PRIVATE_KEY=0x... npx lightnode chat "Write me a haiku about LightChain"
429
+ PRIVATE_KEY=0x... npx lightnode batch prompts.json --concurrency 4 # N prompts in parallel
430
+ PRIVATE_KEY=0x... npx lightnode agent "research X and summarize" # ReAct agent, built-in tools
405
431
  PRIVATE_KEY=0x... npx lightnode wallet address
406
432
  PRIVATE_KEY=0x... npx lightnode wallet balance --net testnet
407
433
  npx lightnode wallet new # generates a fresh key
408
434
  PRIVATE_KEY=0x... npx lightnode worker preflight --net testnet
409
435
  ```
410
436
 
437
+ ### Worker operator (signs as the worker key)
438
+
439
+ Run a worker's on-chain lifecycle from the terminal. `status` and `can-deregister`
440
+ are read-only; the rest sign with `PRIVATE_KEY` and act on the worker that key
441
+ controls. Mainnet `clearstuck` and `deregister` realize a slash, so they require
442
+ `--yes`.
443
+
444
+ ```bash
445
+ npx lightnode worker status 0x... # registration, stake, claimable, live config
446
+ PRIVATE_KEY=0x... npx lightnode worker can-deregister # what blocks the exit, before spending gas
447
+ PRIVATE_KEY=0x... npx lightnode worker settle # release completed jobs past their window + withdraw
448
+ PRIVATE_KEY=0x... npx lightnode worker withdraw # pull the earned balance into the worker wallet
449
+ PRIVATE_KEY=0x... npx lightnode worker clearstuck --yes # claimTimeout acked, past-deadline jobs that block exit
450
+ PRIVATE_KEY=0x... npx lightnode worker deregister --yes # clear stuck + settle + withdraw + deregister
451
+ ```
452
+
411
453
  ### Scaffolders (write files into your project)
412
454
 
413
455
  ```bash
package/dist/analytics.js CHANGED
@@ -76,7 +76,7 @@ function groupBy(jobs, key) {
76
76
  export function aggregateModelStats(jobs, models, nowSec = Math.floor(Date.now() / 1000)) {
77
77
  const nameById = new Map(models.map((m) => [m.id.toLowerCase(), m.name]));
78
78
  return [...groupBy(jobs, (j) => j.model_id?.toLowerCase()).entries()]
79
- .map(([id, js]) => ({ modelId: id, name: nameById.get(id) ?? `${id.slice(0, 10)}…`, ...classifyJobs(js, nowSec) }))
79
+ .map(([id, js]) => ({ modelId: id, name: nameById.get(id) ?? `${id.slice(0, 10)}...`, ...classifyJobs(js, nowSec) }))
80
80
  .sort((a, b) => b.total - a.total);
81
81
  }
82
82
  /** Per-worker reliability, busiest first (top `limit`). */
package/dist/dao.d.ts CHANGED
@@ -329,6 +329,37 @@ export declare const GOVERNOR_ABI: readonly [{
329
329
  readonly outputs: readonly [{
330
330
  readonly type: "bool";
331
331
  }];
332
+ }, {
333
+ readonly name: "ProposalCreated";
334
+ readonly type: "event";
335
+ readonly inputs: readonly [{
336
+ readonly type: "uint256";
337
+ readonly name: "proposalId";
338
+ }, {
339
+ readonly type: "address";
340
+ readonly name: "proposer";
341
+ }, {
342
+ readonly type: "address[]";
343
+ readonly name: "targets";
344
+ }, {
345
+ readonly type: "uint256[]";
346
+ readonly name: "values";
347
+ }, {
348
+ readonly type: "string[]";
349
+ readonly name: "signatures";
350
+ }, {
351
+ readonly type: "bytes[]";
352
+ readonly name: "calldatas";
353
+ }, {
354
+ readonly type: "uint256";
355
+ readonly name: "voteStart";
356
+ }, {
357
+ readonly type: "uint256";
358
+ readonly name: "voteEnd";
359
+ }, {
360
+ readonly type: "string";
361
+ readonly name: "description";
362
+ }];
332
363
  }];
333
364
  /** Minimal IVotes ABI for delegate + balance reads (LCAIBallots). */
334
365
  export declare const VOTES_ABI: readonly [{
@@ -380,6 +411,18 @@ interface MinimalPublicClient {
380
411
  functionName: string;
381
412
  args?: readonly unknown[];
382
413
  }) => Promise<unknown>;
414
+ getBlockNumber?: () => Promise<bigint>;
415
+ getLogs?: (args: {
416
+ address?: `0x${string}`;
417
+ event?: unknown;
418
+ args?: Record<string, unknown>;
419
+ fromBlock?: bigint | "earliest" | "latest";
420
+ toBlock?: bigint | "latest";
421
+ }) => Promise<ReadonlyArray<{
422
+ args?: Record<string, unknown>;
423
+ blockNumber?: bigint;
424
+ transactionHash?: `0x${string}`;
425
+ }>>;
383
426
  }
384
427
  interface MinimalWalletClient {
385
428
  writeContract: (args: {
@@ -412,6 +455,20 @@ export interface DaoConfig {
412
455
  /** Approx voting period in seconds, assuming 12s/block on Ethereum. */
413
456
  votingPeriodSecs: number;
414
457
  }
458
+ /**
459
+ * One row returned by `DAO.recentProposals`. Lightweight summary you can
460
+ * map straight into a list UI. Use `dao.proposal(id)` for the full vote
461
+ * counts and exact deadlines.
462
+ */
463
+ export interface ProposalRow {
464
+ id: bigint;
465
+ proposer: `0x${string}`;
466
+ /** First non-empty line of the proposal `description`. */
467
+ title: string;
468
+ state: ProposalState;
469
+ stateLabel: string;
470
+ blockNumber: bigint;
471
+ }
415
472
  /**
416
473
  * DAO client. Wraps reads (proposal state, config) + writes (propose, vote,
417
474
  * queue, execute) on the Ethereum LCAIGovernor.
@@ -434,6 +491,19 @@ export declare class DAO {
434
491
  config(): Promise<DaoConfig>;
435
492
  /** Quorum required at a given timepoint (in wei of voting weight). */
436
493
  quorum(timepoint: bigint): Promise<bigint>;
494
+ /**
495
+ * List recent proposals on the governor by scanning `ProposalCreated`
496
+ * events. Scans back `lookbackBlocks` from the current head and returns
497
+ * up to `limit` proposals (newest first) with their current state.
498
+ *
499
+ * Ethereum mainnet RPCs cap a single `getLogs` to 10k blocks; the SDK
500
+ * chunks the range automatically. Default lookback is 300k blocks
501
+ * (~40 days) and default limit is 10.
502
+ */
503
+ recentProposals(opts?: {
504
+ lookbackBlocks?: number;
505
+ limit?: number;
506
+ }): Promise<ProposalRow[]>;
437
507
  /** Cast a For / Against / Abstain vote. Wallet must be the voter and have delegated their LCAI. */
438
508
  castVote(proposalId: bigint, support: VoteSupport, reason?: string): Promise<`0x${string}`>;
439
509
  /** Submit a new proposal. Wallet must hold at least `proposalThreshold` delegated votes. */
package/dist/dao.js CHANGED
@@ -98,6 +98,8 @@ export const GOVERNOR_ABI = parseAbi([
98
98
  "function proposalEta(uint256 proposalId) external view returns (uint256)",
99
99
  "function getVotes(address account, uint256 timepoint) external view returns (uint256)",
100
100
  "function hasVoted(uint256 proposalId, address account) external view returns (bool)",
101
+ // Events - needed for recentProposals() event scan.
102
+ "event ProposalCreated(uint256 proposalId, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 voteStart, uint256 voteEnd, string description)",
101
103
  ]);
102
104
  /** Minimal IVotes ABI for delegate + balance reads (LCAIBallots). */
103
105
  export const VOTES_ABI = parseAbi([
@@ -190,6 +192,75 @@ export class DAO {
190
192
  args: [timepoint],
191
193
  });
192
194
  }
195
+ /**
196
+ * List recent proposals on the governor by scanning `ProposalCreated`
197
+ * events. Scans back `lookbackBlocks` from the current head and returns
198
+ * up to `limit` proposals (newest first) with their current state.
199
+ *
200
+ * Ethereum mainnet RPCs cap a single `getLogs` to 10k blocks; the SDK
201
+ * chunks the range automatically. Default lookback is 300k blocks
202
+ * (~40 days) and default limit is 10.
203
+ */
204
+ async recentProposals(opts = {}) {
205
+ if (!this.publicClient.getLogs || !this.publicClient.getBlockNumber) {
206
+ throw new Error("DAO.recentProposals: publicClient does not expose getLogs / getBlockNumber. Use a viem PublicClient.");
207
+ }
208
+ const lookback = BigInt(opts.lookbackBlocks ?? 300000);
209
+ const limit = Math.max(1, opts.limit ?? 10);
210
+ const head = await this.publicClient.getBlockNumber();
211
+ const start = head > lookback ? head - lookback : 0n;
212
+ const CHUNK = 10000n;
213
+ // ProposalCreated is item index that matches the parsed ABI entry.
214
+ const event = GOVERNOR_ABI.find((x) => x.type === "event" && x.name === "ProposalCreated");
215
+ if (!event)
216
+ throw new Error("DAO.recentProposals: ProposalCreated event missing from GOVERNOR_ABI");
217
+ // Fan out chunked log reads in parallel - same shape the public proxy
218
+ // endpoint uses, but driven entirely by the caller's RPC.
219
+ const ranges = [];
220
+ for (let from = start; from <= head; from += CHUNK) {
221
+ const to = from + CHUNK - 1n > head ? head : from + CHUNK - 1n;
222
+ ranges.push({ from, to });
223
+ }
224
+ const rows = [];
225
+ const settled = await Promise.allSettled(ranges.map((r) => this.publicClient.getLogs({
226
+ address: this.addresses.governor,
227
+ event,
228
+ fromBlock: r.from,
229
+ toBlock: r.to,
230
+ })));
231
+ for (const res of settled) {
232
+ if (res.status !== "fulfilled")
233
+ continue;
234
+ for (const log of res.value) {
235
+ const args = log.args ?? {};
236
+ const id = args.proposalId;
237
+ const proposer = args.proposer;
238
+ const description = args.description ?? "";
239
+ if (id == null || !proposer)
240
+ continue;
241
+ const title = description.split(/\r?\n/).map((s) => s.trim()).find(Boolean) ?? `Proposal #${id.toString()}`;
242
+ rows.push({
243
+ id,
244
+ proposer,
245
+ title: title.length > 140 ? title.slice(0, 137) + "..." : title,
246
+ // state filled in below in one batched call
247
+ state: 0,
248
+ stateLabel: "",
249
+ blockNumber: log.blockNumber ?? 0n,
250
+ });
251
+ }
252
+ }
253
+ // Sort newest-first by id (uint256 monotonic in OZ Governor) and trim.
254
+ rows.sort((a, b) => (b.id > a.id ? 1 : b.id < a.id ? -1 : 0));
255
+ const trimmed = rows.slice(0, limit);
256
+ // Fetch the live state for each in parallel so the row is immediately usable.
257
+ const states = await Promise.all(trimmed.map((r) => this.state(r.id).catch(() => 0)));
258
+ return trimmed.map((r, i) => ({
259
+ ...r,
260
+ state: states[i],
261
+ stateLabel: PROPOSAL_STATE_LABEL[states[i]] ?? "unknown",
262
+ }));
263
+ }
193
264
  // -------- Writes --------
194
265
  /** Cast a For / Against / Abstain vote. Wallet must be the voter and have delegated their LCAI. */
195
266
  castVote(proposalId, support, reason) {
package/dist/index.d.ts CHANGED
@@ -91,7 +91,7 @@ export declare class LightNode {
91
91
  * (especially in registry-proxy environments like StackBlitz where lockfiles
92
92
  * may pin an older minor than the local install command suggests).
93
93
  */
94
- export declare const SDK_VERSION = "0.7.0";
94
+ export declare const SDK_VERSION = "0.7.2";
95
95
  export { NETWORKS, WORKER_REGISTRY, REGISTRY_TOPICS, aggregateModelStats, aggregateWorkerStats, networkAnalytics, modelStatsCsv, workerStatsCsv, workerJobsCsv, fromWei, computeModelId as modelId, estimateJobFee, JOB_REGISTRY_CONSUMER_ABI, consumerGatewayUrl, consumerGatewayHost, GatewayClient, GatewayHttpError, prepareSession, submitPrompt, decryptResponse, generateEcdhKeyPair, crypto, runInference, runInferenceWithKey, runInferenceStream, Conversation, chat, runInferenceBatch, Agent, parseAgentOutput, workerPreflight, workerWatch, Bridge, BRIDGE_ROUTE, HYPERLANE_ROUTER_ABI, ERC20_ABI, addressToBytes32, quoteBridgeFee, bridgeableBalance, bridgeAllowance, approveBridge, bridgeTransfer, DAO, DAO_ADDRESSES, ProposalState, PROPOSAL_STATE_LABEL, VoteSupport, GOVERNOR_ABI, VOTES_ABI, OnchainModelRegistry, AIVM_MODEL_REGISTRY_ABI, BENCHMARK_REGISTRY_ABI, ModelStatus, MODEL_STATUS_LABEL, StalledWorkerError, OnChainRevertError, RelayTokenTimeoutError, GatewayAuthError, isStalledWorker, WorkerOperator, WORKER_REGISTRY_ABI, JOB_REGISTRY_OPERATOR_ABI, AI_CONFIG_ABI, JOB_STATE, decodeWorkerError, WorkerOpError, isWorkerOpError, };
96
96
  export type { BearerSource, GatewayClientOptions, SelectSessionResult, PrepareSessionResult, UploadBlobResult, SessionTokenResult } from "./gateway.js";
97
97
  export type { SessionPreparation, RunInferenceArgs, RunInferenceResult, RunInferenceWithKeyArgs, RunInferenceStreamResult } from "./inference.js";
@@ -100,7 +100,7 @@ export type { BatchPrompt, BatchResult, RunInferenceBatchArgs } from "./batch.js
100
100
  export type { AgentTool, AgentStep, AgentOptions, AgentRunResult } from "./agent.js";
101
101
  export type { WorkerPreflightArgs, WorkerPreflightResult, WorkerWatchOptions, WorkerEventKind, WorkerEvent, WorkerWatchHandle } from "./worker.js";
102
102
  export type { BridgeChain, BridgeEndpoints, BridgeTransferArgs } from "./bridge.js";
103
- export type { DaoChain, DaoAddresses, ProposalSummary, DaoConfig } from "./dao.js";
103
+ export type { DaoChain, DaoAddresses, ProposalSummary, ProposalRow, DaoConfig } from "./dao.js";
104
104
  export type { BaseModel, ModelVariant, AccessTier, AccessPolicy, Benchmark, OnchainModelRegistryOptions } from "./onchain-models.js";
105
105
  export type { MinimalWalletClient, MinimalPublicClient, WorkerOperatorOpts, WorkerProtocolConfig, WorkerStatus, DeregisterReadiness, StuckJob, EarningsBreakdown, OnchainJob, JobState, DecodedWorkerError, } from "./worker-operator.js";
106
106
  export type { NetworkId, NetworkConfig, Worker, Job, ModelInfo, NetworkStats, ModelStat, WorkerStat, NetworkAnalytics };
package/dist/index.js CHANGED
@@ -146,7 +146,7 @@ export class LightNode {
146
146
  * (especially in registry-proxy environments like StackBlitz where lockfiles
147
147
  * may pin an older minor than the local install command suggests).
148
148
  */
149
- export const SDK_VERSION = "0.7.0";
149
+ export const SDK_VERSION = "0.7.2";
150
150
  export { NETWORKS, WORKER_REGISTRY, REGISTRY_TOPICS, aggregateModelStats, aggregateWorkerStats, networkAnalytics, modelStatsCsv, workerStatsCsv, workerJobsCsv, fromWei, computeModelId as modelId, estimateJobFee, JOB_REGISTRY_CONSUMER_ABI, consumerGatewayUrl, consumerGatewayHost,
151
151
  // v0.3 inference-submit surface (BETA - see README "Submitting inference").
152
152
  GatewayClient, GatewayHttpError, prepareSession, submitPrompt, decryptResponse, generateEcdhKeyPair, crypto,
@@ -57,12 +57,12 @@ export interface SessionPreparation {
57
57
  * Parameter names match the canonical on-chain ABI (paramsHash,
58
58
  * ephemeralPubKey, initState) verified live in the LightChain inference
59
59
  * integration guide. The slot mapping is:
60
- * - paramsHash keccak256(model tag)
61
- * - worker prepared.worker
62
- * - encWorkerKey hex(encWorker) // ECDH-wrap for the worker
63
- * - ephemeralPubKey hex(encDisputer) // ECDH-wrap for the disputer
64
- * - initState prepared.signature // dispatcher EIP-712 signature
65
- * - expiry prepared.expiry
60
+ * - paramsHash from keccak256(model tag)
61
+ * - worker from prepared.worker
62
+ * - encWorkerKey from hex(encWorker) // ECDH-wrap for the worker
63
+ * - ephemeralPubKey from hex(encDisputer) // ECDH-wrap for the disputer
64
+ * - initState from prepared.signature // dispatcher EIP-712 signature
65
+ * - expiry from prepared.expiry
66
66
  */
67
67
  createSessionArgs: {
68
68
  paramsHash: `0x${string}`;
@@ -236,7 +236,7 @@ export declare class WorkerOperator {
236
236
  * Clear one stuck (acknowledged-but-never-completed, past-deadline) job.
237
237
  * Permissionless on-chain - the worker itself may call it.
238
238
  *
239
- * ⚠️ MAINNET SLASH: this finalizes the job as TimedOut, which realizes the
239
+ * MAINNET SLASH: this finalizes the job as TimedOut, which realizes the
240
240
  * completion-timeout slash on the worker's stake (mainnet:
241
241
  * `config().slashBps.completionTimeout` = 5% of stake per job at the time of
242
242
  * writing; TESTNET has slashing disabled, so it's free there). This is the
@@ -283,8 +283,8 @@ export declare class WorkerOperator {
283
283
  /** Deregister - releases stake to the wallet. Reverts (ActiveJobsExist) if any in-flight job remains. */
284
284
  deregister(): Promise<`0x${string}`>;
285
285
  /**
286
- * The flagship rescue: clear stuck jobs release any settled completed jobs +
287
- * withdraw earnings deregister. The one flow no official tool provides.
286
+ * The flagship rescue: clear stuck jobs then release any settled completed jobs +
287
+ * withdraw earnings then deregister. The one flow no official tool provides.
288
288
  * Pass the worker's known job IDs (from the subgraph). Returns every tx done.
289
289
  */
290
290
  unstickAndDeregister(candidateJobIds: Array<bigint | number>): Promise<{
@@ -431,7 +431,7 @@ export class WorkerOperator {
431
431
  * Clear one stuck (acknowledged-but-never-completed, past-deadline) job.
432
432
  * Permissionless on-chain - the worker itself may call it.
433
433
  *
434
- * ⚠️ MAINNET SLASH: this finalizes the job as TimedOut, which realizes the
434
+ * MAINNET SLASH: this finalizes the job as TimedOut, which realizes the
435
435
  * completion-timeout slash on the worker's stake (mainnet:
436
436
  * `config().slashBps.completionTimeout` = 5% of stake per job at the time of
437
437
  * writing; TESTNET has slashing disabled, so it's free there). This is the
@@ -526,8 +526,8 @@ export class WorkerOperator {
526
526
  return this.send("deregister", this.workerReg, WORKER_REGISTRY_ABI_PARSED, "deregisterWorker", []);
527
527
  }
528
528
  /**
529
- * The flagship rescue: clear stuck jobs release any settled completed jobs +
530
- * withdraw earnings deregister. The one flow no official tool provides.
529
+ * The flagship rescue: clear stuck jobs then release any settled completed jobs +
530
+ * withdraw earnings then deregister. The one flow no official tool provides.
531
531
  * Pass the worker's known job IDs (from the subgraph). Returns every tx done.
532
532
  */
533
533
  async unstickAndDeregister(candidateJobIds) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lightnode-sdk",
3
- "version": "0.7.0",
3
+ "version": "0.7.2",
4
4
  "description": "Read-only TypeScript client for LightChain AI: workers, jobs, models, on-chain registration, and per-model network analytics. Independent, community-built (not an official LightChain package).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",