Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
add substrate-connect tutorial
  • Loading branch information
bernardoaraujor committed Jun 14, 2022
commit 21df77a794aad489213f80d10e6d3567d56e453e
9 changes: 9 additions & 0 deletions content/config/nav.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,15 @@ tutorials:
url: /tutorials/smart-contracts/erc20-token/
- title: Troubleshoot smart contracts
url: /tutorials/smart-contracts/sc-common-issues/
- title: Run a Light Client in your browser
url: /tutorials/light-clients/
pages:
- title: Download the browser extension
url: /tutorials/light-clients/browser-extension/
- title: Connect with a well-known relay-chain
url: /tutorials/light-clients/well-known-relay/
- title: Connect with a parachain
url: /tutorials/light-clients/parachains/
reference:
title: Reference
url: /reference/
Expand Down
8 changes: 8 additions & 0 deletions content/md/en/docs/tutorials/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,11 @@ You'll learn how to:
- Store, increment, and retrieve simple values using a smart contract.
- Use maps to store and retrieve values in a smart contract.
- Build a smart contract for transferring ERC-20 tokens.

## Run a Light Client in your browser

The **Run a Light Client in your browser** tutorials show how you can bypass the need to connect to an RPC node and push decentralization even further. You'll learn how to:

- Download the browser extension
- Connect with a well-known relay-chain
- Connect with a parachain
25 changes: 25 additions & 0 deletions content/md/en/docs/tutorials/light-clients/browser-extension.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
---
title: Download the browser extension
description: Why and how to download the Substrate Connect browser extension.
---

Substrate connect provides a way to interact with [substrate](https://substrate.dev/)
based blockchains in the browser without using an RPC server. Substrate connect
uses a [smoldot](https://github.com/paritytech/smoldot/) WASM light client to
securely connect to the blockchain network without relying on specific 3rd parties.

Due to browser limitations on websockets from https pages, establishing a good
number of peers is difficult as many nodes need to be available with TLS. Substrate
Connect provides a browser extension to overcome this limitation and to keep
the chains synced in the background, which makes your apps faster.

When building an app with Substrate Connect, it will detect whether the user has
the extension and use it, or create the WASM light client in-page for them. Although optional, the extension allows for a few optimizations, namely:

- Better resource usage: multiple browser tabs can share a single connection to the same chain, instead of each opening their own connection.
- Better synchronisation speed: the browser extension automatically starts synchronising the chain when the browser starts, and holds a cache which lets it do so faster. When a browser tab wants to connect to a chain, and the browser extension is installed, it is frequent that the chain connection and synchronisation is instantaneous. Without this browser extension, synchronising a chain can take from 10 to 30 seconds.
- Better connectivity, as the extension has the possibility to connect to nodes that don’t have a TLS certificate in front of them.

The first step of the tutorial is to install the extension in either Firefox or Chrome:
- Chrome: https://chrome.google.com/webstore/detail/substrate-connect-extensi/khccbhhbocaaklceanjginbdheafklai
- Firefox: https://addons.mozilla.org/en-US/firefox/addon/substrate-connect/
10 changes: 10 additions & 0 deletions content/md/en/docs/tutorials/light-clients/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
title: Run a Light Client in your browser
description: Introduces tutorials for running in-browser light clients via Substrate Connect.
---

The **Run a Light Client in your browser** tutorials show how you can bypass the need to connect to an RPC node and push decentralization even further. You'll learn how to:

- [Download the browser extension](/tutorials/light-clients/browser-extension/) describes why and how to download the Substrate Connect browser extension.
- [Connect with a well-known relay-chain](/tutorials/light-clients/well-known-relay/) describes how to connect to a well-known relay chain.
- [Connect with a parachain](/tutorials/light-clients/parachains/) describes how to connect with a parachain.
72 changes: 72 additions & 0 deletions content/md/en/docs/tutorials/light-clients/parachains.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
---
title: Connect with a parachain
description: How to connect with a parachain via Substrate Connect
---

## Before you begin

Before you begin, make sure you have [installed the Browser Extension](/tutorials/light-clients/browser-extension/), and that you have learned how to [connect to a well-known relay-chain](/tutorials/light-client/well-known-relay/).

## Tutorial objectives

By completing this tutorial, you will accomplish the following objectives:

- Learn how to load a chainspec into the light client.

- Create a basic webapp that connects to a parachain from the browser.

## Connect to Statemint

This tutorial is very similar to the previous, where we [connected to a well-known relay-chain](/tutorials/light-client/well-known-relay/).

But instead of using a chainspec that's embedded into the Substrate Connect library, we are going to explicitly provide it to our code.

We want to connect to Statemint, a common-goods parachain connected to Polkadot. You can download its chainspec from the [cumulus repository](https://github.com/paritytech/cumulus/blob/master/parachains/chain-specs/statemint.json).

Go ahead and save it into the same directory from the previous tutorial (`empty-webapp`). Then, edit the contents of `index.ts` so it looks like the following:
```typescript
import {
ScProvider,
WellKnownChain,
} from "@polkadot/rpc-provider/substrate-connect";
import { ApiPromise } from "@polkadot/api";
import jsonParachainSpec from "./statemint.json";

window.onload = () => {
void (async () => {
try {
const relayProvider = new ScProvider(WellKnownChain.polkadot);
const parachainSpec = JSON.stringify(jsonParachainSpec);
const provider = new ScProvider(parachainSpec, relayProvider);

await provider.connect();
const api = await ApiPromise.create({ provider });
await api.rpc.chain.subscribeNewHeads(
(lastHeader: { number: unknown; hash: unknown }) => {
console.log(
`New block #${lastHeader.number} has hash ${lastHeader.hash}`
);
}
);
} catch (error) {
console.error(<Error>error);
}
})();
};
```

This code is very similar to the previous one. The main differences are
- we are loading `statemint.json` into a `parachainSpec` object.
- we are creating a `relayProvider` object for the Relay chain, and using it in the construction of the `provider` object for the Parachain, along with `parachainSpec`.

In the directory of the webapp, run the following again:

```bash
yarn
yarn dev
```

That should open a browser on `http://localhost:3001/`. Open the JavaScript console from your browser and observe the output. You should see smoldot (the actual wasm light client) being initialised, followed by the hashes of the incoming blocks of Statemint.

