### Install SDK Dapp via yarn
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Install the sdk-dapp library using yarn. Ensure you are running your app on https.
```bash
yarn add @multiversx/sdk-dapp
```
--------------------------------
### Install SDK Dapp via npm
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Install the sdk-dapp library using npm. Ensure you are running your app on https.
```bash
npm install @multiversx/sdk-dapp
```
--------------------------------
### Initialize and Start WebviewClient
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/providers/strategies/WebviewProviderStrategy/WebviewClient/README.md
Initialize the WebviewClient with a callback for login cancellations and start listening for messages. This is used in the parent dApp to manage authentication requests from child iframes.
```typescript
import { WebviewClient } from '@multiversx/sdk-dapp/out/providers/strategies/WebviewProviderStrategy/WebviewClient';
const webviewClient = new WebviewClient({
// Perform action when login is cancelled
onLoginCancelled: async () => {
setApp(null)
}
});
webviewClient.startListening();
// Optional: Register a custom event handler
webviewClient.registerEvent('dAppcustomEvent', (event) => {
console.log('Received data:', event.data.payload);
});
```
--------------------------------
### Create and Login with Custom Provider
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Example of creating a custom provider using ProviderFactory and logging in. Ensure the custom provider extends the IProvider interface.
```typescript
const provider = await ProviderFactory.create({
type: 'custom-provider'
});
await provider?.login();
```
--------------------------------
### Link dapp-core with YALC
Source: https://github.com/multiversx/mx-sdk-dapp/wiki/How-To
Use YALC for linking local packages. Install YALC globally, then link 'dapp-core' to your project. After changes, publish from the 'dist' folder.
```bash
yarn install
yarn build
yarn start
cd dist
```
```bash
yalc link @elrondnetwork/dapp-core
```
```bash
yalc publish --push
```
```bash
yalc remove --all
```
--------------------------------
### Example Commit Message
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/CONTRIBUTING.md
Follow this format for clear and informative commit messages. Include a brief summary line and detailed bullet points for changes.
```git commit
feat: add support for custom transaction tracking
- Adds customizable tracking options
- Updates documentation
- Includes unit tests
```
--------------------------------
### Example Usage of sendAndTrackTransactions
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/managers/TransactionManager/TRANSACTIONS_MANAGER_README.md
Demonstrates how to use the sendAndTrackTransactions helper with custom toast messages. Transactions can be sent in parallel or as sequential batches.
```typescript
const transactions = [tx1, tx2]; // or [[tx1, tx2], [tx3]]
const sessionId = await sendAndTrackTransactions({
transactions,
options: {
transactionsDisplayInfo: {
processingMessage: 'Processing your transactions...',
successMessage: 'All transactions successful!',
errorMessage: 'There was an error.'
}
}
});
```
--------------------------------
### Send and Track Transactions Directly
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/managers/TransactionManager/TRANSACTIONS_MANAGER_README.md
Use TransactionManager.getInstance() to get an instance and then use send() to send transactions and track() to monitor their status.
```typescript
const txManager = TransactionManager.getInstance();
const sentTransactions = await txManager.send(transactions);
const sessionId = await txManager.track(sentTransactions, options);
```
--------------------------------
### LogoutManager Configuration Example
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/managers/LogoutManager/LOGOUT_MANAGER_README.md
Configure token expiration and warning times for the LogoutManager via the nativeAuth config in initApp.
```typescript
const config: InitAppType = {
// ...
nativeAuth: {
expirySeconds: 30, // Token expires after 30 seconds
tokenExpirationToastWarningSeconds: 10 // Show warning 10 seconds before logout
}
}
```
--------------------------------
### Control Internal Webcomponents via EventBus
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
This example demonstrates how to interact with internal webcomponents using the EventBus pattern. It shows how to create a component instance, retrieve its EventBus, and publish messages.
```typescript
import { ComponentFactory } from '@multiversx/sdk-dapp/out/utils/ComponentFactory';
const modalElement = await ComponentFactory.create(
'mvx-ledger-connect-panel'
);
const eventBus = await modalElement.getEventBus();
eventBus.publish('TRANSACTION_TOAST_DATA_UPDATE', someData);
```
--------------------------------
### Signing a Transaction with SDK Dapp
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Construct and sign a transaction using the MultiversX SDK. This example demonstrates creating a 'pong' transaction and signing it via the account provider. Ensure you have the necessary imports and initialized variables like `contractAddress`, `network`, and `account`.
```typescript
import { Address, Transaction } from '@multiversx/sdk-core';
import {
GAS_PRICE,
GAS_LIMIT
} from '@multiversx/sdk-dapp/out/constants/mvx.constants';
import { getAccountProvider } from '@multiversx/sdk-dapp/out/providers/helpers/accountProvider';
import { refreshAccount } from '@multiversx/sdk-dapp/out/utils/account/refreshAccount';
const pongTransaction = new Transaction({
value: BigInt(0),
data: Buffer.from('pong'),
receiver: Address.newFromBech32(contractAddress),
gasLimit: BigInt(GAS_LIMIT),
gasPrice: BigInt(GAS_PRICE),
chainID: network.chainId,
nonce: BigInt(account.nonce),
sender: Address.newFromBech32(account.address),
version: 1
});
await refreshAccount(); // optionally, to get the latest nonce
const provider = getAccountProvider();
const signedTransactions = await provider.signTransactions(transactions);
```
--------------------------------
### Process Transactions for Table Display
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/controllers/CONTROLLERS_README.md
This example demonstrates how to use the TransactionsTableController to process raw server transaction data into a format suitable for display in a UI table. It utilizes hooks for account and network configuration and updates the processed transaction state when the component mounts or dependencies change.
```typescript
import { TransactionsTableController } from 'controllers/TransactionsTableController/TransactionsTableController';
import { useEffect, useState } from 'react';
import type { MvxTransactionsTable as MvxTransactionsTablePropsType } from '@multiversx/sdk-dapp-ui/web-components/mvx-transactions-table';
import type { ServerTransactionType } from '@multiversx/sdk-dapp/out/types/serverTransactions.types';
import {
MvxTransactionsTable,
} from '@multiversx/sdk-dapp-ui/react';
import type { TransactionsRowType } from '@multiversx/sdk-dapp/out/controllers/TransactionsTableController/transactionsTableController.types';
import { TransactionsTableController } from '@multiversx/sdk-dapp/out/controllers/TransactionsTableController';
import { useGetAccount } from '@multiversx/sdk-dapp/out/react/account/useGetAccount';
import { useGetNetworkConfig } from '@multiversx/sdk-dapp/out/react/network/useGetNetworkConfig';
interface TransactionsTablePropsType {
transactions?: ServerTransactionType[];
}
export const TransactionsTable = (
{ transactions = [] }:
TransactionsTablePropsType
) => {
const { address } = useGetAccount();
const { network } = useGetNetworkConfig();
const [processedTransaction, setProcessedTransactions] = useState<
TransactionsRowType[]
>([]);
useEffect(() => {
processTransactions();
}, []);
const processTransactions = async () => {
const transactionsData =
await TransactionsTableController.processTransactions({
address,
egldLabel: network.egldLabel,
explorerAddress: network.explorerAddress,
transactions
});
setProcessedTransactions(transactionsData);
};
return ;
};
```
--------------------------------
### React Unlock Component Example
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/managers/UnlockPanelManager/UNLOCK_PANEL_MANAGER_README.md
A React component that initializes the UnlockPanelManager and opens the unlock panel on component mount if the user is not logged in. It uses react-router-dom for navigation.
```typescript
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { UnlockPanelManager, useGetLoginInfo } from 'lib';
import { RouteNamesEnum } from 'localConstants';
export const Unlock = () => {
const navigate = useNavigate();
const { isLoggedIn } = useGetLoginInfo();
const unlockPanelManager = UnlockPanelManager.init({
loginHandler: () => {
navigate(RouteNamesEnum.dashboard);
},
onClose: () => {
navigate(RouteNamesEnum.home);
}
});
const handleOpenUnlockPanel = () => {
unlockPanelManager.openUnlockPanel();
};
useEffect(() => {
if (isLoggedIn) {
navigate(RouteNamesEnum.dashboard);
return;
}
handleOpenUnlockPanel();
}, [isLoggedIn]);
return null;
};
```
--------------------------------
### Open Notifications Feed Button
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/managers/NotificationsFeedManager/NOTIFICATIONS_FEED_MANAGER_README.md
Example of a React component that provides a button to open the notifications feed. It uses the `openNotificationsFeed` method from the manager.
```typescript
import { faBell } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { NotificationsFeedManager } from '@multiversx/sdk-dapp/out/managers/NotificationsFeedManager/NotificationsFeedManager';
import { Button } from 'components';
export const NotificationsButton = () => {
const handleOpenNotificationsFeed = async () => {
await NotificationsFeedManager.getInstance().openNotificationsFeed();
};
return (
);
};
```
--------------------------------
### Build the mx-sdk-dapp library
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Run this command to build the library. Ensure your package manager is set up correctly.
```bash
npm run build
```
--------------------------------
### Get Singleton Instance
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/managers/NotificationsFeedManager/NOTIFICATIONS_FEED_MANAGER_README.md
Access the singleton instance of the NotificationsFeedManager to interact with its methods.
```typescript
const notificationsFeedManager = NotificationsFeedManager.getInstance();
```
--------------------------------
### Initialize SDK Dapp Application
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Configure storage, network, and signing providers by calling initApp. It's recommended to call this in index.tsx before rendering the app.
```typescript
// index.tsx
import { initApp } from '@multiversx/sdk-dapp/out/methods/initApp/initApp';
import type { InitAppType } from '@multiversx/sdk-dapp/out/methods/initApp/initApp.types';
import { EnvironmentsEnum } from '@multiversx/sdk-dapp/out/types/enums.types';
import { App } from "./App";
const config: InitAppType = {
storage: { getStorageCallback: () => sessionStorage },
dAppConfig: {
// nativeAuth: true, // optional
environment: EnvironmentsEnum.devnet,
// network: { // optional
// walletAddress: 'https://devnet-wallet.multiversx.com' // or other props you want to override
// },
// transactionTracking: { // optional
// successfulToastLifetime: 5000,
// onSuccess: async (sessionId) => {
// console.log('Transaction session successful', sessionId);
// },
// onFail: async (sessionId) => {
// console.log('Transaction session failed', sessionId);
// }
}
// customProviders: [myCustomProvider] // optional
};
initApp(config).then(() => {
render(() => , root!); // render your app
});
```
--------------------------------
### Directory Structure of SDK Dapp
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
This bash snippet shows the directory structure of the SDK Dapp, highlighting key folders like apiCalls, constants, providers, methods, react, and store.
```bash
src/
├── apiCalls/ ### methods for interacting with the API
├── constants/ ### useful constants from the ecosystem like ledger error codes, default gas limits for transactions etc.
├── controllers/ ### business logic for UI elements that are not bound to the store
├── managers/ ### business logic for UI elements that are bound to the store
├── providers/ ### signing providers
├── methods/ ### utility functions to query and update the store
├── react/ ### react hooks to query the store
└── store/ ### store initialization, middleware, slices, selectors and actions
```
--------------------------------
### Stopping Automatic Logout with LogoutManager
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/managers/LogoutManager/LOGOUT_MANAGER_README.md
Call LogoutManager.getInstance().stop() to disable automatic logout logic, for example, after a successful login.
```typescript
import { LogoutManager } from '@multiversx/sdk-dapp/out/managers/LogoutManager/LogoutManager';
loginHandler: () => {
navigate('/dashboard');
// Stop automatic logout upon native auth expiration
LogoutManager.getInstance().stop();
},
```
--------------------------------
### Run unit tests for mx-sdk-dapp
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Execute this command to run the unit tests for the library. This helps verify the integrity of the codebase.
```bash
npm test
```
--------------------------------
### Subscribing to Store Changes for Live Updates
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Implement live updates by subscribing to store changes using `getStore` and `store.subscribe`. This is useful for non-reactive environments like SolidJS where you need to track state modifications.
```typescript
import { createSignal, onCleanup } from 'solid-js';
import { getStore } from '@multiversx/sdk-dapp/out/store/store';
export function useStore() {
const store = getStore();
const [state, setState] = createSignal(store.getState());
const unsubscribe = store.subscribe((newState) => {
setState(newState);
});
onCleanup(() => unsubscribe());
return state;
}
```
--------------------------------
### Link dapp-core with npm
Source: https://github.com/multiversx/mx-sdk-dapp/wiki/How-To
Use this method to link a local 'dapp-core' project to your dapp project via npm. Ensure both projects are in the same parent directory.
```bash
npm link ../my-dapp/node_modules/react ../my-dapp/node_modules/axios
```
```bash
npm run build
npm run start
```
```bash
npm link ../dapp-core/dist
```
```bash
npm run start
```
--------------------------------
### Create and Send Custom Toasts
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Demonstrates how to create custom toast notifications for user feedback, either with a custom component or a simple message. Also shows how to close a custom toast.
```typescript
import {
createRoot
} from 'react-dom/client';
import { createCustomToast } from '@multiversx/sdk-dapp/out/store/actions/toasts/toastsActions';
import { ToastManager } from '@multiversx/sdk-dapp/out/managers/ToastManager';
// by creating a custom toast element containing a component
createCustomToast({
toastId: 'username-toast',
instantiateToastElement: () => {
const toastBody = document.createElement('div');
const root = createRoot(toastBody);
root.render();
return toastBody;
}
});
// or by creating a simple custom toast
createCustomToast({
toastId: 'custom-toast',
icon: 'times',
iconClassName: 'warning',
message: 'This is a custom toast',
title: 'My custom toast'
});
// closing a custom toast
const toastManager = ToastManager.getInstance();
toastManager.closeToast('custom-toast') // toastId
```
--------------------------------
### Sign Transactions with Options
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Demonstrates how to use the `signTransactions` method with optional parameters for skipping guardian validation or providing a post-signing callback.
```typescript
import type { SignTransactionsOptionsType } from '@multiversx/sdk-dapp/out/providers/DappProvider/helpers/signTransactions/signTransactionsWithProvider';
const options: SignTransactionsOptionsType = {
skipGuardian?: boolean; // Skip guardian validation for guarded accounts
callback?: (signedTransactions: Transaction[]) => Promise; // Post-signing callback
};
const signedTransactions = await provider.signTransactions(transactions, options);
```
--------------------------------
### Fetch Account Information from API
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/apiCalls/API_CALLS_README.md
Fetches account information from the MultiversX API using the provided address and base URL. Requires axiosInstance and getCleanApiAddress utilities. Includes guardian info by default.
```typescript
import { getAccountFromApi } from 'apiCalls/account/getAccountFromApi';
const account = await getAccountFromApi({
address: 'erd1...',
baseURL: 'https://api.multiversx.com'
});
```
--------------------------------
### Manual LogoutManager Initialization
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/managers/LogoutManager/LOGOUT_MANAGER_README.md
Manually initialize the LogoutManager by calling getInstance().init() if needed.
```typescript
import { LogoutManager } from '@multiversx/sdk-dapp/out/managers/LogoutManager/LogoutManager';
LogoutManager.getInstance().init();
```
--------------------------------
### Programmatic Login with ProviderFactory (Extension)
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Demonstrates programmatic login using the ProviderFactory for the extension provider. This method is suitable for custom UI implementations. Ensure the dApp is served over HTTPS.
```typescript
import { ProviderTypeEnum } from '@multiversx/sdk-dapp/out/providers/types/providerFactory.types';
const provider = await ProviderFactory.create({
type: ProviderTypeEnum.extension
});
await provider.login();
```
--------------------------------
### Enable WalletConnect V2 in WalletConnectLoginButton
Source: https://github.com/multiversx/mx-sdk-dapp/wiki/WalletConnect-V2-Setup
Set the `isWalletConnectV2` flag to true in the `` component to activate WalletConnect V2 functionality for user login.
```jsx
```
--------------------------------
### Import TransactionManager and Transaction
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/managers/TransactionManager/TRANSACTIONS_MANAGER_README.md
Import necessary classes from the SDK for transaction management.
```typescript
import { Transaction } from '@multiversx/sdk-core';
import { TransactionManager } from '@multiversx/sdk-dapp/out/managers/TransactionManager';
import type { TransactionsDisplayInfoType } from '@multiversx/sdk-dapp/out/types/transactions.types';
```
--------------------------------
### Send and Track Transactions with TransactionManager
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Shows how to send signed transactions using `TransactionManager` and track their status with custom toast notifications.
```typescript
import { TransactionManager } from '@multiversx/sdk-dapp/out/managers/TransactionManager';
import type { TransactionsDisplayInfoType } from '@multiversx/sdk-dapp/out/types/transactions.types';
const txManager = TransactionManager.getInstance();
const sentTransactions = await txManager.send(signedTransactions);
const toastInformation: TransactionsDisplayInfoType = {
processingMessage: 'Processing transactions',
errorMessage: 'An error has occurred during transaction execution',
successMessage: 'Transactions executed'
};
const sessionId = await txManager.track(sentTransactions, {
transactionsDisplayInfo: toastInformation
});
```
--------------------------------
### Opening the Unlock Panel
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/managers/UnlockPanelManager/UNLOCK_PANEL_MANAGER_README.md
Opens the login side panel to allow users to select a wallet provider and initiate the login process.
```APIDOC
## unlockPanelManager.openUnlockPanel()
### Description
Triggers the display of the login side panel, presenting the user with available wallet providers to initiate the login flow.
### Method
```typescript
unlockPanelManager.openUnlockPanel()
```
### Endpoint
N/A (This is a method call on an initialized manager instance)
### Parameters
None
### Request Example
```typescript
// Assuming unlockPanelManager has been initialized
unlockPanelManager.openUnlockPanel();
```
### Response
N/A (This method controls UI presentation and does not return a value directly related to API responses.)
```
--------------------------------
### UnlockPanelManager Initialization
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/managers/UnlockPanelManager/UNLOCK_PANEL_MANAGER_README.md
Initializes the UnlockPanelManager with login and close handlers. This is a singleton, so subsequent calls will update the handlers.
```APIDOC
## UnlockPanelManager.init()
### Description
Initializes the UnlockPanelManager singleton with configuration options, including handlers for login completion and panel closure, and an optional list of allowed providers.
### Method
```typescript
UnlockPanelManager.init(params: UnlockPanelManagerInitParamsType)
```
### Parameters
#### Initialization Parameters
- **loginHandler** (function | async function) - Required. A callback function executed after a successful login, or an async function to perform custom login logic.
- **onClose** (function) - Optional. A callback function executed when the panel is closed without a successful login.
- **allowedProviders** (Array) - Optional. An array specifying which providers to display and in what order. Defaults to all supported providers.
### Request Example
```typescript
import { UnlockPanelManager } from '@multiversx/sdk-dapp/out/managers/UnlockPanelManager';
const unlockPanelManager = UnlockPanelManager.init({
loginHandler: () => {
// Handle post-login navigation or actions
console.log('Login successful!');
},
onClose: () => {
// Handle panel close without login
console.log('Panel closed.');
},
// Example of restricting providers:
// allowedProviders: ['walletConnect', 'myCustomProvider']
});
```
### TypeScript Types
```typescript
type UnlockPanelManagerInitParamsType = {
loginHandler: (() => void) | (({ type, anchor }: { type: string, anchor: any }) => Promise);
allowedProviders?: string[];
onClose?: () => void;
};
```
```
--------------------------------
### Open Notifications Feed with NotificationManager
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Demonstrates how to open the transaction notifications feed using the `NotificationManager`.
```typescript
const notificationManager = NotificationManager.getInstance();
await notificationManager.openNotificationsFeed();
```
--------------------------------
### Accessing Account and Network Data with Store Selectors
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Retrieve account and network configuration data using store selector functions when not using React. Note that this approach is not reactive unless you manually subscribe to store changes.
```typescript
import { getAccount } from '@multiversx/sdk-dapp/out/methods/account/getAccount';
import { getNetworkConfig } from '@multiversx/sdk-dapp/out/methods/network/getNetworkConfig';
const account = getAccount();
const { egldLabel } = getNetworkConfig();
```
--------------------------------
### Displaying Account and Network Data with React Hooks
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Use these React hooks to access user account details like address and balance, and network configuration such as the EGLD label. Ensure the SDK Dapp is properly configured for React.
```typescript
import { useGetAccount } from '@multiversx/sdk-dapp/out/react/account/useGetAccount';
import { useGetNetworkConfig } from '@multiversx/sdk-dapp/out/react/network/useGetNetworkConfig';
const account = useGetAccount();
const {
network: { egldLabel }
} = useGetNetworkConfig();
console.log(account.address);
console.log(`${account.balance} ${egldLabel}`);
```
--------------------------------
### Enable WalletConnect V2 in WalletConnectLoginContainer
Source: https://github.com/multiversx/mx-sdk-dapp/wiki/WalletConnect-V2-Setup
Activate WalletConnect V2 by setting the `isWalletConnectV2` flag to true within the `` component, providing access to the login UI without the button.
```jsx
```
--------------------------------
### Customize Global Transaction Toasts and Callbacks
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/managers/TransactionManager/TRANSACTIONS_MANAGER_README.md
Configure global toast lifetimes and callbacks for transaction success and failure within the initApp configuration.
```typescript
initApp({
dAppConfig: {
transactionTracking: {
successfulToastLifetime: 5000,
onSuccess: async (sessionId) => { /* ... */ },
onFail: async (sessionId) => { /* ... */ }
}
}
});
```
--------------------------------
### getAccountFromApi
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/apiCalls/API_CALLS_README.md
Fetches account information from the MultiversX API. This is a public function intended for direct use by developers.
```APIDOC
## getAccountFromApi
### Description
Fetches account information from the MultiversX API. This function is exported from the account module and is intended for direct use.
### Method
POST
### Endpoint
/accounts
### Parameters
#### Query Parameters
- **withGuardianInfo** (boolean) - Optional - Includes guardian info in the response.
#### Request Body
- **address** (string) - Optional - The account address to fetch.
- **baseURL** (string) - Required - The base URL for the API.
### Response
#### Success Response (200)
- **AccountType** (object) - Account data if found.
- **null** - If the address is invalid or an error occurs.
### Request Example
```json
{
"address": "erd1...",
"baseURL": "https://api.multiversx.com"
}
```
### Response Example
```json
{
"address": "erd1...",
"balance": "1000000000000000000",
"nonce": 123,
"code": "",
"username": null,
"guardian": "erd1...",
"accounts": []
}
```
```
--------------------------------
### Configure npm link with preserveSymlinks
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
When using npm link, ensure the server configuration includes `preserveSymlinks: true` to correctly resolve symlinked packages.
```javascript
resolve: {
preserveSymlinks: true, // "
alias: {
src: "/src",
},
},
```
--------------------------------
### UnlockPanelManager Initialization with Custom Login Logic
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/managers/UnlockPanelManager/UNLOCK_PANEL_MANAGER_README.md
Initializes the UnlockPanelManager with an advanced login handler that allows for custom logic, such as using a provider instance to perform the login.
```APIDOC
## UnlockPanelManager.init() with Custom Login Handler
### Description
Initializes the UnlockPanelManager, providing a custom asynchronous `loginHandler`. This handler allows for direct interaction with provider instances to manage the login process, retrieve user addresses, and perform custom navigation.
### Method
```typescript
UnlockPanelManager.init(params: UnlockPanelManagerInitParamsType)
```
### Parameters
#### Initialization Parameters
- **loginHandler** (async function) - Required. An asynchronous function that receives `type` and `anchor` to create a provider instance. It should handle the login process and can perform custom actions like navigation based on the returned address.
- **onClose** (function) - Optional. Called when the panel is closed without login.
### Request Example
```typescript
import { UnlockPanelManager } from '@multiversx/sdk-dapp/out/managers/UnlockPanelManager';
import { ProviderFactory } from '@multiversx/sdk-dapp/out/providers/ProviderFactory'; // Assuming ProviderFactory is accessible
const unlockPanelManager = UnlockPanelManager.init({
loginHandler: async ({ type, anchor }) => {
const provider = await ProviderFactory.create({ type, anchor });
const { address } = await provider.login();
// Example: navigate to a dashboard with the address
// navigate(`/dashboard?address=${address}`);
console.log(`Logged in with address: ${address}`);
},
onClose: () => {
console.log('Panel closed.');
}
});
```
### TypeScript Types
```typescript
type UnlockPanelManagerInitParamsType = {
loginHandler: (({ type, anchor }: { type: string, anchor: any }) => Promise);
onClose?: () => void;
};
```
```
--------------------------------
### Import NotificationsFeedManager
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/managers/NotificationsFeedManager/NOTIFICATIONS_FEED_MANAGER_README.md
Import the NotificationsFeedManager class from the SDK.
```typescript
import { NotificationsFeedManager } from '@multiversx/sdk-dapp/out/managers/NotificationsFeedManager/NotificationsFeedManager';
```
--------------------------------
### Import API Call Modules
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/apiCalls/API_CALLS_README.md
Import the main API call module for accessing various blockchain data functions.
```typescript
import { getAccountFromApi } from 'apiCalls';
```
--------------------------------
### Configure Native Auth Auto Logout and Warning Toast
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Configure native authentication settings within the initApp method. Set expirySeconds for auto logout and tokenExpirationToastWarningSeconds to display a warning toast before logout.
```typescript
// in initApp config
const config: InitAppType = {
// ...
nativeAuth: {
expirySeconds: 30, // test auto logout after 30 seconds
tokenExpirationToastWarningSeconds: 10 // show warning toast 10 seconds before auto logout
}
};
```
--------------------------------
### Using Callback Option for Sign Transactions
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Illustrates the usage of the `callback` option within `signTransactions` to process signed transactions before guardian validation, such as logging.
```typescript
const signedTransactions = await provider.signTransactions(transactions, {
callback: async (signedTxs) => {
// Example: Log signed transactions before guardian processing
console.log('User signed transactions:', signedTxs);
// Return the transactions to proceed with guardian validation
return signedTxs;
}
});
```
--------------------------------
### Define API Endpoint URLs
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/apiCalls/API_CALLS_README.md
Import and use endpoint constants to construct URLs for various MultiversX API resources.
```typescript
import { ACCOUNTS_ENDPOINT, TRANSACTIONS_ENDPOINT } from 'apiCalls/endpoints';
const accountUrl = `${apiAddress}/${ACCOUNTS_ENDPOINT}/${address}`;
const transactionsUrl = `${apiAddress}/${TRANSACTIONS_ENDPOINT}`;
```
--------------------------------
### Inspect Transaction Store Information
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Accesses and inspects transaction session data from the SDK Dapp's store. Use `getStore()` for direct access or `useStore` for reactivity.
```typescript
import {
pendingTransactionsSessionsSelector,
transactionsSliceSelector
} from '@multiversx/sdk-dapp/out/store/selectors/transactionsSelector';
import { getStore } from '@multiversx/sdk-dapp/out/store/store';
const store = getStore(); // or use useStore hook for reactivity
const pendingSessions = pendingTransactionsSessionsSelector(store.getState());
const allTransactionSessions = transactionsSliceSelector(store.getState());
const isSessionIdPending = Object.keys(pendingSessions).includes(sessionId);
const currentSession = allTransactionSessions[sessionId];
const currentSessionStatus = currentSession?.status;
const currentTransaction = currentSession?.transactions?.[0];
const currentTransactionStatus = currentTransaction?.status;
```
--------------------------------
### Configure DappProvider with WalletConnect V2 Project ID
Source: https://github.com/multiversx/mx-sdk-dapp/wiki/WalletConnect-V2-Setup
Provide the WalletConnect V2 Project ID within the customNetworkConfig of the DappProvider wrapper. This ID is essential for accessing the WalletConnect Cloud Relay.
```jsx
```
--------------------------------
### Track Transactions with Minimal Custom Info
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
A simplified way to track transactions, providing only essential custom messages for error, success, and processing states.
```typescript
const sessionId = await transactionManager.track(sentTransactions, {
transactionsDisplayInfo: {
errorMessage: 'Failed adding stake',
successMessage: 'Stake successfully added',
processingMessage: 'Staking in progress'
}
});
```
--------------------------------
### Updated Imports from dapp-core
Source: https://github.com/multiversx/mx-sdk-dapp/wiki/Migration-guide-2.0
Import specific modules from their respective folders instead of the main index.js. This enables tree-shaking and reduces bundle size.
```javascript
import {
SignTransactionsModals
} from '@elrondnetwork/dapp-core/dist/UI'
import { DappProvider } from '@elrondnetwork/dapp-core/wrappers'
import { useGetAccountInfo } from '@elrondnetwork/dapp-core/hooks'
import { formatAmount } from '@elrondnetwork/dapp-core/utils'
```
--------------------------------
### Format Amount Component with Controller
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/controllers/CONTROLLERS_README.md
This component utilizes the FormatAmountController to format and validate amount displays. It integrates with network configuration and provides formatted integer and decimal parts along with a label. Ensure necessary network configurations and constants like DECIMALS and DIGITS are imported.
```tsx
import { MvxFormatAmount } from '@multiversx/sdk-dapp-ui/react';
import { MvxFormatAmountPropsType } from '@multiversx/sdk-dapp-ui/types';
export { DECIMALS, DIGITS } from '@multiversx/sdk-dapp-utils/out/constants';
import { FormatAmountController } from '@multiversx/sdk-dapp/out/controllers/FormatAmountController';
export { useGetNetworkConfig } from '@multiversx/sdk-dapp/out/react/network/useGetNetworkConfig';
interface IFormatAmountProps
extends Partial {
value: string;
className?: string;
}
export const FormatAmount = (props: IFormatAmountProps) => {
const {
network: { egldLabel }
} = useGetNetworkConfig();
const { isValid, valueDecimal, valueInteger, label } =
FormatAmountController.getData({
digits: DIGITS,
decimals: DECIMALS,
egldLabel,
...props,
input: props.value
});
return (
);
};
```
--------------------------------
### Advanced UnlockPanelManager with Custom Login Handler
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Use an advanced UnlockPanelManager configuration where the loginHandler processes the login result. It creates a provider instance and performs the login, then navigates to the dashboard with the user's address.
```typescript
export const AdvancedConnectButton = () => {
const unlockPanelManager = UnlockPanelManager.init({
loginHandler: async ({ type, anchor }) => {
const provider = await ProviderFactory.create({
type,
anchor
});
const { address, signature } = await provider.login();
navigate(`/dashboard?address=${address}`);
},
onCancelLogin: async () => { // optional action to be performed when the user cancels the login
navigate('/');
}
});
const handleOpenUnlockPanel = () => {
unlockPanelManager.openUnlockPanel();
// if you want to select a specific provider for your user, you can call
// unlockPanelManager.selectProvider(ProviderTypeEnum.extension);
};
return ;
};
```
--------------------------------
### Initialize UnlockPanelManager
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/managers/UnlockPanelManager/UNLOCK_PANEL_MANAGER_README.md
Initializes the UnlockPanelManager with login and close handlers. The loginHandler is called after a successful login, and onClose is called when the panel is closed without logging in. Custom providers can be specified using allowedProviders.
```typescript
import { UnlockPanelManager } from '@multiversx/sdk-dapp/out/managers/UnlockPanelManager';
const unlockPanelManager = UnlockPanelManager.init({
loginHandler: () => {
// Called after login is performed
navigate('/dashboard');
},
onClose: () => {
// Called when the panel is closed without login
navigate('/');
},
// allowedProviders: [ProviderTypeEnum.walletConnect, 'myCustomProvider'] // Optional: restrict or reorder providers
});
```
--------------------------------
### Advanced Login Handler with Custom Logic
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/managers/UnlockPanelManager/UNLOCK_PANEL_MANAGER_README.md
Demonstrates an advanced usage of UnlockPanelManager where the loginHandler performs custom logic, including creating a provider instance and logging in using its address. This is useful for custom provider integrations.
```typescript
const unlockPanelManager = UnlockPanelManager.init({
loginHandler: async ({ type, anchor }) => {
const provider = await ProviderFactory.create({ type, anchor });
const { address } = await provider.login();
navigate(`/dashboard?address=${address}`);
}
});
```
--------------------------------
### Send and Track Transactions Helper
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/managers/TransactionManager/TRANSACTIONS_MANAGER_README.md
A helper function to send and track transactions concurrently. It utilizes the TransactionManager's send and track methods. Options can disable toasts or customize transaction display messages.
```typescript
type SendAndTrackTransactionsType = {
transactions: Transaction[] | Transaction[][];
options?: {
disableToasts?: boolean;
transactionsDisplayInfo?: TransactionsDisplayInfoType;
};
};
export const sendAndTrackTransactions = async ({
transactions,
options
}: SendAndTrackTransactionsType) => {
const txManager = TransactionManager.getInstance();
const sentTransactions = await txManager.send(transactions);
const sessionId = await txManager.track(sentTransactions, options);
return sessionId;
};
```
--------------------------------
### NotificationsFeedManager Methods
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/managers/NotificationsFeedManager/NOTIFICATIONS_FEED_MANAGER_README.md
Provides access to the singleton instance of NotificationsFeedManager and its core methods for controlling the notifications feed UI.
```APIDOC
## NotificationsFeedManager API
### Import
```typescript
import { NotificationsFeedManager } from '@multiversx/sdk-dapp/out/managers/NotificationsFeedManager/NotificationsFeedManager';
```
### Singleton Access
```typescript
const notificationsFeedManager = NotificationsFeedManager.getInstance();
```
### Methods
#### `openNotificationsFeed()`
Opens the notifications feed side panel, hides toasts, and subscribes to store updates.
- **Method:** `openNotificationsFeed`
- **Returns:** `Promise`
#### `isNotificationsFeedOpen()`
Returns whether the notifications feed is currently open.
- **Method:** `isNotificationsFeedOpen`
- **Returns:** `boolean`
```
--------------------------------
### Importing API Functions Directly
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/apiCalls/API_CALLS_README.md
Always import functions directly from their specific files for better module management. Avoid importing from index.ts files.
```typescript
import { getAccountFromApi } from 'apiCalls/account/getAccountFromApi'
```
```typescript
import { getAccountFromApi } from 'apiCalls/account'
```
--------------------------------
### Initialize UnlockPanelManager for dApp Login
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Initializes the UnlockPanelManager to open a side panel with supported login providers. Link the openUnlockPanel method to a user action like a button click. The loginHandler is called upon successful login.
```typescript
import { UnlockPanelManager } from '@multiversx/sdk-dapp/out/managers/UnlockPanelManager';
import { ProviderFactory } from '@multiversx/sdk-dapp/out/providers/ProviderFactory';
export const ConnectButton = () => {
const unlockPanelManager = UnlockPanelManager.init({
loginHandler: () => {
navigate('/dashboard');
},
onClose: () => { // optional action to be performed when the user closes the Unlock Panel
navigate('/');
},
// allowedProviders: [ProviderTypeEnum.walletConnect, 'myCustomProvider'] // optionally, only show specific providers
});
const handleOpenUnlockPanel = () => {
unlockPanelManager.openUnlockPanel();
};
return ;
};
```
--------------------------------
### Log Out User
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Logs out the current user by calling the `logout()` method on the account provider. Ensure the account provider is correctly initialized.
```typescript
import { getAccountProvider } from '@multiversx/sdk-dapp/out/providers/helpers/accountProvider';
const provider = getAccountProvider();
await provider.logout();
```
--------------------------------
### TransactionManager.getInstance()
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/managers/TransactionManager/TRANSACTIONS_MANAGER_README.md
Returns the singleton instance of the TransactionManager. This is the primary way to access TransactionManager functionalities.
```APIDOC
## TransactionManager.getInstance()
### Description
Returns the singleton instance of the TransactionManager.
### Method
N/A (Static method)
### Endpoint
N/A
```
--------------------------------
### Fetch Multiple Transactions by Hashes
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/apiCalls/API_CALLS_README.md
Efficiently retrieve multiple transactions in a single API call by providing an array of their hashes. This is optimized for fetching several transactions at once.
```typescript
import { getServerTransactionsByHashes } from 'apiCalls/transactions/getServerTransactionsByHashes';
const transactions = await getServerTransactionsByHashes([
'hash1',
'hash2',
'hash3'
]);
```
--------------------------------
### Send Batch Transactions
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Use this method to send transactions sequentially, where each batch must complete before the next one begins execution. This is useful for ordered operations.
```typescript
const transactionManager = TransactionManager.getInstance();
const batchTransactions: SignedTransactionType[][] = [
[tx1, tx2],
[tx3, tx4]
];
const sentTransactions = await transactionManager.send(batchTransactions);
```
--------------------------------
### Format User Balance with MvxFormatAmount
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Format user balances using the FormatAmount component, which utilizes FormatAmountController for data processing. This component requires network configuration and specific formatting constants.
```tsx
import { MvxFormatAmount } from '@multiversx/sdk-dapp-ui/react';
import { MvxFormatAmountPropsType } from '@multiversx/sdk-dapp-ui/types';
export { DECIMALS, DIGITS } from '@multiversx/sdk-dapp-utils/out/constants';
import { FormatAmountController } from '@multiversx/sdk-dapp/out/controllers/FormatAmountController';
export { useGetNetworkConfig } from '@multiversx/sdk-dapp/out/react/network/useGetNetworkConfig';
interface IFormatAmountProps extends Partial {
value: string;
className?: string;
}
export const FormatAmount = (props: IFormatAmountProps) => {
const {
network: { egldLabel }
} = useGetNetworkConfig();
const { isValid, valueDecimal, valueInteger, label } =
FormatAmountController.getData({
digits: DIGITS,
decimals: DECIMALS,
egldLabel,
...props,
input: props.value
});
return (
);
};
```
--------------------------------
### Fetch Blockchain Economics Data
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/apiCalls/API_CALLS_README.md
Fetches economics data including supply, price, and APR. Requires the base API URL. Returns null on failure.
```typescript
import { getEconomics } from 'apiCalls/economics/getEconomics';
const economics = await getEconomics({
baseURL: 'https://api.multiversx.com'
});
```
--------------------------------
### Track Transactions with Custom Options
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/README.md
Use this snippet to track transactions with custom toast messages and session information. It allows overriding default messages and defining callbacks for success and failure.
```typescript
import { TransactionManagerTrackOptionsType } from '@multiversx/sdk-dapp/out/managers/TransactionManager/TransactionManager.types';
const options: TransactionManagerTrackOptionsType = {
disableToasts: false, // `false` by default
transactionsDisplayInfo: {
// optional. If left `undefined`, it will use the default messages
errorMessage: 'Failed adding stake',
successMessage: 'Stake successfully added',
receivedMessage: 'Stake successfully added', // optional, add it in case of multiple transactions
processingMessage: 'Staking in progress'
// submittedMessage: 'Stake submitted',
// timedOutMessage: 'Transaction timed out',
// invalidMessage: 'Invalid transaction',
},
sessionInformation: {
// `undefined` by default. Use to perform additional actions based on the session information
stakeAmount: '1000000000000000000000000'
},
onSuccess: async (sessionId) => {
// optional
// overrides the the global `onSuccess` callback set in the `initApp` method for the current session only
console.log('Session successful', sessionId);
},
onFail: async (sessionId) => {
// optional
console.log('Session failed', sessionId);
}
};
const sessionId = await transactionManager.track(
sentTransactions,
options // optional
);
```
--------------------------------
### getEconomics
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/apiCalls/API_CALLS_README.md
Fetches blockchain economics information including supply, price, and APR data. This function is not exported from the main index.ts.
```APIDOC
## getEconomics
### Description
Fetches blockchain economics information including total supply, circulating supply, staked tokens, price, market capitalization, and APR data.
### Method
GET
### Endpoint
/economics
### Parameters
#### Query Parameters
- `url` (string) - Optional - Custom endpoint URL (defaults to `ECONOMICS_ENDPOINT`)
- `baseURL` (string) - Required - The base URL for the API
### Response
#### Success Response (200)
- `totalSupply` (string) - Total token supply
- `circulatingSupply` (string) - Circulating token supply
- `staked` (string) - Total staked tokens
- `price` (number) - Current token price
- `marketCap` (number) - Market capitalization
- `apr` (number) - Annual percentage rate
- `topUpApr` (number) - Top-up APR
### Request Example
```json
{
"baseURL": "https://api.multiversx.com"
}
```
### Response Example
```json
{
"totalSupply": "35278000000000000000000000000000",
"circulatingSupply": "35278000000000000000000000000000",
"staked": "10000000000000000000000000000000",
"price": 0.123,
"marketCap": 4300000000,
"apr": 5.5,
"topUpApr": 6.0
}
```
```
--------------------------------
### Open Unlock Panel
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/managers/UnlockPanelManager/UNLOCK_PANEL_MANAGER_README.md
Opens the login side panel managed by the UnlockPanelManager. This function should be called when the user needs to initiate the login process.
```typescript
unlockPanelManager.openUnlockPanel();
```
--------------------------------
### Automatic LogoutManager Initialization with initApp
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/managers/LogoutManager/LOGOUT_MANAGER_README.md
The LogoutManager is automatically initialized when using initApp if native auth is enabled and the user is logged in.
```typescript
import { initApp } from '@multiversx/sdk-dapp/out/methods/initApp/initApp';
initApp(config).then(() => {
// Your app logic
});
```
--------------------------------
### Fetch Transactions with Filtering and Pagination
Source: https://github.com/multiversx/mx-sdk-dapp/blob/main/src/apiCalls/API_CALLS_README.md
Use this function to retrieve transactions based on sender, receiver, timestamps, status, and pagination. It can also include smart contract results and username information.
```typescript
import { getTransactions } from 'apiCalls/transactions/getTransactions';
const transactions = await getTransactions({
apiAddress: 'https://api.multiversx.com',
sender: 'erd1...',
page: 1,
transactionSize: 10,
withScResults: true
});
```