|
| 1 | +--- |
| 2 | +title: Polkadot API Account Watcher Tutorial |
| 3 | +description: This tutorial will focus on learning how to build a decentralized command line application using the Polkadot API. |
| 4 | +--- |
| 5 | + |
| 6 | +### Project Introduction |
| 7 | + |
| 8 | +Our project will be quite simple - it will be a CLI application that runs in the terminal, which watches the relay chain for a certain `extrinsic` (a transaction). This extrinsic will be the `system.remarkWithEvent` extrinsic, meaning it is coming from the `system` pallet (module) on the Westend test network. |
| 9 | + |
| 10 | +The `system.remarkWithEvent` extrinsic allows us to send any arbitrary data on-chain, with the end result being a hash that is the address and the word "email" combined (`address+email`). We'll hash this combination and watch for remarks on a chain that are addressed to us. The `system.remarkWithEvent` extrinsic emits an event that we can use PAPI to watch the chain for. |
| 11 | + |
| 12 | +Once we receive a remark addressed to us, we will play the infamous "You've Got Mail!" sound byte. |
| 13 | + |
| 14 | +### Prerequisites |
| 15 | + |
| 16 | +You should have the following installed as a prerequisite: |
| 17 | + |
| 18 | +- `npm` (or other package manager) |
| 19 | +- `node` |
| 20 | +- `git` |
| 21 | +- [Polkadot.js Browser Extension (wallet)](https://polkadot.js.org/extension/) |
| 22 | + |
| 23 | +You will also need an account with Westend tokens. Below you can find guides for both Polkadot.js and the faucet: |
| 24 | + |
| 25 | +- [Creating Accounts on Polkadot.js](https://www.youtube.com/watch?v=DNU0p5G0Gqc) |
| 26 | +- [Westend Faucet](https://faucet.polkadot.io/westend) |
| 27 | + |
| 28 | +### Cloning the repository |
| 29 | + |
| 30 | +For this tutorial, you can choose to run the example directly by cloning the [main branch of the repository](https://github.com/CrackTheCode016/polkadot-api-example-cli/tree/main), or to use a boilerplate/template and follow the tutorial. |
| 31 | + |
| 32 | +We need to clone the template, which has everything we need to get started with the Polkadot API and Typescript. Be sure you clone the correct branch (`empty-cli`) which already provides all dependencies: |
| 33 | + |
| 34 | +```shell |
| 35 | +git clone https://github.com/CrackTheCode016/polkadot-api-example-cli --branch empty-cli |
| 36 | +``` |
| 37 | + |
| 38 | +Once cloned, run the following to ensure `npm` dependencies are installed: |
| 39 | + |
| 40 | +```shell |
| 41 | +cd polkadot-api-example-cli |
| 42 | +npm install |
| 43 | +``` |
| 44 | + |
| 45 | +### Exploring the Template (Light Clients!) |
| 46 | + |
| 47 | +When we open the repository, we should see the following code (excluding imports): |
| 48 | + |
| 49 | +```typescript |
| 50 | +async function withLightClient(): Promise<PolkadotClient> { |
| 51 | + // Start the light client |
| 52 | + const smoldot = start(); |
| 53 | + // The Westend Relay Chain |
| 54 | + const relayChain = await smoldot.addChain({ chainSpec: westEndChainSpec }) |
| 55 | + return createClient( |
| 56 | + getSmProvider(relayChain) |
| 57 | + ); |
| 58 | +} |
| 59 | + |
| 60 | +async function main() { |
| 61 | + // CLI Code goes here... |
| 62 | +} |
| 63 | + |
| 64 | +main() |
| 65 | +``` |
| 66 | + |
| 67 | +The notable function to pay attention to is the `withLightClient` function. This function uses the built in light client functionality (powered by [`smoldot`](https://github.com/smol-dot/smoldot)) to actually create a light client that syncs and interacts with Polkadot right there in our application. |
| 68 | + |
| 69 | +### Creating the CLI |
| 70 | + |
| 71 | +Next, let's create our CLI, which is to be done within the confines of the `main` function. We will include an option (`-a` / `--account`), which will be the account we will watch for our "mail": |
| 72 | + |
| 73 | +```ts |
| 74 | +const program = new Command(); |
| 75 | +console.log(chalk.white.dim(figlet.textSync("Web3 Mail Watcher"))); |
| 76 | +program.version('0.0.1').description('Web3 Mail Watcher - A simple CLI tool to watch for remarks on Polkadot network'); |
| 77 | + .option('-a, --account <account>', 'Account to watch') |
| 78 | + .parse(process.argv); |
| 79 | + |
| 80 | +// CLI Arguments from commander |
| 81 | +const options = program.opts(); |
| 82 | +``` |
| 83 | + |
| 84 | +### Watching for Remarks |
| 85 | + |
| 86 | +Next, we need to start watching the Westend network for remarks sent to our account. As was done before, all code should be within the `main` function: |
| 87 | + |
| 88 | +```typescript |
| 89 | + // We check for the --account flag, if its not provided we exit |
| 90 | + if (options.account) { |
| 91 | + console.log(chalk.black.bgRed("Watching account:"), chalk.bold.whiteBright(options.account)); |
| 92 | + // We create a light client to connect to the Polkadot (Westend) network |
| 93 | + const lightClient = await withLightClient(); |
| 94 | + // We get the typed API to interact with the network |
| 95 | + const dotApi = lightClient.getTypedApi(wnd); |
| 96 | + // We subscribe to the System.Remarked event and watch for remarks from our account |
| 97 | + dotApi.event.System.Remarked.watch().subscribe((event) => { |
| 98 | + // We look for a specific hash, indicating that its our address + an email |
| 99 | + const { sender, hash } = event.payload; |
| 100 | + // We calculate the hash of our account + email |
| 101 | + const calculatedHash = bytesToHex(blake2b(`${options.account}+email`, { dkLen: 32 })); |
| 102 | + // If the hash matches, we play a sound and log the message - You got mail! |
| 103 | + if (`0x${calculatedHash}` == hash.asHex()) { |
| 104 | + sound.play("youve-got-mail-sound.mp3") |
| 105 | + console.log(chalk.black.bgRed(`You got mail!`)); |
| 106 | + console.log(chalk.black.bgCyan("From:"), chalk.bold.whiteBright(sender.toString())); |
| 107 | + console.log(chalk.black.bgBlue("Hash:"), chalk.bold.whiteBright(hash.asHex())); |
| 108 | + } |
| 109 | + }); |
| 110 | + } else { |
| 111 | + // If the account is not provided, we exit |
| 112 | + console.error('Account is required'); |
| 113 | + return; |
| 114 | + } |
| 115 | +``` |
| 116 | + |
| 117 | +This code is doing quite a bit, so let's break it down: |
| 118 | + |
| 119 | +- First, we check for the existance of the `--account` argument, and log that we are watching that account, else we exit. We are using the `chalk` package to add color to our `console.log` statements. |
| 120 | +- Next, we create our light client. |
| 121 | +- We use a light client and the Westend chain specification (`wnd`) to access a typed API. |
| 122 | +- Once we have our API, we then begin to reactively watch the account for the event that corresponds to the remark. We analyze the payload, looking for a hash which is calculated as follows: |
| 123 | + - hash of: `account_address+email` |
| 124 | +- When an event containing this hash is identified, it then plays the "You've Got Mail!" soundbite. |
| 125 | + |
| 126 | +### Compiling and running |
| 127 | + |
| 128 | +Once we have all of our code in place, we should compile and run the repository: |
| 129 | + |
| 130 | +```shell |
| 131 | +npm start -- --account <account-address> |
| 132 | +``` |
| 133 | + |
| 134 | +Upon running, we should have the following output: |
| 135 | + |
| 136 | +```shell |
| 137 | +❯ npm start -- --account 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY |
| 138 | + |
| 139 | + |
| 140 | +> tsc && node ./dist/index.js --account 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY |
| 141 | + |
| 142 | + __ __ _ _____ __ __ _ _ __ __ _ _ |
| 143 | + \ \ / /__| |__|___ / | \/ | __ _(_) | \ \ / /_ _| |_ ___| |__ ___ _ __ |
| 144 | + \ \ /\ / / _ \ '_ \ |_ \ | |\/| |/ _` | | | \ \ /\ / / _` | __/ __| '_ \ / _ \ '__| |
| 145 | + \ V V / __/ |_) |__) | | | | | (_| | | | \ V V / (_| | || (__| | | | __/ | |
| 146 | + \_/\_/ \___|_.__/____/ |_| |_|\__,_|_|_| \_/\_/ \__,_|\__\___|_| |_|\___|_| |
| 147 | +
|
| 148 | +Watching account: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY |
| 149 | +[smoldot] Smoldot v2.0.34 |
| 150 | +[smoldot] Chain initialization complete for westend2. Name: "Westend". Genesis hash: 0xe143…423e. Chain specification starting at: 0x10cf…b908 (#23920337) |
| 151 | +``` |
| 152 | +
|
| 153 | +## Testing the CLI |
| 154 | +
|
| 155 | +Now that our application is actively watching for remark events on-chain, we can move to testing to see if it works! |
| 156 | +
|
| 157 | +> As mentioned previously, you will need a Westend account with some tokens to pay for fees. |
| 158 | +
|
| 159 | +Navigate to the [PAPI Dev Console > Extrinsics](https://dev.papi.how/extrinsics#networkId=westend&endpoint=light-client). You then want to select the `System` pallet, and the `remark_with_event` call: |
| 160 | +
|
| 161 | + |
| 162 | +
|
| 163 | +Next, we want to be sure we get the correct input for the text field. We want to be sure we are following the convention we set forth in our application: |
| 164 | +
|
| 165 | +- `address+email` |
| 166 | +
|
| 167 | +If for example, we are watching `5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY`, then the field should look like the following: |
| 168 | +
|
| 169 | + |
| 170 | +
|
| 171 | +Once this input is in place, you may click the `Submit extrinsic` button, where you can sign using the Polkadot.js browser wallet: |
| 172 | +
|
| 173 | + |
| 174 | +
|
| 175 | +Heading back to our CLI, we should soon see the following, along with the fact that "YOU'VE GOT MAIL!" (as in the sound should play): |
| 176 | +
|
| 177 | +``` |
| 178 | + __ __ _ _____ __ __ _ _ __ __ _ _ |
| 179 | + \ \ / /__| |__|___ / | \/ | __ _(_) | \ \ / /_ _| |_ ___| |__ ___ _ __ |
| 180 | + \ \ /\ / / _ \ '_ \ |_ \ | |\/| |/ _` | | | \ \ /\ / / _` | __/ __| '_ \ / _ \ '__| |
| 181 | + \ V V / __/ |_) |__) | | | | | (_| | | | \ V V / (_| | || (__| | | | __/ | |
| 182 | + \_/\_/ \___|_.__/____/ |_| |_|\__,_|_|_| \_/\_/ \__,_|\__\___|_| |_|\___|_| |
| 183 | +
|
| 184 | +Watching account: 5Cm8yiG45rqrpyV2zPLrbtr8efksrRuCXcqcB4xj8AejfcTB |
| 185 | +You've got mail! |
| 186 | +From: 5Cm8yiG45rqrpyV2zPLrbtr8efksrRuCXcqcB4xj8AejfcTB |
| 187 | +Hash: 0xb6999c9082f5b1dede08b387404c9eb4eb2deee4781415dfa7edf08b87472050 |
| 188 | +``` |
| 189 | +
|
| 190 | +## Conclusion |
| 191 | +
|
| 192 | +This application can be expanded in a number of ways, whether that is by adding a chatroom through remarks, or by using some of the rollups on Polkadot to expand the functionality. |
0 commit comments