Skip to content

openguild-labs/open-hack-dedot

Repository files navigation

OpenHack Workshop - Dedot

2024-07-18 16 17 02

Made by the collaboration between OpenGuild Labs and Dedot to introduce to participants about building decentralized applications on Polkadot.

Slide Content

Main Activity: Live Coding Session

🎯 Build a simple dapp to show & transfer balance on Polkadot testnet

1. Install SubWallet & create your wallet account

Xnapper-2024-07-18-21 55 02 Xnapper-2024-07-18-21 55 52 Xnapper-2024-07-18-21 55 33

Xnapper-2024-07-18-22 00 14 Xnapper-2024-07-18-22 01 16

2. Install Node.js

# installs nvm (Node Version Manager)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash

# download and install Node.js (you may need to restart the terminal)
nvm install 20

# verifies the right Node.js version is in the environment
node -v # should print `v20.15.1`

# verifies the right NPM version is in the environment
npm -v # should print `10.7.0`

3. Fork, clone the repo

  • Fork the repo
Xnapper-2024-07-18-22 10 30
  • Clone the repo
git clone https://github.com/{your-github-username}/openhack-dedot

E.g: https://github.com/sinzii/openhack-dedot

4. Install dependencies & start development mode

  • Install dependencies
npm i
  • Start development mode
npm run dev

5. Start building the dapp

  • Connect to wallet
  • Show connected account (name & address)
  • Initialize DedotClient to connect to the network (Westend testnet)
  • Fetch & show balance for connected account
  • Build a form to transfer balance (destination address & amount to transfer)
  • Check transaction status (in-block & finalized)
  • Check transaction result (success or not)
  • Subscribe to balance changing

6. How to interact with the network via Dedot?

6.1 Install dedot and necessary dependencies

npm i dedot

npm i -D @dedot/chaintypes @polkadot/extension-inject

6.2 Connect to SubWallet & fetch connected accounts

import { Injected, InjectedAccount, InjectedWindowProvider, InjectedWindow } from '@polkadot/extension-inject/types';

const injectedWindow = window as Window & InjectedWindow;

// Get subwallet-js injected provider to connect with SubWallet
const provider: InjectedWindowProvider = injectedWindow.injectedWeb3['subwallet-js'];

// Connect with SubWallet from the dapp
const injected: Injected = await provider.enable!('Open Hack Dapp');

// Get connected accounts
const accounts: InjectedAccount[] = await injected.accounts.get();

6.3 Initialize DedotClinet to connect to Westend network

import { DedotClient, WsProvider } from 'dedot';
import { WestendApi } from '@dedot/chaintypes';
import { WESTEND } from './networks.ts';

// initialize the client and connect to the network
const client = new DedotClient<WestendApi>(new WsProvider(WESTEND.endpoint));
await client.connect();

// OR via static factory
const client = await DedotClient.new<WestendApi>(new WsProvider(WESTEND.endpoint));

6.4 Fetching balance for an account

import { FrameSystemAccountInfo } from '@dedot/chaintypes/westend';
import { formatBalance } from './utils.ts';
import { WESTEND } from './networks.ts';

const account: InjectedAccount = accounts[0]; // get from accounts list - 6.2
const balance: FrameSystemAccountInfo = await client.query.system.account(account.address);

// Get free/transferable balance
const freeBalance = formatBalance(balance.data.free, WESTEND.decimals);

6.5 Transfer balance to destination address

import { Injected, InjectedAccount } from '@polkadot/extension-inject/types';

const client: DedotClinet = ...;

// Get injected instance & connected account - 6.2
const injected: Injected = ...; 
const account: InjectedAccount = ...;

const amount: number = 1; // how many token in DOT or WND

// Convert the amount (DOT, or WND) to Planck unit
const amountToTransfer: bigint = BigInt(amount) * BigInt(Math.pow(10, WESTEND.decimals));
const destAddress: string = '...';

await client.tx.balances
      .transferKeepAlive(destAddress, amountToTransfer)
      .signAndSend(account.address, { signer: injected.signer }, (result) => {
        console.log(result.status);

        // 'BestChainBlockIncluded': Transaction is included in the best block of the chain
        // 'Finalized': Transaction is finalized  
        if (result.status.type === 'BestChainBlockIncluded' || result.status.type === 'Finalized') {
          if (result.dispatchError) {
            // Transaction is included but has an error
            const error = `${JSON.stringify(Object.values(result.dispatchError))}`;
          } else {
            // Transaction is included and executed successfully
          }
        }
      });

6.6 Subscribe to balance changing

import { FrameSystemAccountInfo } from '@dedot/chaintypes/westend';
import { formatBalance } from './utils.ts';
import { WESTEND } from './networks.ts';

const account: InjectedAccount = accounts[0]; // get from accounts list - 6.2

// Pass in a callback to be called whenver the balance is changed/updated
const unsub = await client.query.system.account(account.address, (balance: FrameSystemAccountInfo) => {
  // Get free/transferable balance
  const freeBalance = formatBalance(balance.data.free, WESTEND.decimals);   
});

Challenge: Set your on-chain identity

Prerequisite: Complete the main activity

  • Initialize DedotClient to connect to Westend People testnet (WestendPeopleApi)
  • Build a form to enter identity information: Display name, Email, Discord handle
  • Make a transaction to set on-chain identity for connected account (via client.tx.identity.setIdentity)
  • Fetch & render your on-chain identity (via client.query.identity.identityOf)
  • If connected account is already set on-chain identity, show the identity information instead the form

A bounty of 2 DOT to claim for the first 5 participants to submit the challenge to OpenGuild

πŸ™‹ How to claim the bounty?

πŸ‘‰ Complete the challenge on your fork repository
πŸ‘‰ Star Dedot repository
πŸ‘‰ Follow OpenGuild Lab Github
πŸ‘‰ Join OpenGuild Discord
πŸ‘‰ Submit the proof-of-work (your challenge repository) to OpenGuild Discord


πŸ™Œ How to contribute to the community?

To submit a proposal, ideas, or any questions, please submit them here: OpenGuild Discussion πŸ’¬ View tickets and activities that you can contribute: Community Activities πŸ–οΈ

  • Help to grow the community: Community growth is a collective effort. By actively engaging with and inviting fellow enthusiasts to join our community, you play a crucial role in expanding our network. Encourage discussions, share valuable insights, and foster a welcoming environment for newcomers.

  • Participate in workshops and events: Be an active participant in our workshops and events. These sessions serve as valuable opportunities to learn, collaborate, and stay updated on the latest developments in the Polkadot ecosystem. Through participation, you not only enhance your knowledge but also contribute to the collaborative spirit of OpenGuild. Share your experiences, ask questions, and forge connections with like-minded individuals.

  • Propose project ideas: Your creativity and innovation are welcomed at OpenGuild. Propose project ideas that align with the goals of our community. Whether it's a new application, a tool, or a solution addressing a specific challenge in the Polkadot ecosystem, your ideas can spark exciting collaborations.

  • Contribute to our developer tools: Get involved in the ongoing development and improvement of tools that aid developers in their projects. Whether it's through code contributions, bug reports, or feature suggestions, your involvement in enhancing these tools strengthens the foundation for innovation within OpenGuild and the broader Polkadot community.