# Embedded Wallet SDK React

With the Embedded Wallet SDK, you can supercharge your dApp’s UX. It is super easy to integrate and completely customisable to meet your dApp’s styles. It also helps solve the current Snaps limitations and integrating this will allow users to view their balances, manage their assets, and more.

{% tabs %}
{% tab title="Swapfast" %}

<figure><img src="https://897927660-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrOZ4nLnlAQp8G5goWQ1X%2Fuploads%2FrPJ1mxMROSZIGACWbaWs%2FScreenshot_1.png?alt=media&#x26;token=2762df20-29c8-4d0b-936c-b578465e44e8" alt=""><figcaption></figcaption></figure>
{% endtab %}

{% tab title="Badkids Shop" %}

<figure><img src="https://897927660-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrOZ4nLnlAQp8G5goWQ1X%2Fuploads%2FEJhuUqUha3YUwcqvAQN8%2FScreenshot%202024-08-08%20at%2010.13.48%20AM.png?alt=media&#x26;token=e918f78e-522f-4d53-bd1e-1ae87ec38f4a" alt=""><figcaption></figcaption></figure>
{% endtab %}
{% endtabs %}

## Installation

```bash
npm install @leapwallet/embedded-wallet-sdk-react
```

## Usage

### Get Started

```tsx
import React from "react";
import { useChain } from "@cosmos-kit/react";
import { AccountModal } from "@leapwallet/embedded-wallet-sdk-react";
import "@leapwallet/embedded-wallet-sdk-react/styles.css";

const chainId = "osmosis-1";
const chain = "osmosis";
const restUrl = "https://rest.cosmos.directory/osmosis";

const YourApp = () => {
  const { address } = useChain(chain);
  const [isModalOpen, setIsModalOpen] = React.useState(false);
  
  // trigger the dApp's connect and disconnect wallet flow
  const connectWallet = () => {}
  const disconnectWallet = () => {}
  
  const connectedWalletType = "wallet-type"

  const chainData = {
      [chainId]: {
        address: address ?? "",
        restURL: restURL
      },
  };

  return (
    <div>
      {/* other components */}
      <button onClick={() => setIsModalOpen(true)}>Open Modal</button>
      
      {/* enclose component within provider */}
      <EmbeddedWalletProvider
      connectWallet={connectWallet}
      disconnectWallet={disconnectWallet}
      connectedWalletType={connectedWalletType}
      >
	  <AccountModal
	    theme="dark"
	    chainRecords={chainData}
	    isOpen={isModalOpen}
	    onClose={closeModal}
	  />
      </EmbeddedWalletProvider>
      {/* other components */}
    </div>
  );
};
```

#### Props

| Name                  | Type                                                                                                 | Description                                                                                                                                  |
| --------------------- | ---------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `theme`               | `"light" \| "dark"`                                                                                  | Theme of the modal                                                                                                                           |
| `chainRecords`        | `Record<string, { address: string; restUrl?: string, coinType?: string }> \| null`. Key is `chainId` | Record of addresses and REST URLs corresponding to given chain ID.                                                                           |
| `isOpen`              | `boolean`                                                                                            | Whether the modal is open                                                                                                                    |
| `onClose`             | `() => void`                                                                                         | Callback function when the modal is closed                                                                                                   |
| `config`              | `Config`                                                                                             | Config of the modal                                                                                                                          |
| `height`              | `string`                                                                                             | Height of the component                                                                                                                      |
| `width`               | `string`                                                                                             | Width of the component                                                                                                                       |
| `enableWalletConnect` | `boolean`                                                                                            | When true, wallet connection can be controlled via embedded wallet                                                                           |
| `restrictChains`      | `boolean`                                                                                            | Defaults to false, shows balances of all discoverable chains. Passing this as true restricts to only fetching balances for specified chains. |

Here is the type definition of `Config`:

