Last active
April 10, 2025 09:37
-
-
Save niklasp/ab30b68fed1b9bffad0abedfddc52611 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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