Tiến Nguyễn Khắc
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
**NOTE**: Polkassembly doesn't do code highlighting, so a much easier to read version can be found [here](https://hackmd.io/wUbQpWBqTFaPD-I6D_O6Mw?view) instead. # Proposal for `reactive-dot`: A reactive library for building Substrate front-end ## Overview I'm [Tien](https://github.com/tien) and was a lead front-end developer working in the Polkadot space for the past 1.5 years. Now I'm going independent and I'd like to solve some developer experience issues I encountered along the way. Prior to my involvement with Polkadot, I've worked on various projects within other ecosystems, namely Ethereum & Cosmos. This library came about based on my experience building out front-ends with Polkadot.js, and comparing it with the developer experience available in Ethereum, realizing the same wasn't available for Polkadot. This proposal outlines the creation of `reactive-dot`, a comprehensive React library designed to simplify and streamline the integration of Polkadot network functionalities into React applications. Inspired by the popular Wagmi library for Ethereum, `reactive-dot` aims to provide developers with an easy-to-use, modular, and flexible toolkit for interacting with the Polkadot ecosystem. ## Objectives 1. **Simplify Development**: Provide a set of intuitive React hooks to facilitate Polkadot network interactions, making it accessible for developers of all skill levels. 2. **Enhance Developer Experience**: Reduce the boilerplate code and complexity involved in integrating Polkadot, allowing developers to focus on building robust applications. 3. **Promote Adoption**: Encourage the adoption of Polkadot by lowering the entry barrier for developers through improved tooling. ## Key features for the first version ### Multichain support Easy chain selection via React context. ```tsx const Root = () => ( <ReDotProvider config={{ providers: { "0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3": new WsProvider("wss://apps-rpc.polkadot.io"), "0xb0a8d493285c2df73290dfb7e61f870f17b41801197a149ca93654499ea3dafe": new WsProvider("wss://kusama-rpc.polkadot.io"), }, }} > <ReDotChainProvider genesisHash="0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"> <App /> </ReDotChainProvider> <ReDotChainProvider genesisHash="0xb0a8d493285c2df73290dfb7e61f870f17b41801197a149ca93654499ea3dafe"> <App /> </ReDotChainProvider> </ReDotProvider> ); ``` Or via options override ```ts const account = useQueryStorage("system", "account", [accountAddress], { genesisHash: "0xb0a8d493285c2df73290dfb7e61f870f17b41801197a149ca93654499ea3dafe", }); ``` ### Reading of storage Access and read data stored in the Substrate-based storage directly from your React components. ```ts // Reading single value // this value is live from chain and will be updated automatically const totalIssuance = useQueryStorage("balances", "totalIssuance", []); console.log("Total issuance:", totalIssuance.toHuman()); // Reading multiple values const poolMetadatum = useQueryStorage( "nominationPools", "metadata", [0, 1, 2, 3], { multi: true, }, ); for (const poolMetadata of poolMetadatum) { console.log("Pool name:", poolMetadata.toUtf8()); } ``` ### React suspense compatibility React suspense are first class citizen for async & error handling. ```tsx const CurrentBlock = () => { const currentBlock = useQueryStorage("system", "number", []); return <p>Current block: {currentBlock}</p>; }; const App = () => ( <ErrorBoundary fallback="Error fetching block"> <Suspense fallback="Loading block..."> <CurrentBlock /> </Suspense> </ErrorBoundary> ); ``` ### Caching, deduplication & persistent Multiple reads of the same value throughout the application will only be fetched once, cached, and is kept up to date everywhere. ```tsx const myAccount = "SOME_ACCOUNT_ADDRESS"; const FreeBalance = () => { // First invocation will initiate subscription via web socket const account = useQueryStorage("system", "account", [myAccount]); return <p>Free balance: {account.data.free.toHuman()}</p>; }; const FrozenBalance = () => { // Second invocation will only wait for and reuse value coming from the first invocation const account = useQueryStorage("system", "account", [myAccount]); return <p>Frozen balance: {account.data.frozen.toHuman()}</p>; }; const ReservedBalance = () => { // Third invocation will also only wait for and reuse value coming from the first invocation const account = useQueryStorage("system", "account", [myAccount]); return <p>Reserved balance: {account.data.reserved.toHuman()}</p>; }; const App = () => ( <div> {/* `useQueryStorage("system", "account", [myAccount])` will only be executed once & is kept up to date for all 3 components */} <FreeBalance /> <FrozenBalance /> <ReservedBalance /> </div> ); ``` ### Full TypeScript support with autocompletion The library aim to provides strong TypeScript definition with 1-1 mapping to Substrate pallets definition. #### Autocompletion ![image](https://hackmd.io/_uploads/BkVFkEe4A.png) ![image](https://hackmd.io/_uploads/rkIo14lNC.png) ![image](https://hackmd.io/_uploads/SyeXA1VeNR.png) #### Strong return type definition ![image](https://hackmd.io/_uploads/ByfE1Vl4R.png) ![image](https://hackmd.io/_uploads/HkXWJNe4A.png) ### And more The scope of this library can expand significantly based on community interest. Potential future features include: 1. Wallet/account connections management 2. Submitting transactions 3. Utility hooks outside of reading storage 4. Auto conversion of SCALE type encoding to native JS types (i.e. `U32` -> `Number`, `U256` -> `BigInt`, etc) 5. Multi-adapter support: Polkadot.js, Polkadot-API, DeDot, etc 6. Multi-framework support: React, Vue, Angular, etc 7. Etc ## Demo A working proof of concept showcasing the library can be found [here](https://stackblitz.com/edit/vitejs-vite-lyatc5?file=src%2FApp.tsx). ## Code comparison The below code snippets perform the following tasks: - Initiate connection to the chain - Reading the chain current block and the account balance - Display loading and error (if there's any) state - Display the final result after finished loading all values with no error ### With Polkadot.js ```tsx import { ApiPromise, WsProvider } from "@polkadot/api"; import type { u32 } from "@polkadot/types-codec"; import type { FrameSystemAccountInfo } from "@polkadot/types/lookup"; const MY_ACCOUNT = "SOME_ADDRESS"; const LOADING = new Symbol(); const App = () => { const [api, setApi] = useState<ApiPromise | LOADING | Error>(); const [currentBlock, setCurrentBlock] = useState<u32 | LOADING | Error>(); const [account, setAccount] = useState< FrameSystemAccountInfo | LOADING | Error >(); useEffect(() => { (async () => { setApi(LOADING); try { const api = await ApiPromise.create({ provider: new WsProvider("wss://my.chain"), }); setApi(api); } catch (error) { setApi(new Error("Unable to initialize ApiPromise", { cause: error })); } })(); }, []); useEffect(() => { if (api === LOADING || api instanceof Error) { return; } const unsubscribePromise = (async () => { setCurrentBlock(LOADING); try { return api.query.system.number((currentBlock) => setCurrentBlock(currentBlock), ); } catch (error) { setCurrentBlock( new Error("Unable to get current block", { cause: error }), ); } })(); return () => { unsubscribePromise.then((unsubscribe) => { if (unsubscribe === undefined) { return; } unsubscribe(); }); }; }, [api]); useEffect(() => { if (api === LOADING || api instanceof Error) { return; } const unsubscribePromise = (async () => { setAccount(LOADING); try { return api.query.system.account(MY_ACCOUNT, (account) => setAccount(account), ); } catch (error) { setAccount(new Error("Unable to get account", { cause: error })); } })(); return () => { unsubscribePromise.then((unsubscribe) => { if (unsubscribe === undefined) { return; } unsubscribe(); }); }; }, [api]); if (api === LOADING || currentBlock === LOADING || account === LOADING) { return <p>Loading...</p>; } if ( api instanceof Error || currentBlock instanceof Error || account instanceof Error ) { return <p>Sorry, something went wrong.</p>; } return ( <p> Your account free balance is: {account.data.free.toHuman()} at block{" "} {currentBlock.toNumber()} </p> ); }; ``` ### With `reactive-dot` ```tsx const MY_ACCOUNT = "SOME_ADDRESS"; const _Balance = () => { const currentBlock = useQueryStorage("system", "number", []); const account = useQueryStorage("system", "account", [MY_ACCOUNT]); return ( <p> Your account free balance is: {account.data.free.toHuman()} at block{" "} {currentBlock.toNumber()} </p> ); }; const Balance = () => ( <ErrorBoundary fallback={<p>Sorry, something went wrong.</p>}> <Suspense fallback={<p>Loading...</p>}> <_Balance /> </Suspense> </ErrorBoundary> ); const App = () => ( <ReDotProvider config={{ providers: { [SOME_GENESIS_HASH]: new WsProvider("wss://my.chain"), }, }} > <ReDotChainProvider genesisHash={SOME_GENESIS_HASH}> <Balance /> </ReDotChainProvider> </ReDotProvider> ); ``` ## Timeline & Budget Requested amount: 6,000 DOT Estimated length of work: 8 weeks/~320 hours Estimated rate: 18.75 DOT or ~139.20 USD per hour The requested amount also covers the retrospective work from numerous experiments and research efforts that validated this idea and led to the development of the initial working proof of concept. ### Planned schedule 1. Week 1: Research & planning 2. Week 2-4: Core development 3. Week 5-6: Writing unit & integration tests 4. Week 7: Documentation, walkthrough & website 5. Week 8: Official version 1 6. Ongoing: Feedback & iteration Of which version 1 will include React support for the capabilities outlined in the [section](#key-features-for-the-first-version) before, excluding possible [future goals](#and-more) ## Conclusion `reactive-dot` aims to revolutionize the way developers interact with the Polkadot network by providing a robust, user-friendly, and feature-rich React library. By simplifying the development process and fostering a vibrant community, `reactive-dot` will play a pivotal role in promoting the adoption and growth of the Polkadot ecosystem. We seek the support and funding from the treasury to bring this ambitious project to life.

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully