A Comprehensive Guide to Using the OKX Connect UI Package

·

The @okxconnect/ui package is an essential tool for developers looking to seamlessly integrate OKX wallet connectivity into their decentralized applications (DApps). This powerful npm package simplifies the process of connecting to wallets, handling transactions, and managing user sessions, all while providing a customizable user interface.

This guide will walk you through everything you need to know to get started, from installation and initialization to advanced features and error handling.

Getting Started with Installation

To begin integrating OKX Connect into your DApp, you first need to install the package via npm. Ensure you have Node.js and npm installed on your system before proceeding.

Open your terminal and run the following command:

npm install @okxconnect/ui

This command fetches the latest version of the package and adds it to your project's dependencies. It's recommended to use version 1.8.7 or later for access to the latest features and improvements.

Initializing the Connect UI

Before you can connect to a wallet or send transactions, you need to initialize the OKXUniversalConnectUI object. This setup configures essential parameters such as your DApp's metadata, user interface preferences, and language settings.

The initialization function requires several parameters:

Here is a basic example of how to initialize the UI:

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

const universalUi = await OKXUniversalConnectUI.init({
  DAppMetaData: {
    icon: "https://your-dapp.com/icon.png",
    name: "Your DApp Name"
  },
  actionsConfiguration: {
    returnStrategy: 'tg://resolve',
    modals: 'all',
    tmaReturnUrl: 'back'
  },
  language: "en_US",
  uiPreferences: {
    theme: THEME.LIGHT
  },
  restoreConnection: true
});

Connecting to a User's Wallet

The primary function of this package is to establish a connection between your DApp and a user's crypto wallet. The openModal method triggers the connection interface, allowing users to select and approve a wallet connection.

This method requires you to define the blockchain namespaces and chains your DApp supports. For Ethereum Virtual Machine (EVM) systems, the namespace key is eip155.

Key Parameters for openModal:

Example Connection Request:

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

A successful connection returns a session object containing the session topic, connected accounts, supported methods, and chain information.

👉 Explore more strategies for wallet connection

Connecting and Signing in One Step

For a more streamlined user experience, you can combine the connection and signing processes into a single step using the openModalAndSign method. This is ideal for actions that require immediate user authorization, like signing a message upon first connect.

This method uses the same connectParams as openModal but adds a signRequest parameter, which is an array containing the signing method (e.g., personal_sign), the chain ID, and the parameters for the signature.

Example of Connection with Signing:

// First, set up a listener for the signature response
universalUi.on("connect_signResponse", (signResponse) => {
  console.log("Signature received:", signResponse);
});

var session = await universalUi.openModalAndSign(
  {
    namespaces: {
      eip155: {
        chains: ["eip155:1", "eip155:137"],
        defaultChain: "1",
        rpcMap: { "137": "https://polygon.drpc.org" }
      }
    },
    optionalNamespaces: {
      eip155: {
        chains: ["eip155:43114"]
      }
    }
  },
  [{
    method: "personal_sign",
    chainId: "eip155:1",
    params: ["0x4d7920656d61696c206973...", "0x4B0897b0513FdBeEc7C469D9aF4fA6C0752aBea7"],
  }]
);

Sending Transactions and Requests

Once connected, you can send various requests to the wallet, such as signing messages or sending transactions, using the request method. This method is highly flexible and allows you to specify the exact chain and configure modal behaviors for each request.

Structure of a Request:

let result = await universalUi.request(
  {
    method: "personal_sign",
    params: ["0x506c65617365207369676e...", "0x4B0897b0513FdBeEc7C469D9aF4fA6C0752aBea7"]
  },
  "eip155:1", // Chain ID
  { modals: 'all' } // Action configuration
);

Advanced RPC Configuration and Usage

For advanced operations beyond standard wallet methods, you can leverage the RPC configuration specified in your rpcMap during connection. This allows you to directly query blockchain data, such as fetching transaction details.

Example RPC Query:

let rpcData = {
  method: "eth_getTransactionByHash",
  params: ["0xd62fa4ea3cf7ee3bf6f5302b764490730186ed6a567c283517e8cb3c36142e1a"],
};
let transactionDetails = await universalUi.request(rpcData, "eip155:137");

Managing Sessions and UI

The package provides robust methods for managing the user session and interface:

Handling Events

The SDK emits various events that you can listen to for handling different states and user actions:

Understanding Error Codes

Proper error handling is crucial for a smooth user experience. The package defines a set of clear error codes for common issues:

Error CodeDescription
UNKNOWN_ERRORAn unexpected error occurred.
ALREADY_CONNECTED_ERRORA wallet connection already exists.
NOT_CONNECTED_ERRORAttempted an operation without an active wallet connection.
USER_REJECTS_ERRORThe user rejected the connection or transaction request.
METHOD_NOT_SUPPORTEDThe requested wallet method is not supported.
CHAIN_NOT_SUPPORTEDThe requested blockchain chain is not supported by the wallet.
WALLET_NOT_SUPPORTEDThe connected wallet does not support the required functionality.
CONNECTION_ERRORA general error occurred during the connection process.

Frequently Asked Questions

What is the primary use of the @okxconnect/ui package?
This npm package provides a pre-built UI component and SDK for DApp developers to easily integrate OKX wallet connectivity. It handles the complexities of connecting to wallets, managing user sessions, signing messages, and sending transactions through a simple and customizable interface.

How do I handle a user rejecting a connection request?
The SDK will throw a USER_REJECTS_ERROR (code 300) if a user rejects a connection or signature request. Your application should catch this error and handle it gracefully, for example, by displaying a friendly message to the user informing them that the action was cancelled.

Can I customize the appearance of the connection modal?
Yes, but the customization options are primarily limited to choosing between light and dark themes (THEME.LIGHT or THEME.DARK) and setting your DApp's name and icon during the initialization phase. More extensive UI modifications require working with the underlying SDK logic.

What is the difference between namespaces and optionalNamespaces?
namespaces define the essential blockchains and chains that your DApp must have access to in order to function. If the user's wallet doesn't support any of these, the connection will fail. optionalNamespaces define chains that are nice to have but not required; the connection will succeed even if they are unsupported.

How can I interact with a custom EVM network or a testnet?
To interact with a custom network, you must include its chain ID in the optionalNamespaces parameter and provide its RPC URL in the rpcMap object during the connection process (openModal or openModalAndSign). If the wallet doesn't recognize the chain, you may need to prompt the user to add it manually using the wallet_addEthereumChain method after connecting.

My DApp is inside Telegram. Are there special configurations?
Yes, for Telegram Mini Apps (TMA), you should configure the returnStrategy and tmaReturnUrl parameters in the actionsConfiguration object during init. A common configuration is returnStrategy: 'tg://resolve' and tmaReturnUrl: 'back', which ensures the user returns to your Mini App after closing the wallet.