# 1.0 React Hooks

### Overview

Our React Hooks library uses `react-query` under the hood & will expose request parameters & response objects that mimic `react-query` functionality. For instance, in the request parameters you can pass the `{ enabled: boolean }` object and other request parameters found in [react-query's documentation](https://tanstack.com/query/v4/docs/reference/useQuery?from=reactQueryV3\&original=https://react-query-v3.tanstack.com/reference/useQuery). The response objects will also mimic `react-query` with `{ data, isLoading, isSuccess }` etc.

{% hint style="info" %}
Since we are mimicking `react-query` Reveel's SDK integration should feel familiar to many react devs. This also means we are essentially mimicking the request parameter & response objects used by [`wagmi`](https://wagmi.sh/) which should also feel familiar to web3 Devs.
{% endhint %}

Functions with example uses are shown below. All the examples below use wagmi functions alongside @r3vl/sdk, but this is not a requirement. Notably, the following example is using `wagmi 0.10.8`

### Integrating the sdk into your frontend

Add the package to your frontend app:

```shell
yarn add @r3vl/sdk

--------- or ---------

npm install @r3vl/sdk
```

Add the provider to your frontend (below is a next.js example):

```typescript
import { R3vlProvider, createClient as r3vlCreateClient } from "@r3vl/sdk";
import { WagmiConfig, createClient } from "wagmi";

const r3vlClient = r3vlCreateClient();
const wagmiClient = createClient({
  // per wagmi instructions: https://wagmi.sh/examples/connect-wallet
});
const App = ({ Component, pageProps }: AppProps) => {
  return (
    <WagmiConfig client={wagmiClient}>
      <R3vlProvider client={r3vlClient}>
        <Component {...pageProps} />
      </R3vlProvider>
    </WagmiConfig>
  )
}
```

### Creating Revenue Path (code subject to change)

```typescript
import { useCreateRevenuePath, useR3vlClient } from "@r3vl/sdk";
import { ethers } from "ethers";
import { useProvider, useNetwork, useSigner } from "wagmi";

interface ICreateArgs {
  walletList: string[][];
  distribution: number[][];
  tiers: { [token: 'ETH' | 'WETH' | 'DAI' | 'USDC']: BigNumberish }[]
  name: string;
  mutabilityEnabled: boolean;
}

export const CreatePathButton = ({ createArgs }: { ICreateArgs }) => {
    const { chain } = useNetwork();
    const provider = useProvider();
    const { data: signer } = useSigner();

    useR3vlClient({
        chainId: chain?.id,
        provider,
        signer,
        initV2Final: true, // In case you want to create a "complex" Revenue Path with tiers
        initSimple: true, // For revenue paths with no additional tiers configuration
        apiKey: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx',
        // Api key is required so SDK can store and access data related to Revenue Path configuration 
    });

    const { mutate: createRevenuePath } = useCreateRevenuePath();
    
    const handleSubmit = () => {
        createRevenuePath(createArgs);
    };
    
    return (
        <button onClick={handleSubmit}>Create Path</button>
    );
};
```

#### At the moment, @r3vl/sdk is compatible with the following chains:

* Ethereum (mainnet & goerli)
* Polygon (mainnet & mumbai)
* Arbitrum (one & testnet)
* Optimism (mainnet & goerli)
* Aurora (mainnet & testnet)

#### Here a live example of a NextJS implementation of the R3VL SDK

{% embed url="<https://codesandbox.io/embed/next-js-r3vl-sdk-hcr9sh?fontsize=14&theme=dark&view=editor>" %}

### Withdrawing From Revenue Path

```typescript
import { useWithdraw } from "@r3vl/sdk";
import { useAccount, useProvider, useNetwork, useSigner } from "wagmi";
import { ethers } from "ethers";

const revPathAddress = '0xSomeAddress'

export const WithdrawRevenueButton = () => {
    const { chain } = useNetwork();
    const provider = useProvider();
    const { data: signer } = useSigner();

    useR3vlClient({
        chainId: chain?.id,
        provider,
        signer,
        initV2Final: true, // In case you want to create a "complex" Revenue Path with tiers
        initSimple: true, // For revenue paths with no additional tiers configuration
        apiKey: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx',
        // Api key is required so SDK can store and access data related to Revenue Path configuration 
    });

    const withdraw = useWithdraw(revPathAddress);
    const { address } = useAccount();
    
    const handleWithdraw = () => {
        withdraw.mutate({
            walletAddress: address,
            isERC20: 'someTokenAddress' // OPTIONAL - Address of specific erc20 token
        });
    };
    
    return (
        <button onClick={handleWithdraw}>Withdraw Revenue</button>
    );
};
```

### Get Revenue Path Balances

{% hint style="info" %}
a simple hook to display a user's available balances
{% endhint %}

<pre class="language-typescript"><code class="lang-typescript">import { useBalances } from "@r3vl/sdk";
import { useAccount, useProvider, useNetwork, useSigner } from "wagmi";
import { ethers } from "ethers";

const revPathAddress = '0xSomeAddress'

export const DisplayBalances = () => {
<strong>    const { chain } = useNetwork();
</strong>    const provider = useProvider();
    const { data: signer } = useSigner();

    useR3vlClient({
        chainId: chain?.id,
        provider,
        signer,
        initV2Final: true, // In case you want to create a "complex" Revenue Path with tiers
        initSimple: true, // For revenue paths with no additional tiers configuration
        apiKey: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx',
        // Api key is required so SDK can store and access data related to Revenue Path configuration 
    });

    const { address } = useAccount();
    const { data: balances } = useBalances(
        revPathAddress,
        {
            walletAddress: address, // OPTIONAL - Address of specific user wallet
            isERC20: 'someTokenAddress' // OPTIONAL - Address of specific erc20 token
        }, { enabled: !!address }
    );
    
    return (
        // earnings - withdrawn = withdrawable
        &#x3C;div display="flex">
            &#x3C;div className="total-earnings">{balances.earnings}&#x3C;/div>
            &#x3C;div className="total-withdrawn">{balances.withdrawn}&#x3C;/div>
            &#x3C;div className="total-withdrawable">{balances.withdrawable}&#x3C;/div>
        &#x3C;/div>
    );
};
</code></pre>

### Get Revenue Path Tiers

{% hint style="info" %}
a simple hook to fetch tier data from an existing revenue path
{% endhint %}

```typescript
import { useBalances } from "@r3vl/sdk";
import { useAccount, useProvider, useNetwork, useSigner } from "wagmi";
import { ethers } from "ethers";

const revPathAddress = '0xSomeAddress'

export const DisplayBalances = () => {
    const { chain } = useNetwork();
    const provider = useProvider();
    const { data: signer } = useSigner();

    useR3vlClient({
        chainId: chain?.id,
        provider,
        signer,
        initV2Final: true, // In case you want to create a "complex" Revenue Path with tiers
        initSimple: true, // For revenue paths with no additional tiers configuration
        apiKey: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx',
        // Api key is required so SDK can store and access data related to Revenue Path configuration 
    });

    const { address } = useAccount();
    const { data: tiers, isFetched: tiersFetched } =
        useRevenuePathTiers(revPathAddress)
    const tier = tiers?.[0] || {}

    if (tiersFetched) console.log(
        "Revenue path data:",
        Object.keys(tier.proportions: {
           [address: string]: number 
        }).reduce((prev, curr) => {
            return [
                ...prev, {
                    address: curr,
                    share: tier.proportions[curr] * 10000000000000 
                }
            ]
        }, [])
    )
)
    return null
};
```

### Updating Revenue Path

{% hint style="info" %}
hook to update an existing revenue path in case user's wallet owns that revenue path and it's mutability is enabled
{% endhint %}

```typescript
import { useUpdateRevenuePath, useR3vlClient } from "@r3vl/sdk";
import { ethers } from "ethers";
import { useProvider, useNetwork, useSigner } from "wagmi";

interface IUpdateLimitsArgs {
  tokens: string[],
  newLimits: number[], 
  tier: number
}

interface IAddRevenueTierArgs {
  walletList: string[][]
  distribution: number[][]
  newAddedTierLimits: number[]
  finalFundWalletList: string[]
  finalFundDistribution: number[]
  finalFundIndex: number
}

export const UpdateRevenuePath = (
  {
    updateLimitsArgs,
    addRevenueTierArgs
  }: {
    updateLimitsArgs: IUpdateLimitsArgs
    addRevenueTierArgs: IAddRevenueTierArgs
  }) => {
    const { chain } = useNetwork();
    const provider = useProvider();
    const { data: signer } = useSigner();

    useR3vlClient({
        chainId: chain?.id,
        provider,
        signer,
        initV2Final: true, // In case you want to create a "complex" Revenue Path with tiers
        initSimple: true, // For revenue paths with no additional tiers configuration
        apiKey: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx',
        // Api key is required so SDK can store and access data related to Revenue Path configuration 
    });

    const {
      updateLimits,
      addRevenueTier
    } = useUpdateRevenuePath();
    
    const updateLimitsBtn = () => {
      updateLimits(updateLimitsArgs);
    };
    const addRevenueTierBtn = () => {
      addRevenueTier(addRevenueTierArgs);
    };

    return (
        <>
          <button onClick={updateLimitsBtn}>Update Tier Limits</button>
          <button onClick={updateLimitsBtn}>Add New Tier</button>
        </>
    );
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.r3vl.xyz/reveel-protocol-v2-documentation/sdk/1.0-react-hooks.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
