Giter Site home page Giter Site logo

substra-hooks's Introduction

Deprecated

SubstraHooks Core

No Maintenance Intended

SubstraHooks is a collection of useful react hooks that work with polkadot.js on Substrate blockchains

inspired by useDApp

Usage

Add it to your project:

yarn add @substra-hooks/core @polkadot/api @polkadot/extension-dapp

Use it in your React app:

import React from 'react'
import { SubstraHooksProvider } from '@substra-hooks/core';

export enum NETWORKS {
    kusama = 'kusama',
    statemine = 'statemine',
}

const apiProviderConfig = {
    [NETWORKS.kusama]: {
        id: NETWORKS.kusama,
        wsProviderUrl: 'wss://kusama-rpc.polkadot.io',
    },
    [NETWORKS.statemine]: {
        id: NETWORKS.statemine,
        wsProviderUrl: 'wss://statemine-rpc.polkadot.io',
    },
}

// Wrap everything in <SubstraHooksProvider />
export default () => (
    <SubstraHooksProvider apiProviderConfig={apiProviderConfig} defaultApiProviderId={NETWORKS.kusama}>
        <App />
    </SubstraHooksProvider>
)
// App.tsx
import React from 'react'
import { useAccountBalance, useSystemProperties, useAssetBalance } from '@substra-hooks/core'

const App = () => {
    const { accounts, w3enable, w3Enabled } = usePolkadotExtension();
    const balancePayload = useAccountBalance(accounts?.[0]?.address || '');
    const assetPayload = useAssetBalance(accounts?.[0]?.address || '', 8, NETWORKS.statemine);
    const systemProperties = useSystemProperties()

    console.log('systemProperties', systemProperties)

    useEffect(() => {
        if (!w3Enabled) {
            w3enable();
        }
    }, [w3Enabled])

    console.log('accounts', accounts)
    console.log('balanceFormatted', accounts?.[5]?.address || '', balanceFormatted);
    console.log('assetPayload', assetPayload);

    return (
        <>
          <div>Balance: {balancePayload?.balance.formatted}</div>
          <div>Locked Balance: {balancePayload && balancePayload?.locked?.formatted}</div>
          <div>Reserved Balance: {balancePayload?.reserved?.formatted}</div>
          <div>Total Balance: {balancePayload?.total?.formatted}</div>
        </>
    )
}

If your app is using SSR (i.e. next.js) then you need to dynamically import Provider with no SSR, create your own local Provider first

import { ReactNode } from 'react';
import { SubstraHooksProvider } from '@substra-hooks/core';

interface ISubstraHooksProviderProps {
    apiProviderConfig: ApiProviderConfig;
    children: ReactNode;
}


const SubstraHooksProviderSSR = ({ apiProviderConfig, children }: ISubstraHooksProviderProps) => {
    return (
        <SubstraHooksProvider
            apiProviderConfig={apiProviderConfig}
            defaultApiProviderId={NETWORKS.kusama}>
            {children}
        </SubstraHooksProvider>
    );
};

export default SubstraHooksProviderSSR;
const SubstraHooksProviderSSR = dynamic(() => import('./substra-hook-provider'), {
  ssr: false,
});

const MyApp = ({ Component, pageProps }: AppProps) => {

  return (
      <SubstraHooksProviderSSR wsProviderUrl="wss://kusama-rpc.polkadot.io">
          <Component {...pageProps} />
      </SubstraHooksProviderSSR>
  );
};

export default MyApp;

API

Providers

SubstraHooksProvider

Main Provider that includes ExtensionProvider

ExtensionProvider

Provider that mainly deals with polkadot browser extension

Hooks

useApiProvider

Returns polkadot.js ApiPromise. Returns default ApiPromise as defined by defaultApiProviderId on SubstraHooksProvider, additional argument can be passed to return different ApiPromise from default one

const polkadotStatemineApi = useApiProvider('statemine');

useSystemProperties

Returns parsed results of polkadotApi.rpc.system.properties API in following format.

{
    tokenDecimals: number;
    tokenSymbol: string;
    ss58Format: number;
}

Returns system properties fetched from the chain connected by your default api provider, additional argument can be passed to return different system properties from different node

const systemProperties = useSystemProperties()

useAccountBalance

Returns token balance of given address from the default node.

const { balanceFormatted, balanceRaw } = useAccountBalance(userEncodedAddress);

useAssetBalance

Returns balance of specified asset id for given address from the default node.

const { balanceFormatted, balanceRaw } = useAssetBalance(
    userEncodedAddress,
    ASSET_ID,
    'statemine',
);

useEncodedAddress

Returns substrate address in a format of ss58Format of your default chain node

const ownerAddressEncoded = useEncodedAddress(owner);

usePolkadotExtension

import {useEffect} from "react";
...
const { w3Enabled, w3enable, accounts } = usePolkadotExtension();

const initialise = () => {
    if (!w3Enabled) {
        w3enable();
    }
};

useEffect(() => {
    if (!w3Enabled) {
        initialise();
    }
}, [w3Enabled])

console.log(accounts);

substra-hooks's People

Contributors

2075 avatar darknebula0 avatar denvradiy avatar evilshoot avatar matt-paul avatar yornaath avatar yurigii avatar yuripetusko avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

substra-hooks's Issues

expand extension hooks

For the extension hook, it would be great if extension hook would return methods to set and get your active account. This would save selected account object to reducer/context and then be able to return selected account.

Additionally maybe it's good idea to be able to pass callback or your own storage provider for persistent storage so address stays on refresh (maybe use zustand for this)

Remove api-augment

This is fine for Kusama / Polkadot chains but custom chains implement own type-gen and augmentation which makes substra-hooks incompatible.

Proposal to remove this line from bundled core:

import "@polkadot/api-augment";

So it is up to the upstream clients to augment types.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.