@okxconnect/ui: Integrate Wallet Connectivity into Your DApp

·

Integrating blockchain wallet functionality into decentralized applications (DApps) has become a critical requirement for Web3 developers. The @okxconnect/ui SDK simplifies this process by offering a robust, user-friendly interface to connect, authenticate, and interact with wallets—especially within the OKX ecosystem. Whether you're building on Ethereum, Polygon, Avalanche, or other EVM-compatible chains, this tool streamlines key operations such as wallet connection, transaction signing, and session management.

This guide walks you through the full integration workflow of @okxconnect/ui, covering installation, initialization, core methods, event handling, and best practices—all while maintaining SEO-friendly content structure and readability.


Install @okxconnect/ui via npm

To begin integrating wallet connectivity into your DApp, install the package using npm:

npm install @okxconnect/ui

This lightweight SDK provides a modular API for connecting to OKX Wallet and managing user sessions seamlessly across platforms, including mobile apps and Telegram Mini Apps.

👉 Discover how easy it is to integrate secure wallet access today.


Initialize the SDK

Before establishing a wallet connection, initialize the SDK with metadata about your DApp:

import { OKXUniversalConnectUI } from "@okxconnect/ui";

const universalUi = await OKXUniversalConnectUI.init({
  DAppMetaData: {
    name: "My Web3 App",
    icon: "https://example.com/icon-180x180.png" // PNG recommended, 180x180px
  },
  actionsConfiguration: {
    returnStrategy: 'tg://resolve', // For deep linking in Telegram
    modals: 'all',
    tmaReturnUrl: 'back'
  },
  uiPreferences: {
    theme: THEME.LIGHT
  },
  language: "en_US",
  restoreConnection: true
});

Key Initialization Parameters


Connect to a Wallet

Use openModal() to prompt users to connect their wallet:

const session = await universalUi.openModal({
  namespaces: {
    eip155: {
      chains: ["eip155:1", "eip155:137"], // Ethereum & Polygon
      defaultChain: "eip155:1",
      rpcMap: {
        "137": "https://polygon.drpc.org"
      }
    }
  },
  optionalNamespaces: {
    eip155: {
      chains: ["eip155:43114"] // Avalanche (optional)
    }
  }
});

What This Returns

The resolved promise includes:

If a requested chain isn’t supported, the connection is rejected. Optional chains allow fallback support.


Connect and Sign in One Step

For immediate data signing upon connection, use openModalAndSign():

universalUi.on("connect_signResponse", (signResponse) => {
  console.log("Signature result:", signResponse);
});

await universalUi.openModalAndSign(
  {
    namespaces: { /* same as above */ }
  },
  [
    {
      method: "personal_sign",
      chainId: "eip155:1",
      params: ["0xMessageToSign", "0xUserAddress"]
    }
  ]
);

This triggers the connect_signResponse event once the user approves or rejects the signature request.

👉 See how one-click signing improves user experience in modern DApps.


Send Transactions and Sign Messages

Use the request() method to send transactions or sign messages:

const data = {
  method: "personal_sign",
  params: [
    "0xPlease sign this message to confirm your identity.",
    "0x4B0897b0513FdBeEc7C469D9aF4fA6C0752aBea7"
  ]
};

const result = await universalUi.request(data, "eip155:1", "all");
console.log(result); // e.g., "0xe8d34297c33a61..."

You can customize modal behavior (before, success, error) and return strategies per request.


Use Custom RPCs for Advanced Queries

When standard methods aren't enough, query blockchain data directly via RPC:

const rpcData = {
  method: "eth_getTransactionByHash",
  params: ["0xd62fa4ea3cf7ee3bf6f5302b764490730186ed6a567c283517e8cb3c36142e1a"]
};

const txDetails = await universalUi.request(rpcData, "eip155:137");

Ensure the target chain is included in your initial connection configuration.


Manage Sessions and UI Settings

Check Connection Status

const isConnected = universalUi.isConnected();

Returns true if currently connected.

Get Current Session Info

Retrieve active session details like accounts, chains, and methods.

Change Theme or Language Dynamically

universalUi.uiOptions = {
  language: 'zh_CN',
  uiPreferences: { theme: THEME.DARK }
};

Supports real-time UI updates without reinitialization.

Set Default Chain

universalUi.setDefaultChain('eip155:1'); // Switch to Ethereum

Ensures operations default to the correct network when multiple chains are available.


Disconnect and Clean Up

To end a session:

await universalUi.disconnect();

This triggers the session_delete event and clears local session data.

Also remove event listeners when no longer needed:

const unsubscribe = universalUi.onModalStateChange((state) => { /* handle */ });
unsubscribe(); // Clean up

Handle Events for Real-Time Feedback

Listen to important lifecycle events:

universalUi.on("display_uri", (uri) => {
  console.log("Connect URI:", uri);
});

universalUi.on("session_update", (session) => {
  console.log("Session updated:", session);
});

universalUi.on("session_delete", ({ topic }) => {
  console.log("Disconnected from session:", topic);
});

universalUi.on("accountChanged", (session) => {
  console.log("Account changed:", session);
});

These enable responsive UI updates based on user actions.


Error Handling Guide

Common error codes include:

Always wrap calls in try-catch blocks and display user-friendly messages.


Frequently Asked Questions (FAQ)

Q: What wallets does @okxconnect/ui support?
A: It primarily integrates with OKX Wallet (version 6.90.1+), supporting both mobile and Telegram Mini App environments.

Q: Can I connect to non-EVM blockchains?
A: Currently, only EVM-compatible chains (via eip155) are supported. Support for other standards may be added in future versions.

Q: How do I add a custom network?
A: Include it in optionalNamespaces. If not recognized, use wallet_addEthereumChain via the request() method after connection.

Q: Is automatic reconnection possible?
A: Yes—set restoreConnection: true during initialization to resume previous sessions on page reload.

Q: What languages are supported?
A: Over 15 languages including English (en_US), Chinese (zh_CN), Spanish (es_ES), French (fr_FR), Arabic (ar_AE), and more.

Q: How do I handle deep linking in Telegram Mini Apps?
A: Configure returnStrategy: 'tg://resolve' and tmaReturnUrl: 'back' to ensure smooth navigation after signing.


👉 Start integrating seamless wallet connectivity with just a few lines of code.