```ts
type Config = {
  // This function is called to render the title of the modal
  title?: (page: Page) => React.ReactNode;
  // This function is called to render the sub-title of the modal
  subTitle?: (page: Page) => React.ReactNode;
  // Should the modal be closed when the backdrop is clicked
  closeOnBackdropClick?: boolean;
  // Should the modal be closed when the escape key is pressed
  closeOnEscape?: boolean;
  // Configure the action list on the home page
  actionListConfig?: ActionListConfig;
  // Should action buttons be visible
  showActionButtons?: boolean;
};

type ActionListConfig = Record<
  string,
  {
    label?: string;
    onClick?: () => void;
    enabled?: boolean;
    order?: number;
  }
>;

enum Page {
  HOME = "home",
  ADDRESSES = "addresses"
}
```

#### Example Configuration

```tsx
import { Page, Actions } from '@leapwallet/snaps-sdk-react'

const config: Config = {
  title: (page) => {
    switch (page) {
      case Page.HOME:
        return "Assets";
      case Page.ADDRESSES:
        return "Addresses";
    }
  },
  closeOnBackdropClick: true,
  closeOnEscape: true,
  actionListConfig: {
    [Actions.Swap]: {
      label: "Swap",
      onClick: () => {
        console.log('Open Swap tab');
      },
      enabled: true,
    },
    [Actions.Bridge]: {
      enabled: false,
    },
  },
};
```

### Usage with Custom React UI

In case you want to create your own UI in react, we have exposed the react hooks that we use internally. If you are not using react, then you can check out the [next page](https://docs.leapwallet.io/cosmos/embedded-wallet-sdk/usage-without-ui).

For making queries, we primarily use [swr](https://swr.vercel.app), so a lot of return values from hooks will have the same return type (except for the data).

#### User Balances

To fetch user balances, you can use `useRichBalance` hook.

```tsx
const balanceQuery = useRichBalance(
  address,
  chainId,
  restUrl,
  swrConfiguration
);
```

**Parameters -**

1. `address` - the wallet address your querying the balance for
2. `chainId` - self explanatory
3. `restUrl` (optional) - custom rest url for the node
4. `swrConfiguration` (optional) - configure your swr query, click [here](https://swr.vercel.app/docs/global-configuration.en-US) for more information

#### **Multi Chain Balances**

To fetch balances across multiple chains, you can use

```jsx
const aggregatedBalances = useAggregatedRichBalance(
  chainRecords,
  key
)
```

**Parameters -**

1. `aggregatedChainData` - chain records which you provide account modal to fetch balances
2. `key` - optional, key for SWR configuration

#### User Activity

To fetch user activity, you can use `useActivity` hook. The return type of a `@tanstack/react-query` [`useInfiniteQuery`](https://tanstack.com/query/v4/docs/react/reference/useInfiniteQuery) hook.

```tsx
const activityQuery = useActivity(address, chainId, restUrl);
```

**Parameters -**

1. `address` - the wallet address your querying the balance for
2. `chainId` - self explanatory
3. `restUrl` (optional) - custom rest url for the node

**Return Value -**

The `activityQuery.data.pages` field will be a list of objects with the following fields -

```javascript
{
    sender: [] // array of activity where user is sender of tokens
    recipient: [] // // array of activity where user is received of tokens
}
```

**Usage Example -**

Using the activity data

```typescript
import { type ActivityCardContent } from '@leapwallet/snaps-sdk-core'

// flat list of activity
const activityList = activityQuery.data.pages
    .reduce((acc, cur) => {
        return [...acc, ...cur.sender.activity, ...cur.recipient.activity];
    }, [] as ActivityCardContent[]);
    
// you can now sort this list however you want
```

Triggering the next (data) page load using the last element on the list

```tsx
const [searchQuery, setSearchQuery] = useState<string>('')

useEffect(() => {
  // track last item on the list
  const lastItem = document.querySelector("#activity-bottom");
  if (
    !lastItem ||
    activityQuery.isLoading ||
    activityQuery.isFetchingNextPage ||
    activityQuery.error ||
    searchQuery.trim().length > 0
  ) {
    return;
  }
  const handleIntersection = ([i]: IntersectionObserverEntry[]) => {
    if (i.isIntersecting) {
      activityQuery.fetchNextPage();
    }
  };
  const observer = new IntersectionObserver(handleIntersection, {
    root: null,
    rootMargin: "0px",
    threshold: 1.0,
  });
  observer.observe(lastItem);
  return () => {
    observer.disconnect();
  };
}, [activityQuery, debouncedSearchQuery]);
```
