Dapp-core-components - A library that holds the core logic of a dapp on the Elrond Network with an example to get started easily

Last update: Feb 6, 2022

dapp-core-components

A library that holds the core logic of a dapp on the Elrond Network with an example to get started easily

NPM JavaScript Style Guide

If you need only the dapp-core basic logic, without the additional UI, consider using the stripped down version at @elrondnetwork/dapp-core

Installation

The library can be installed via npm or yarn.

npm install @elrondnetwork/dapp-core-components

or

yarn add @elrondnetwork/dapp-core-components

Usage

dapp-core-components aims to abstract and simplify the process of interacting with users' wallets and with the Elrond Network, allowing developers to easily get started with a new application or integrate dapp-core-components into an existing application.

This library covers two main areas: User Identity and Transactions. The API for interacting with library's logic is exposed via hooks and methods that can be called for logging in the user, getting the status of the user or sending transactions.

However, to simplify usage even further, the library also comes with a default UI that already uses these hooks and methods under the hood. These UI elements can be easily customized with custom css classes.

The default UI is exposed via the DappUI object.

import { DappUI } from "@elrondnetwork/dapp-core-components";

More on this below.

Prerequisites

There are a couple of requirements that need to be met for the application to work properly.

React

React

This library was built for applications that use React, it might not be suitable for usage with other libraries or frameworks.

DappProvider

DappProvider

You need to wrap your application with the DappProvider component, which is exported by the library, as we need to create a global Context to be able to manipulate the data.

  • import the Provider:

import { DappProvider } from "@elrondnetwork/dapp-core-components";

  • Wrap your application with this Provider.

As you might have noticed, the DappProvider accepts a networkConfig object with a couple of keys. This allows using different APIs and different connection providers.

  • walletConnectBridge (optional) is a string that is used to establish the connection to walletConnect library.
  • walletConnectDeepLink (optional) is a string that will create a deeplink for an application that is used on a mobile phone, instead of generating the login QR code.
  • network is a required configuration file that contains the following information about the environment of the application:
{
  id: string;
  egldLabel: string;
  name: string;
  walletAddress: string;
  apiAddress: string;
  gatewayAddress: string;
  explorerAddress: string;
}
UI Wrappers

UI Wrappers

The library exposes a couple of Components that are connected to the redux store and are used to display various elements when something happens inside the app:

  • TransactionsToastList will display new transactions in nice toasts at the bottom of the screen. This component is fully customizable.
">
  import {DappUI} from "@elrondnetwork/dapp-core-components";

  
    
    
     
    
     
  
    

  • SignTransactionsModals will show a modal when a new transaction is submitted, prompting the user to verify and sign it.
">
  import {DappUI} from "@elrondnetwork/dapp-core-components";


    
  
     
  
     

    

NotificationModal Will show a modal to the user with various warnings and errors.

">
  import {DappUI} from "@elrondnetwork/dapp-core-components";


    
  
     
  
     

    

  • DappCoreUIWrapper is a wrapper that needs to be wrapped around the whole tree to namespace the styles inside dapp-core-components Components.
">
  import {DappCoreUIWrapper} from "@elrondnetwork/dapp-core-components";


    
  
     
  
      
  
     

    

User Identity

dapp-core-components makes logging in and persisting user's session easy and hassle-free. The library exposes two ways in which a user can be logged in:

Login UI

Login UI

There are a couple of very handy React components that can be used to login the user and protect certain routes if the user is not logged in.

Under the DappUI object mentioned above, you can find 4 buttons (one for each provider) which abstract away all the logic of loggin in the user and render the default UI. These buttons can be easily customized with a custom css class. The exported buttons are:

  • DappUI.ExtensionLoginButton
  • DappUI.WalletConnectLoginButton
  • DappUI.LedgerLoginButton
  • DappUI.WebWalletLoginButton

example:

">

   

They can also be used with children

<>

Login text

<>

    
     
  <>
    
     
    
     

Login text

<>

Also, for a quicker setup, the DappUI object exports an DappUI.UnlockPage component, which contains all 4 buttons.

Another handly component is DappUI.AuthenticatedRoutesWrapper, which can be used to protect certain routes and redirect the user to login page if the user is not authenticated.

Import from dapp-core-components:

import { AuthenticatedRoutesWrapper} from "@elrondnetwork/dapp-core-components";

Use with routes:


    
     
          {appContent}
        
    

routes should be an array with objects with a signature similar to this:

{
    path: "/dashboard",
    title: "Dashboard",
    component: Dashboard,
    authenticatedRoute: true,
  }

