Integrating wallet connectivity is a fundamental step for any decentralized application (DApp) operating within the Web3 ecosystem. This guide provides a comprehensive overview of the technical process for establishing a secure and functional link between your DApp and user wallets, specifically for chains within the Cosmos network.
Installation and Initial Setup
To begin the integration process, developers must first install and initialize the necessary connection library. This is typically done via a package manager like npm.
Before initiating any wallet connection, you must create a UI controller object. This object will manage the subsequent processes of connecting to a wallet and sending transaction requests.
Request Parameters
dappMetaData - object: Contains metadata about your DApp.
- name - string: The name of your application. Note that this is not used as a unique identifier.
- icon - string: A URL pointing to your application's icon. The image must be in a supported format like PNG or ICO (SVG is not supported). A 180x180px PNG is recommended for optimal display.
actionsConfiguration - object: Configures the behavior of modal prompts and return strategies.
- modals - ('before' | 'success' | 'error')[] | 'all': Defines which modal interfaces are shown during a transaction process. The default is 'before'.
- returnStrategy - string 'none' |
${string}://${string}: For in-app wallets, this specifies the deep link return strategy after a user signs or rejects a request. For instance, within Telegram, you might configure this astg://resolve. - tmaReturnUrl - string 'back' | 'none' |
${string}://${string}: Specifically for the Telegram Mini Wallet, this sets the return strategy. Use 'back' to close the wallet and return to the DApp after signing, 'none' to take no action, or a custom deep link. The default is 'back'.
uiPreferences - object: Customizes the user interface.
- theme - Can be:
THEME.DARK,THEME.LIGHT, or"SYSTEM".
- theme - Can be:
- language - string: Sets the interface language. Options include "en_US", "zh_CN", "ru_RU", and several others. The default is "en_US".
Return Value
- OKXUniversalConnectUI: The initialized UI controller object.
Example Code Snippet
Establishing a Wallet Connection
The core function of this integration is to connect a user's wallet to your DApp. This process retrieves the wallet address, which acts as a unique identifier and is essential for signing transactions.
Request Parameters
connectParams - ConnectParams: The parameters for the connection request.
namespaces -
[namespace: string]: ConnectNamespace: Essential information for the connection request. For Cosmos-based chains, the key is"cosmos". If the wallet does not support any of the requested chains, the connection will be rejected.- chains: string[]: An array of specific Chain ID information.
- defaultChain?: string: The default chain to use.
optionalNamespaces -
[namespace: string]: ConnectNamespace: Optional information for the connection. If these chains are not supported, the connection may still proceed.- chains: string[]: An array of specific Chain ID information.
- defaultChain?: string: The default chain to use.
sessionConfig: object
- redirect: string: A URL or deep link to redirect to after a successful connection. For Telegram Mini Apps, this can be set to a Telegram deep link like
"tg://resolve".
- redirect: string: A URL or deep link to redirect to after a successful connection. For Telegram Mini Apps, this can be set to a Telegram deep link like
Return Value
Promise ``: A promise that resolves to the session object.
- topic: string: A unique session identifier.
- namespaces:
Record: Information about the successfully connected namespaces. - chains: string[]: An array of the connected chain IDs.
- accounts: string[]: An array of the connected account addresses.
- methods: string[]: An array of methods supported by the wallet for the current namespace.
- defaultChain?: string: The default chain for the current session.
- sessionConfig?: SessionConfig
dappInfo: object: Information about your DApp.
- name: string
- icon: string
- redirect?: string: The post-connection redirect parameter.
Example Code Snippet
๐ Explore more connection strategies
Connecting a Wallet and Requesting a Signature
This method combines the wallet connection process with an immediate request to sign a piece of data. The signature result is returned via a "connect_signResponse" event callback.
Request Parameters
- connectParams - ConnectParams: The standard connection parameters as described above.
signRequest - RequestParams[]: An array containing the signature request. Note that only one method can be requested at a time.
- method: string: The name of the method to be called. For Cosmos, a supported method is
"cosmos_signArbitrary". - chainId: string: The Chain ID where the method should be executed. This must be one of the chains listed in the
namespacesparameter. - params: unknown[] | Record `` | object | undefined: The parameters required by the specified method.
- method: string: The name of the method to be called. For Cosmos, a supported method is
Return Value
- Promise ``: A promise that resolves to the session object, similar to the standard connection return value.
Example Code Snippet
Checking Wallet Connection Status
This utility function allows your DApp to check if a wallet is currently connected, enabling you to adjust the UI accordingly.
Return Value
- boolean: Returns
trueif a wallet is connected, otherwisefalse.
Example Code Snippet
Preparing Transactions and Account Interactions
Once a connection is established, you can create a provider object (e.g., OKXCosmosProvider) by passing the initialized okxUniversalConnectUI object to its constructor. This provider is then used for subsequent interactions like fetching account data or signing transactions.
Fetching Account Information
Retrieves public key information and addresses for the connected wallet on a specified chain.
Request Parameters
- chainId: string: The Chain ID of the network to query (e.g.,
cosmoshub-4,osmosis-1).
Return Value
Object: An object containing the account details.
- algo: "secp256k1" (The algorithm used).
- address: string: The wallet address.
- bech32Address: string: The wallet address in Bech32 format.
- pubKey: Uint8Array: The raw public key bytes.
Example Code Snippet
Signing an Arbitrary Message
Requests the connected wallet to cryptographically sign a specific message string.
Request Parameters
- chain - string: The Chain ID on which to execute the signing request.
- signerAddress - string: The address of the wallet that should sign the message.
- message - string: The plain text message that needs to be signed.
Return Value
Promise - object: A promise that resolves to the signature object.
pub_key : object
- type: string: The type of public key.
- value: string: The public key value.
- signature: string: The resulting signature.
Example Code Snippet
Signing an Amino-Based Transaction (signAmino)
This method is used to sign a transaction structured in the Amino format, commonly used in the Cosmos ecosystem.
Request Parameters
- chainId - string: The Chain ID for the transaction (required).
- signerAddress - string: The address of the signing wallet.
- signDoc - object: The transaction data object in Amino format, compatible with libraries like cosmjs.
Return Value
Promise - Object: A promise that resolves to the signed transaction object.
- signed - object: The original signed document.
- signature - object: The generated signature data.
Example Code Snippet
Signing a Direct Protocol Buffer Transaction (signDirect)
This method is used for signing transactions encoded directly using Protocol Buffers, offering a more compact representation.
Request Parameters
- chainId - string: The Chain ID for the transaction (required).
- signerAddress - string: The address of the signing wallet.
signDoc - object: The transaction data object for direct signing.
- bodyBytes: Uint8Array
- authInfoBytes: Uint8Array
- chainId: string
- accountNumber: string
Return Value
Promise - Object: A promise that resolves to the signed transaction object.
- signed - object: The signed document.
- signature - object: The signature.
Example Code Snippet
๐ Get advanced signing methods
Disconnecting a Wallet
This function severs the active connection between your DApp and the user's wallet and deletes the current session. It is a necessary step before attempting to connect a different wallet.
Handling Events
The connection interface emits various events (e.g., connect_signResponse) that your DApp can listen for to react to state changes, signature responses, and other asynchronous actions.
Common Error Codes and Handling
Be prepared to handle exceptions that may be thrown during connection, transaction signing, or disconnection.
Common Exceptions
| Error Code | Description |
|---|---|
UNKNOWN_ERROR | An unexpected, unidentified error occurred. |
ALREADY_CONNECTED_ERROR | The wallet is already connected. |
NOT_CONNECTED_ERROR | The operation failed because no wallet is connected. |
USER_REJECTS_ERROR | The user manually rejected the request. |
METHOD_NOT_SUPPORTED | The requested method is not supported by the wallet. |
CHAIN_NOT_SUPPORTED | The requested blockchain is not supported. |
WALLET_NOT_SUPPORTED | The wallet is not supported for this operation. |
CONNECTION_ERROR | A general network or connection error occurred. |
Frequently Asked Questions
What is the primary purpose of connecting a Web3 wallet to a DApp?
Connecting a wallet authenticates a user's identity on the blockchain without traditional logins. It allows the DApp to read the user's public address and, with explicit permission, request signatures to execute transactions and interact with smart contracts securely.
What is the difference between 'namespaces' and 'optionalNamespaces'?namespaces define the essential blockchains your DApp requires to function. If the user's wallet doesn't support any of these, the connection will fail. optionalNamespaces define chains your DApp can use but doesn't require. The connection will succeed even if these are unsupported, allowing for a more flexible user experience.
How should I handle a user rejecting a connection or signature request?
Your code should gracefully catch the USER_REJECTS_ERROR exception. Use this to inform the user that the action was canceled and to update your UI accordingly, for example, by re-enabling a "Connect" button without causing an application crash.
What are the key security considerations when integrating wallet connect?
Always verify the authenticity of transaction details before a user signs them. Never expose private keys. Use the returned signature on your backend to verify the message's authenticity before executing critical actions. Ensure your dappMetaData uses a secure (HTTPS) link for its icon.
Can I customize the UI language and theme for the connection prompts?
Yes, the initialization parameters include uiPreferences where you can set a preferred theme (e.g., dark, light, system) and a language code to tailor the interface for your target audience.
What should I do if I encounter a 'CHAIN_NOT_SUPPORTED' error?
This means the user's wallet is not configured for the blockchain your DApp is trying to use. Your application should guide the user, perhaps by providing instructions on how to add that specific network to their wallet or by switching to a supported chain within your DApp's interface.