Skip to content

Instantly share code, notes, and snippets.

@niklasp
Created April 8, 2025 22:27
Show Gist options
  • Save niklasp/50b84a050c609987ebac3edd23e9ccb5 to your computer and use it in GitHub Desktop.
Save niklasp/50b84a050c609987ebac3edd23e9ccb5 to your computer and use it in GitHub Desktop.
// `dot` is the name we gave to `npx papi add`
import { dot } from "@polkadot-api/descriptors";
import { createClient, SS58String } from "polkadot-api";
import { getSmProvider } from "polkadot-api/sm-provider";
import { chainSpec } from "polkadot-api/chains/polkadot";
import { startFromWorker } from "polkadot-api/smoldot/from-node-worker";
import { fileURLToPath } from "url";
import { dirname, join } from "path";
import { Worker } from "worker_threads";
export async function getNonce(signer: SS58String) {
// next15 + turbopack does not support the import.meta.resolve like suggested in papi.how
// const workerPath = fileURLToPath(
// import.meta.resolve("polkadot-api/smoldot/node-worker")
// );
const currentFilePath = fileURLToPath(import.meta.url);
const currentDir = dirname(currentFilePath);
const workerPath = join(
currentDir,
"..",
"node_modules",
"polkadot-api",
"dist",
"reexports",
"smoldot_node-worker.js"
);
const worker = new Worker(workerPath);
const smoldot = startFromWorker(worker);
const chain = await smoldot.addChain({ chainSpec });
// Connect to the polkadot relay chain.
const client = createClient(getSmProvider(chain));
// With the `client`, you can get information such as subscribing to the last
// block to get the latest hash:
client.finalizedBlock$.subscribe((finalizedBlock) =>
console.log(finalizedBlock.number, finalizedBlock.hash)
);
// To interact with the chain, you need to get the `TypedApi`, which includes
// all the types for every call in that chain:
const dotApi = client.getTypedApi(dot);
// get the account info
const accountInfo = await dotApi.query.System.Account.getValue(signer);
smoldot.terminate();
return accountInfo.nonce;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment