# Advanced Usage

## Using Hooks Independently

You can use the SDK hooks independently without the full widget UI.

### useQuote - Generate Payment Quotes

{% code title="useQuote example.tsx" %}

```typescript
import { useQuote } from '@ordanetwork/sdk/react';

function QuoteExample() {
  const { quote, isLoading, error, requestQuote } = useQuote();

  const getQuote = async () => {
    const result = await requestQuote({
      fromChainId: '1',        // Ethereum
      toChainId: '137',        // Polygon
      fromTokenAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
      toTokenAddress: '0xc2132D05D31c914a87C6611C10748AEb04B58e8F',   // USDT
      amount: '100',           // 100 USDC
      fromAddress: '0x...',    // User wallet
    });

    console.log('Quote:', result);
  };

  return (
    <div>
      <button onClick={getQuote} disabled={isLoading}>
        {isLoading ? 'Loading...' : 'Get Quote'}
      </button>
      {quote && (
        <div>
          <p>You will receive: {quote.toAmount} {quote.toToken.symbol}</p>
          <p>Fee: {quote.fee}</p>
        </div>
      )}
    </div>
  );
}
```

{% endcode %}

***

### useTransaction - Monitor Transaction Status

{% code title="useTransaction example.tsx" %}

```typescript
import { useTransaction } from '@ordanetwork/sdk/react';

function TransactionStatus({ txId }: { txId: string }) {
  const { status, isLoading, waitForCompletion } = useTransaction();

  useEffect(() => {
    if (txId) {
      // Poll for transaction completion
      waitForCompletion(txId, {
        interval: 2000,    // Check every 2 seconds
        timeout: 300000,   // Timeout after 5 minutes
      }).then((finalStatus) => {
        console.log('Transaction complete:', finalStatus);
      });
    }
  }, [txId, waitForCompletion]);

  return (
    <div>
      {status && (
        <div>
          <p>Status: {status.status}</p>
          <p>Progress: {status.completionPercentage}%</p>
        </div>
      )}
    </div>
  );
}
```

{% endcode %}

***

### useTokenPrices - Fetch USD Prices

{% code title="useTokenPrices example.tsx" %}

```typescript
import { useTokenPrices } from '@ordanetwork/sdk/react';

function TokenPrices() {
  const { prices, isLoading, error } = useTokenPrices([
    { address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', chainId: '1' }, // USDC
    { address: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', chainId: '1' }, // WETH
  ]);

  if (isLoading) return <div>Loading prices...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      {prices.map((price) => (
        <div key={price.address}>
          <p>{price.symbol}: ${price.usdPrice}</p>
        </div>
      ))}
    </div>
  );
}
```

{% endcode %}

***

### useBalances - Fetch Wallet Balances

{% code title="useBalances example.tsx" %}

```typescript
import { useBalances } from '@ordanetwork/sdk/react';
import { useAccount } from 'wagmi';

function WalletBalances() {
  const { address } = useAccount();
  const { data, isLoading, error } = useBalances(address, {
    chainIds: ['1', '137', '42161'], // Ethereum, Polygon, Arbitrum
    filter: 'known', // Only show known tokens
  });

  if (isLoading) return <div>Loading balances...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      {data?.balances.map((balance) => (
        <div key={`${balance.chainId}-${balance.address}`}>
          <p>
            {balance.symbol}: {balance.formatted} (${balance.usdValue})
          </p>
        </div>
      ))}
    </div>
  );
}
```

{% endcode %}

***

## Accessing the SDK Instance

Access the core SDK instance for direct API calls:

{% code title="useOrdaSDK example.tsx" %}

```typescript
import { useOrdaSDK } from '@ordanetwork/sdk/react';

function CustomComponent() {
  const { sdk, isLoading, error } = useOrdaSDK();

  useEffect(() => {
    if (sdk) {
      // Direct SDK access
      sdk.quote.request({ /* params */ })
        .then((quote) => console.log('Quote:', quote));
    }
  }, [sdk]);

  if (isLoading) return <div>Initializing SDK...</div>;
  if (error) return <div>SDK Error: {error.message}</div>;

  return <div>SDK Ready!</div>;
}
```

{% endcode %}

***

## Using UI Components Separately

All UI components can be used independently:

{% code title="UI components example.tsx" %}

```typescript
import { Button, Dialog, Input } from '@ordanetwork/sdk/react';

function CustomForm() {
  return (
    <Dialog>
      <DialogTrigger asChild>
        <Button variant="default">Open Form</Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Enter Amount</DialogTitle>
        </DialogHeader>
        <Input type="number" placeholder="0.00" />
        <Button>Submit</Button>
      </DialogContent>
    </Dialog>
  );
}
```

{% endcode %}

***

### OrdaProvider Configuration

The `OrdaProvider` component accepts a `config` prop with the following options:

```typescript
interface OrdaProviderConfig {
  /**
   * Async function that fetches a JWT token from your backend.
   * Called on initialization and automatically before token expiration.
   *
   * @returns Promise resolving to { jwt: string, expiresAt: number }
   */
  getToken: () => Promise<TokenResponse>;

  /**
   * AppKit configuration for wallet connections.
   * Create using createAppKitConfig().
   */
  appKitConfig: AppKitConfig;

  /**
   * Enable debug mode for development.
   * Logs SDK initialization, token refresh, and request details.
   *
   * @default false
   */
  debug?: boolean;
}

interface TokenResponse {
  jwt: string;      // JWT token string
  expiresAt: number; // Unix timestamp in seconds
}
```

### AppKit Configuration

The `createAppKitConfig` function creates a wallet connection configuration:

```typescript
interface AppKitFactoryConfig {
  /**
   * WalletConnect Project ID from cloud.reown.com
   * Required for wallet connections.
   */
  projectId: string;

  /**
   * Optional metadata for wallet connection UI
   */
  metadata?: {
    name?: string;        // App name (default: 'orda Widget')
    description?: string; // App description
    url?: string;         // App URL (default: 'https://orda.network')
    icons?: string[];     // App icon URLs
  };
}
```

Example with custom metadata:

```typescript
const appKitConfig = createAppKitConfig({
  projectId: process.env.NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID!,
  metadata: {
    name: 'My DeFi App',
    description: 'Multi-chain payment platform',
    url: 'https://mydefiapp.com',
    icons: ['https://mydefiapp.com/logo.png'],
  },
});
```


---

# 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.orda.network/developers/widget-beta/advanced-usage.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.