The important parts that makes this component work are the flag authenticatedRoute: true and the key path, which means that this route should be accessible only to authenticated users.

Login hooks

Login hooks

If needed, the Login UI can be bypassed using a custom UI, and opt in for the login hooks, which expose a trigger function and the login data, ready to be rendered.

These hooks are exposed by the loginServices object, which can be imported from dapp-core-components:

import {loginServices} from @elrondnetwork/dapp-core-components

There are 4 available hooks:

  • useExtensionLogin
  • useWalletConnectLogin
  • useLedgerLogin
  • useWebWalletLogin

All hooks have the same respose signature:

return type is as follows:

const [triggerFunction, genericLoginReturnType, customLoginReturnType] = useLoginHook({
    callbackRoute,
    logoutRoute
  });
  • initiateLogin is a function that needs to be called for the login flow to be initiated;
  • genericLoginReturnType is an object that is exactly the same for all hooks:
{
  error: string,
  isFailed: boolean,
  isLoading: boolean,
  isLoggedIn: boolean
}
  • customLoginReturnType is an object that is custom for each hook and returns specific data for that login:

    • null for useExtensionLogin;

    • null for useWebWalletConnect;

    • { uriDeepLink: string, qrCodeSvg: svgElement } for useWalletConnectLogin;

{
  accounts: string[];
  showAddressList: boolean;
  startIndex: number;
  selectedAddress: SelectedAddress | null;
  onGoToPrevPage: () => void;
  onGoToNextPage: () => void;
  onSelectAddress: (address: SelectedAddress | null) => void;
  onConfirmSelectedAddress: () => void;
}

for useLedgerLogin;

Reading User State

Reading User State

Once logged in, the user's session is persisted and can be read and deleted via a couple of handy functions.

For logging out, the library exposes a simple function called logout, which can be called to clear the user data.

There are 2 ways of reading the user current state: hooks (to be used inside components and for reacting to changes in the data) and simple functions (for reading data outside of React components or inside handlers).

  • hooks: useGetLoginInfo, useGetAccountInfo, useGetNetworkConfig;
  • functions: getAccount, getAccountBalance, getAccountShard, getAddress, getIsLoggedIn;

Transactions

The dapp-core-components library exposes a straight-forward way of sending transactions and tracking their status, with a couple of handy UI components;

Sending Transactions

Sending Transactions

The API for sending transactions is a function called sendTransactions:

import { sendTransactions } from "@elrondnetwork/dapp-core-components";

It can be used to send a transaction with minimum information:

const { sessionId, error } = await sendTransactions({
    transactions: [
        {
          value: '1000000000000000000',
          data: 'ping',
          receiver: contractAddress
        },
      ],
    });

It returns a Promise that will be fulfilled with {error?: string; sessionId: string | null;}

sessionId is the transaction's batch id which can be used to track a transaction's status and react to it.

Tracking a transaction

Tracking a transaction

The library exposes a hook called useTrackTransactionStatus under the object transactionServices.

import {transactionServices} from @elrondnetwork/dapp-core-components;

const transactionStatus = transactionServices.useTrackTransactionStatus({
  transactionId: sessionId,
  onSuccess,
  onFailed,
  onCancelled
});

transactionStatus has the following information about the transaction:

{
  isPending,
  isSuccessful,
  isFailed,
  isCancelled,
  errorMessage,
  status,
  transactions
}

It's safe to pass in null as a sessionId, so if the transaction wasn't yet sent, the hook will just return an empty object.

Also, one can use the hook useGetPendingTransactions to get a list of all pending transactions.

Transaction Toasts UI

Transaction Toasts UI

dapp-core-components also exposes a toast component for tracking transactions that uses the above mentioned hooks and displays toasts with transactions statuses.

The toasts list is exposed via DappUI.TransactionsToastList component and can be used just by rendering it inside the application.


    
  
     
  
     

    

Important: This has to be inside the children.

Roadmap

See the open issues for a list of proposed features (and known issues).

Contributing

Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are greatly appreciated.

One can contribute by creating pull requests, or by opening issues for discovered bugs or desired features.

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Developers

The Elrond Team.

License

GPL-3.0-or-later

GitHub

https://github.com/ElrondNetwork/dapp-core-components
You might also like...

Basic Dapp showing how a React Dapp can connect to Cronos using MetaMask and Crypto.com Defi Wallet

cronos-dapp-basic Basic Dapp showing how a React Dapp can connect to Cronos using MetaMask and Crypto.com Defi Wallet You need to have node version 14

Dec 27, 2021

Dinos-nft-minting-dapp - A nice and easy way for linking an existing NFT smart contract to this minting dapp