From here onwards, the usage is very similar to what would have been usually done via PolkadotJS. All you have to do is follow the [official documentation](https://polkadot.js.org/docs/) and interact with the chain.

101 changes: 101 additions & 0 deletions content/md/en/docs/tutorials/light-clients/well-known-relay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
---
title: Connect with a well-known relay-chain
description: How to connect to a well-known relay chain via Substrate Connect
---

## Before you begin

Before you begin, make sure you have [installed the Browser Extension](/tutorials/light-clients/browser-extension/).

## Tutorial objectives

By completing this tutorial, you will accomplish the following objectives:

- Learn why a chainspec is necessary to start a light client.

- Create a basic webapp that loads a light client into the browser.

- Learn how to use an embedded chainspec on Substrate Connect for a well-known relay-chain.

## Basics of Chainspec

In order to connect to some network, a light client needs to be provided with a [chainspec](https://docs.substrate.io/v3/runtime/chain-specs/). It dictates which network the light client will connect to, which entities it will initially communicate with, and what consensus-critical state it must have at genesis.

Connecting with the well-known relay-chains is very straightforward, because Substrate Connect already comes with their chainspecs ready for usage out-of-the-box, so you don’t have to worry about them.

Those well-known relay-chains are:
- Polkadot
- Kusama
- Rococo
- Westend

If you eventually want to connect to a different relay-chain, then you will need to handle some chainspec file. But that will be explained later on in this tutorial, for now, let’s focus on the well-known chains!

## Connect to Polkadot

First, start by cloning a template for an empty webapp:
```bash
git clone https://github.com/bernardoaraujor/empty-webapp
cd empty-webapp
```

After that, install the necessary dependencies:
```bash
yarn add @polkadot/rpc-provider
yarn add @polkadot/api
```

You should notice that `index.ts` is empty. Go ahead and paste the following contents inside of it:
```typescript
import {
ScProvider,
WellKnownChain,
} from "@polkadot/rpc-provider/substrate-connect";
import { ApiPromise } from "@polkadot/api";

window.onload = () => {
void (async () => {
try {
const provider = new ScProvider(WellKnownChain.polkadot);

await provider.connect();
const api = await ApiPromise.create({ provider });
await api.rpc.chain.subscribeNewHeads(
(lastHeader: { number: unknown; hash: unknown }) => {
console.log(
`New block #${lastHeader.number} has hash ${lastHeader.hash}`
);
}
);
} catch (error) {
console.error(<Error>error);
}
})();
};

```

If you’re familiar with PolkadotJS, you might have noticed this code is very similar to the traditional approach taken there. The only difference is that instead of using a `WsProvider`, we are now using a `ScProvider`.

Also, notice that instead of a WebSocket URL, which would have been the address of a client, we used `WellKnownChain.polkadot`, which represents the chainspec for the Polkadot network.

You can provide any of these network names:
- `polkadot`
- `ksmcc3`
- `westend2`
- `rococo_v2_2`

Note that these are the "real" names of the chains rather than the names they are more commonly known as (such as Kusama or Rococo). For example, "ksmcc3" is the name of Kusama. This is important for chains which have been hard forked. For example, “rococo_v2" and "rococo_v2_2" are two different chains. Hopefully, polkadot will never go through a hard fork, but all the other three are subject to change in the future. You can keep track of the current chainspec files provided by Substrate Connect [here](https://bit.ly/3NQl48N).

Now it’s time to see the code in action. In the directory of the webapp, run the following:

```bash
yarn
yarn dev
```

That should open a browser on `http://localhost:3001/`. Open the JavaScript console from your browser and observe the output. You should see smoldot (the actual wasm light client) being initialised, followed by the hashes of the incoming blocks of Polkadot.

Tip: different browsers running on different Operating Systems will have different shortcuts to display the JavaScript console. [Here](https://webmasters.stackexchange.com/a/77337) is a convenient cheat sheet.

To recap what we achieved so far: we fetched block hashes without using any URL for a RPC node, which is arguably a centralised entry point to the network. And we could have done much more, not only block hashes! The point here is that after `WsProvider` is replaced with `ScProvider`, the code can be written as if it was any other app based on PolkadotJS. From here onwards, you can just follow [PolkadotJS docs](https://polkadot.js.org/docs/) and do much more.