As of the latest API release this week, the ScProvider
is actually exported in the @polkadot
packages. To take advantage of it, ensure that you have at least @polkadot/api
7.14.3 installed.
(Prior to this release, you could access the provider via the @substrate/connect
package - the use is slightly different, but nicely documented by the team)
Assuming you have a latest API, you could do the following -
// important: Only ESM is currently supported for
// substrate-connect (either in Node or the browser),
// so always use `import`, not `require`
import { ApiPromise } from '@polkadot/api';
// the ScProvider import is via a sub-path
import { ScProvider } from '@polkadot/rpc-provider/substrate-connect';
// do magic :)
async function main () {
// create a provider, point it to Polkadot
const provider = new ScProvider('polkadot');
// the ScProvider doesn't connect automatically
await provider.connect();
// create an API
const api = await ApiPromise.create({ provider });
// follow new heads
api.rpc.chain.subscribeNewHeads((h) =>
console.log(`\n--- ${h.number.unwrap().toString()}\n`)
);
}
console.log
above is not quite the best solution since the ScProvider
logs all sync details, however the intent of the above is to show you how to wire it up. If you do decide to run it in Node via the commandline and just want the blockNumber outputs, run it via node ./sc.mjs | grep "^---"
. However seeing it run and sync is quite a lot of fun...
(And if you run it under Node, add main().catch(() => process.exit(-1));
at the bottom of the script - the entry point needs to be called from somewhere...)