### Install and Start Application
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md
Run these commands to install dependencies and start the development server.
```bash
pnpm install
pnpm start
```
--------------------------------
### Setup React-Query Client and Provider
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md
Initialize a QueryClient and wrap your application with QueryClientProvider in main.tsx.
```tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
// ...
const queryClient = new QueryClient()
// ...
if (!rootElement.innerHTML) {
const root = ReactDOM.createRoot(rootElement)
root.render(
,
)
}
```
--------------------------------
### Install React-Query Dependencies
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md
Add React-Query and its devtools to your project using pnpm.
```bash
pnpm add @tanstack/react-query @tanstack/react-query-devtools
```
--------------------------------
### Install TanStack Store Dependency
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md
Add TanStack Store to your project dependencies using pnpm.
```bash
pnpm add @tanstack/store
```
--------------------------------
### Fetch Data with useQuery
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md
Example of fetching data from an API using the `useQuery` hook in a React component.
```tsx
import { useQuery } from '@tanstack/react-query'
import './App.css'
function App() {
const { data } = useQuery({
queryKey: ['people'],
queryFn: () =>
fetch('https://swapi.dev/api/people')
.then((res) => res.json())
.then((data) => data.results as { name: string }[]),
initialData: [],
})
return (
{data.map((person) => (
{person.name}
))}
)
}
export default App
```
--------------------------------
### Get Available Size Options
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html
Determines which size properties (rendered, gzip, brotli) are available based on the provided options object. 'renderedLength' is always included.
```javascript
const getAvailableSizeOptions = (options) => {
const availableSizeProperties = ["renderedLength"];
if (options.gzip) {
availableSizeProperties.push("gzipLength");
}
if (options.brotli) {
availableSizeProperties.push("brotliLength");
}
return availableSizeProperties;
};
```
--------------------------------
### Derive State with TanStack Store
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md
Example of creating a derived store that automatically updates based on changes in a base store.
```tsx
import { useStore } from '@tanstack/react-store'
import { Store, Derived } from '@tanstack/store'
import './App.css'
const countStore = new Store(0)
const doubledStore = new Derived({
fn: () => countStore.state * 2,
deps: [countStore],
})
doubledStore.mount()
function App() {
const count = useStore(countStore)
const doubledCount = useStore(doubledStore)
return (
Doubled - {doubledCount}
)
}
export default App
```
--------------------------------
### React Component Initialization
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html
Initializes React component state and lifecycle hooks. This snippet appears to be part of a larger React component setup, likely handling component mounting and updates.
```javascript
var t,r,u,i,o=0,f=[],c=l$1,e=c.__b,a=c.__r,v=c.diffed,l=c.__c,m=c.unmount,s=c.__;function p(n,t){c.__h&&c.__h(r,n,o||t),o=0;var u=r.__H||
```
--------------------------------
### Build Application for Production
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md
Execute this command to create a production-ready build of the application.
```bash
pnpm build
```
--------------------------------
### Setting Up Web3Provider with NexusProvider
Source: https://context7.com/availproject/nexus-ui-components-demo/llms.txt
This component wraps the entire application with necessary providers including Wagmi, ConnectKit, and NexusProvider. Ensure your WalletConnect project ID is set in your environment variables.
```tsx
import { NexusProvider } from '@avail-project/nexus-widgets'
import { createConfig, WagmiProvider } from 'wagmi'
import { defineChain } from 'viem'
import { base, polygon, arbitrum, optimism, mainnet } from 'wagmi/chains'
import { ConnectKitProvider, getDefaultConfig } from 'connectkit'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
const config = createConfig(
getDefaultConfig({
appName: 'Avail Nexus',
walletConnectProjectId: process.env.VITE_WALLETCONNECT_PROJECT_ID!,
multiInjectedProviderDiscovery: true,
chains: [mainnet, base, polygon, arbitrum, optimism],
}),
)
const queryClient = new QueryClient()
const Web3Provider = ({ children }: { children: React.ReactNode }) => (
{children}
)
export default Web3Provider
```
--------------------------------
### Initialize and Manage Nexus SDK with useNexus Hook
Source: https://context7.com/availproject/nexus-ui-components-demo/llms.txt
Use the `useNexus` hook to access the SDK instance, manage its initialization state, and control the provider. It's essential for integrating the SDK into your application's lifecycle, especially for wallet connections and disconnections.
```tsx
// src/components/connect-wallet.tsx
import { useNexus, type EthereumProvider } from '@avail-project/nexus-widgets'
import { useAccount, useWalletClient } from 'wagmi'
import { useEffect } from 'react'
function WalletConnection() {
const { setProvider, provider, isSdkInitialized, deinitializeSdk, initializeSdk, sdk } =
useNexus()
const { status } = useAccount()
const { data: walletClient } = useWalletClient()
useEffect(() => {
// Inject EIP-1193 provider when wallet connects
if (!provider && status === 'connected' && walletClient) {
const ethProvider: EthereumProvider = {
request: (args: unknown) => walletClient.request(args as any),
}
setProvider(ethProvider)
}
// Clean up SDK when wallet disconnects
if (isSdkInitialized && provider && status === 'disconnected') {
deinitializeSdk()
}
}, [status, provider, isSdkInitialized])
// Lazily initialize the SDK on user demand
const handleInit = async () => {
if (!isSdkInitialized) {
try {
await initializeSdk()
console.log('SDK initialized. Instance:', sdk)
} catch (err) {
console.error('SDK init failed:', err)
}
}
}
return
}
```
--------------------------------
### Query Supported Chains and Tokens with sdk.utils
Source: https://context7.com/availproject/nexus-ui-components-demo/llms.txt
Utilize the `sdk.utils` namespace to programmatically discover supported chains and tokens for bridging and swapping operations. This is useful for dynamically configuring UI elements or validating user selections.
```typescript
import { useNexus } from '@avail-project/nexus-widgets'
function SupportedChainsList() {
const { sdk } = useNexus()
const logSupportedData = () => {
// Returns array of supported chain IDs/metadata
const chains = sdk?.utils?.getSupportedChains()
console.log('Supported chains:', chains)
// e.g. [{ id: 8453, name: 'Base' }, { id: 42161, name: 'Arbitrum' }, ...]
// Returns a map of chainId → supported token symbols for swaps
const swapTokens = sdk?.utils?.getSwapSupportedChainsAndTokens()
console.log('Swap supported tokens by chain:', swapTokens)
// e.g. { 8453: ['USDC', 'ETH'], 42161: ['USDC', 'USDT', 'ETH'], ... }
}
return
}
```
--------------------------------
### Get Module IDs from Cache
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html
Retrieves module IDs from a cache. This is a utility function for accessing cached module identifiers.
```javascript
const getModuleIds = (node) => nodeIdsCache.get(node);
```
--------------------------------
### Create a Simple Counter with TanStack Store
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md
Demonstrates creating a basic counter store and using it in a React component with the `useStore` hook.
```tsx
import { useStore } from '@tanstack/react-store'
import { Store } from '@tanstack/store'
import './App.css'
const countStore = new Store(0)
function App() {
const count = useStore(countStore)
return (
)
}
export default App
```
--------------------------------
### picomatch.toRegex
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html
Creates a regular expression directly from a glob pattern string. This is a convenient way to get a RegExp object for matching.
```APIDOC
## picomatch.toRegex(source, options)
### Description
Creates a regular expression from the given regex source string. This is a convenient way to get a RegExp object for matching.
### Parameters
#### Path Parameters
- **source** (String) - Required - Regular expression source string.
- **options** (Object) - Optional - Configuration options for the RegExp constructor, such as flags.
### Request Example
```js
const picomatch = require('picomatch');
const { output } = picomatch.parse('*.js');
console.log(picomatch.toRegex(output));
//=> /^(?:(?!\.)(?=.)[^/]*\.js)$/
```
### Response
#### Success Response (RegExp)
- **RegExp** - A regular expression object created from the given source string.
#### Response Example
```js
/^(?:(?!\.)(?=.)[^/]*\.js)$/
```
```
--------------------------------
### formatTrim Function
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html
Trims insignificant zeros from a formatted number string, for example, converting '1.2000k' to '1.2k'. Useful for cleaning up SI-prefixed numbers.
```javascript
function formatTrim(s) { out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) { switch (s[i]) { case ".": i0 = i1 = i; break; case "0": if (i0 === 0) i0 = i; i1 = i; break; default: if (!+s[i]) break out; if (i0 > 0) i0 = 0; break; } } return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s; }
```
--------------------------------
### Run Tests with Vitest
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md
Use this command to execute the test suite powered by Vitest.
```bash
pnpm test
```
--------------------------------
### Tick Specification Calculation
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html
Calculates tick specifications for generating axis ticks, considering start, stop, and desired count. Handles logarithmic scales.
```javascript
const e10 = Math.sqrt(50), e5 = Math.sqrt(10), e2 = Math.sqrt(2); function tickSpec(start, stop, count) { const step = (stop - start) / Math.max(0, count), power = Math.floor(Math.log10(step)), error = step / Math.pow(10, power), factor = error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1; let i1, i2, inc; if (power < 0) { inc = Math.pow(10, -power) / factor; i1 = Math.round(start * inc); i2 = Math.round(stop
```
--------------------------------
### Tooltip for Compressed Byte Size
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html
Displays a tooltip explaining 'gzipLength' and 'brotliLength'. These values represent the byte size of an individual file after transformations, tree-shaking, and compression.
```jsx
const COMPRESSED = (u$1("span", { children: [u$1("b", { children: LABELS.gzipLength }), " and ", u$1("b", { children: LABELS.brotliLength }), " is a byte size of individual file after individual transformations,", u$1("br", {}), " treeshake and compression."] }));
```
--------------------------------
### Load Route Data Before Rendering
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md
Utilize the 'loader' functionality in TanStack Router to fetch data for a route before it is rendered. This example fetches people data from an API.
```tsx
const peopleRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/people',
loader: async () => {
const response = await fetch('https://swapi.dev/api/people')
return response.json() as Promise<{
results: {
name: string
}[]
}> // Added type assertion for clarity
},
component: () => {
const data = peopleRoute.useLoaderData()
return (
{data.results.map((person) => (
{person.name}
))}
)
},
})
```
--------------------------------
### Module Initialization and State Management
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html
Internal module logic for managing component updates, subscriptions, and lifecycle methods. It handles component mounting, diffing, and unmounting.
```javascript
(r.__H={__:[],__h:[]});return n>=u.__.length&&u.__.push({}),u.__[n]}function d(n){return o=1,h(D,n)}function h(n,u,i){var o=p(t++,2);if(o.t=n,!o.__c&&(o.__=[D(void 0,u),function(n){var t=o.__N?o.__N[0]:o.__[0],r=o.t(t,n);t!==r&&(o.__N=[r,o.__[1]],o.__c.setState({}));}],o.__c=r,!r.__f)){var f=function(n,t,r){if(!o.__c.__H)return true;var u=o.__c.__H.__.filter(function(n){return !!n.__c});if(u.every(function(n){return !n.__N}))return !c||c.call(this,n,t,r);var i=o.__c.props!==n;return u.forEach(function(n){if(n.__N){var t=n.__[0];n.__=n.__N,n.__N=void 0,t!==n.__[0]&&(i=true);}}),c&&c.call(this,n,t,r)||i};r.__f=true;var c=r.shouldComponentUpdate,e=r.componentWillUpdate;r.componentWillUpdate=function(n,t,r){if(this.__e){var u=c;c=void 0,f(n,t,r),c=u;}e&&e.call(this,n,t,r);},r.shouldComponentUpdate=f;}return o.__N||o.__}function y(n,u){var i=p(t++,3);!c.__s&&C(i.__H,u)&&(i.__=n,i.u=u,r.__H.__h.push(i));}function _(n,u){var i=p(t++,4);!c.__s&&C(i.__H,u)&&(i.__=n,i.u=u,r.__h.push(i));}function A(n){return o=5,T(function(){return {current:n}},[])}function T(n,r){var u=p(t++,7);return C(u.__H,r)&&(u.__=n(),u.__H=r,u.__h=n),u.__}function q(n,t){return o=8,T(function(){return n},t)}function x(n){var u=r.context[n.__c],i=p(t++,9);return i.c=n,u?(null==i.__&&(i.__=true,u.sub(r)),u.props.value):n.__}function j(){for(var n;n=f.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(z),n.__H.__h.forEach(B),n.__H.__h=[]}catch(t){n.__H.__h=[],c.__e(t,n.__v);}}c.__b=function(n){r=null,e&&e(n);},c.__=function(n,t){n&&t.__k&&t.__k.__m&&(n.__m=t.__k.__m),s&&s(n,t);},c.__r=function(n){a&&a(n),t=0;var i=(r=n.__c).__H;i&&(u===r?(i.__h=[],r.__h=[],i.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0;})):(i.__h.forEach(z),i.__h.forEach(B),i.__h=[],t=0)),u=r;},c.diffed=function(n){v&&v(n);var t=n.__c;t&&t.__H&&(t.__H.__h.length&&(1!==f.push(t)&&i===c.requestAnimationFrame||((i=c.requestAnimationFrame)||w)(j)),t.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0;})),u=r=null;},c.__c=function(n,t){t.some(function(n){try{n.__h.forEach(z),n.__h=n.__h.filter(function(n){return !n.__||B(n)});}catch(r){t.some(function(n){n.__h&&(n.__h=[]);}),t=[],c.__e(r,n.__v);}}),l&&l(n,t);},c.unmount=function(n){m&&m(n);var t,r=n.__c;r&&r.__H&&(r.__H.__.forEach(function(n){try{z(n);}catch(n){t=n;}}),r.__H=void 0,t&&c.__e(t,r.__v));};var k="function"==typeof requestAnimationFrame;function w(n){var t,r=function(){clearTimeout(u),k&&cancelAnimationFrame(t),setTimeout(n);},u=setTimeout(r,35);k&&(t=requestAnimationFrame(r));}function z(n){var t=r,u=n.__c;"function"==typeof u&&(n.__c=void 0,u()),r=t;}function B(n){var t=r;n.__c=n.__(),r=t;}function C(n,t){return !n||n.length!==t.length||t.some(function(t,r){return t!==n[r]})}function D(n,t){return "function"==typeof t?t(n):t}
```
--------------------------------
### Render Main Component with Context
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html
Renders the main application component, providing a static context with various data and utility functions. This sets up the application's state for rendering.
```javascript
E(u$1(StaticContext.Provider, { value: { data, availableSizeProperties, width, height, getModuleSize, getModuleIds, getModuleColor, rawHierarchy, layout, }, children: u$1(Main, {}) }), parentNode);
```
--------------------------------
### Initialize Treemap Layout
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html
Sets up a treemap layout with specified dimensions, padding, and tiling algorithm. This is used for hierarchical data visualization.
```javascript
const layout = treemap() .size([width, height]) .paddingOuter(PADDING) .paddingTop(TOP_PADDING) .paddingInner(PADDING) .round(true) .tile(treemapResquarify);
```
--------------------------------
### Create a Context Provider/Consumer
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html
Defines a React-like Context API with Provider and Consumer components. The Provider manages context value and notifies subscribers of changes. The Consumer accesses the context value via a render prop.
```javascript
function K(n){function l(n){var u,t;return this.getChildContext||(u=new Set,(t={})[l.__c]=this,this.getChildContext=function(){return t},this.componentWillUnmount=function(){u=null;},this.shouldComponentUpdate=function(n){this.props.value!=n.value&&u.forEach(function(n){n.__e=true,M(n);});},this.sub=function(n){u.add(n);var l=n.componentWillUnmount;n.componentWillUnmount=function(){u&&u.delete(n),l&&l.call(n);};}),n.children}return l.__c="__cC"+h$1++,l.__=n,l.Provider=l.__l=(l.Consumer=function(n,l){return n.children(l)}).contextType=l,l}
```
--------------------------------
### Create a Root Layout with Header and Navigation
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md
Define a root route component that includes a header with navigation links and an outlet for child routes. Includes TanStack Router Devtools.
```tsx
import { Outlet, createRootRoute } from '@tanstack/react-router'
import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
import { Link } from '@tanstack/react-router'
export const Route = createRootRoute({
component: () => (
<>
>
),
})
```
--------------------------------
### Lint, Format, and Check Code
Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md
These scripts help maintain code quality using ESLint and Prettier.
```bash
pnpm lint
pnpm format
pnpm check
```
--------------------------------
### Configuring NexusProvider
Source: https://context7.com/availproject/nexus-ui-components-demo/llms.txt
The `NexusProvider` component from `@avail-project/nexus-widgets` must wrap all components utilizing Nexus hooks or widget buttons. Configure the SDK's network and debug mode via the `config` prop.
```tsx
import { NexusProvider } from '@avail-project/nexus-widgets'
// Minimal setup inside your provider tree
{children}
```
--------------------------------
### sdk.utils
Source: https://context7.com/availproject/nexus-ui-components-demo/llms.txt
Provides utility methods for querying supported chains and tokens within the Nexus SDK.
```APIDOC
## `sdk.utils` — Query Supported Chains and Tokens
The `sdk.utils` namespace exposes utility methods to discover which chains and tokens are supported for bridging and swapping.
### Usage
```tsx
import { useNexus } from '@avail-project/nexus-widgets'
function SupportedChainsList() {
const { sdk } = useNexus()
const logSupportedData = () => {
// Returns array of supported chain IDs/metadata
const chains = sdk?.utils?.getSupportedChains()
console.log('Supported chains:', chains)
// e.g. [{ id: 8453, name: 'Base' }, { id: 42161, name: 'Arbitrum' }, ...]
// Returns a map of chainId → supported token symbols for swaps
const swapTokens = sdk?.utils?.getSwapSupportedChainsAndTokens()
console.log('Swap supported tokens by chain:', swapTokens)
// e.g. { 8453: ['USDC', 'ETH'], 42161: ['USDC', 'USDT', 'ETH'], ... }
}
return
}
```
### Methods in `sdk.utils`
- **`getSupportedChains()`**: Returns an array of supported chain objects, each containing `id` and `name`.
- **`getSwapSupportedChainsAndTokens()`**: Returns a map where keys are chain IDs and values are arrays of token symbols supported for swaps on that chain.
```
--------------------------------
### Fetch Unified User Balances with sdk.getUnifiedBalances()
Source: https://context7.com/availproject/nexus-ui-components-demo/llms.txt
After initializing the SDK, call `sdk.getUnifiedBalances()` to retrieve an aggregated list of the user's token holdings across all supported chains. This function returns a `UserAsset[]` array, useful for displaying a consolidated view of a user's assets.
```tsx
// src/components/view-balance.tsx
import { useNexus, CHAIN_METADATA, SUPPORTED_CHAINS } from '@avail-project/nexus-widgets'
import type { UserAsset } from '@avail-project/nexus-widgets'
import { useState } from 'react'
function ViewUnifiedBalance() {
const { isSdkInitialized, sdk, initializeSdk } = useNexus()
const [balances, setBalances] = useState()
const fetchBalance = async () => {
if (!isSdkInitialized) await initializeSdk()
const result = await sdk?.getUnifiedBalances()
// result example:
// [
// {
// symbol: 'USDC',
// balance: '250.500000',
// balanceInFiat: 250.5,
// icon: 'https://...',
// breakdown: [
// { chain: { id: 8453, name: 'Base' }, balance: '100.0', balanceInFiat: 100.0, decimals: 6 },
// { chain: { id: 42161, name: 'Arbitrum' }, balance: '150.5', balanceInFiat: 150.5, decimals: 6 },
// ]
// }
// ]
setBalances(result)
}
const totalFiat = balances
?.reduce((acc, asset) => acc + asset.balanceInFiat, 0)
.toFixed(2)
return (