Dinos-nft-minting-dapp - A nice and easy way for linking an existing NFT smart contract to this minting dapp

Welcome to HashLips 👄 All the code in these repos was created and explained by

Jan 6, 2022

Create-dapp-solana-nextjs - Scaffolding for a Solana dapp using TS, Next.JS, Tailwinds CSS, and Daisy UI

Create Solana Dapp with Next.JS Want to start develop with Solana fetching NFTs

Jun 21, 2022

React Ethereum Dapp Example

React Ethereum Dapp Example

React Ethereum Dapp Example Includes an example Ethereum token implementation and UI! About This is a starter boilerplate Ethereum dapp I've put toget

Jan 2, 2022

Erb-mksnapshot-example - An example on how to create an Mksnapshot for Electron

Electron React Boilerplate uses Electron, React, React Router, Webpack and React

Jan 9, 2022

Nextjs-chakra-navigation-example - NextJS with chakra-ui responsive nav example

nextjs-chakra-navigation-example I looked at how to implement navigation in next

Jan 23, 2022

A Web3 Social Network Boilerplate Using React.js

A Web3 Social Network Boilerplate Using React.js

web3-social-network-boilerplate This Project is a fork of Ethereum Boilerplate and demostrates how you can build your own Web3 Ethereum Social Network

Jun 19, 2022

Simple React Social Network, built with React,Node,Express,MongoDB and Tailwind

Simple React Social Network, built with React,Node,Express,MongoDB and Tailwind

Full stack react social network application A mini social network application built with React,Typescript, Redux, Node, Express, MongoDB, and Tailwind

May 25, 2022

A cloud and react based network

A cloud and react based network

Around Description Around is a full-stack web application for people to share photos/videos and publish posts. The frontend is built with React, and t

Jan 20, 2022
Comments
  • 1. TypeError: Cannot redefine property: AuthenticatedRoutesWrapper

    I just created a new NextJS project with the new Dapp-core-components, imported the DappProvider from the Dapp-core-components, and I have this error. Capture d’écran 2022-01-21 à 09 45 02

    Reviewed by Neewd at 2022-01-21 08:49
Get started with developing emails with React Components

mjml-react-starter Get started with developing emails with React Components. This starter includes dev and build scripts to get you started with 1 com

May 30, 2022
Psn-social-network-public-source - PSN Social Network App Using React and Spring Boot

PSN SOCIAL NETWORK This app is for educational purpose only. PSN Social Network

Jun 15, 2022
Get started with React, Redux, and React-Router.

Deprecation Warning This project was started at the advent of the Redux ecosystem, and was intended to help users get up and running quickly. Since th

Jun 18, 2022
Get started with Chrome extensions development using webpack, Typescript, Sass, and more
Get started with Chrome extensions development using webpack, Typescript, Sass, and more

Get started with Chrome extensions development using webpack, Typescript, Sass,

Jun 18, 2022
A starter pack to get started with building dapps on Celo
A starter pack to get started with building dapps on Celo

Celo Progressive Dapp Starter A starter pack to get started with building dapps on Celo. You can view a live version of the template deployed at https

Apr 27, 2022
This is a polling dApp to vote and get paid.
This is a polling dApp to vote and get paid.

PollingDapp : vote and get paid How it works Installation Deploy and run node on localhost: Terminal n°1: cd pollingsDapp npx hardhat node Terminal n°

Dec 8, 2021
React Query, Axios, Typescript example: get, post, put, delete - useQuery, useMutation, error handling
React Query, Axios, Typescript example: get, post, put, delete - useQuery, useMutation, error handling

React Query with Axios and Typescript example React Client with React Query and Axios (Typescript) to make CRUD requests to Rest API in that: React Qu

May 16, 2022
Simple React-Native boilerplate code in Typescript for getting started with a new project quickly. It has all the essentials that one would require in a project.

react-native-boilerplate-typescript Simple React-Native boilerplate code in Typescript for getting started with a new project quickly. It has all the

Feb 25, 2022
Cheatsheets for experienced React developers getting started with TypeScript
Cheatsheets for experienced React developers getting started with TypeScript

React+TypeScript Cheatsheets Cheatsheets for experienced React developers getting started with TypeScript Web docs | 中文翻译 | Español | Português | Cont

Jun 25, 2022
Cheatsheets for experienced React developers getting started with TypeScript
Cheatsheets for experienced React developers getting started with TypeScript

React+TypeScript Cheatsheets Cheatsheets for experienced React developers getting started with TypeScript Web docs | 中文翻译 | Español | Português | Cont

Feb 20, 2022