6

This question came to the forefront after reading the question about the connect extension and the usage thereof on live networks.

From the comments it is apparent that I can use the JS API to connect (since the apps UI can do it), so my question is how do I set this up? Which packages do I need in addition to the API and how do I wire it up?

1 Answer 1

7

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...)

1
  • Certainly noisy in the console, but mesmerising to watch
    – Barto
    Mar 30, 2022 at 12:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.