Skip to content

Instantly share code, notes, and snippets.

@niklasp
Last active April 10, 2025 09:37
Show Gist options
  • Save niklasp/ab30b68fed1b9bffad0abedfddc52611 to your computer and use it in GitHub Desktop.
Save niklasp/ab30b68fed1b9bffad0abedfddc52611 to your computer and use it in GitHub Desktop.
import { startFromWorker } from "polkadot-api/smoldot/from-node-worker";
import { Worker } from "worker_threads";
import { fileURLToPath } from "url";
import { dirname, join } from "path";
import type { Client } from "polkadot-api/smoldot";
// Singleton worker instance and nonce cache
let worker: Worker | null = null;
let smoldot: Client | null = null;
const nonceCache: Map<string, number> = new Map();
// Initialize worker once
async function initializeWorker() {
if (worker && smoldot) return { worker, smoldot };
const currentFilePath = fileURLToPath(import.meta.url);
const currentDir = dirname(currentFilePath);
const workerPath = join(
currentDir,
"..",
"node_modules",
"polkadot-api",
"dist",
"reexports",
"smoldot_node-worker.js"
);
worker = new Worker(workerPath);
smoldot = startFromWorker(worker);
return { worker, smoldot };
}
// Cleanup function to be called on server shutdown
export async function cleanupWorker() {
if (smoldot) {
await smoldot.terminate();
smoldot = null;
}
if (worker) {
worker.terminate();
worker = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment