Integrating a wallet into your decentralized application (DApp) on the Cosmos network is a fundamental step for enabling user interactions, from simple connections to complex transaction signing. This guide provides a detailed walkthrough of the essential processes, including installation, connection management, transaction preparation, and error handling, ensuring a seamless experience for both developers and end-users.
Installation and Initialization
To begin integrating wallet connectivity into your DApp, ensure you are using version 6.94.0 or later of the necessary SDK. The integration process typically starts with using npm for package management.
Before establishing a connection, you must create an object that will handle subsequent operations, such as connecting to the wallet and sending transactions.
Key Request Parameters
dappMetaData: An object containing metadata about your application.name: A string representing the application's name. Note that this is not used as a unique identifier.icon: A URL pointing to the application's icon. Supported formats include PNG and ICO, but SVG is not supported. For optimal results, use a URL that points to a 180x180px PNG icon.
Return Value
OKXUniversalProvider: The initialized provider object for further operations.
Example Usage
After installing the required package, initialize the provider with your DApp's metadata to prepare for wallet connections.
Connecting to a Wallet
Establishing a connection to a wallet allows you to retrieve the wallet address, which serves as a unique identifier, and obtain necessary parameters for signing transactions.
Request Parameters
connectParams: An object of typeConnectParamscontaining:namespaces: Optional information about the requested connection. For the Cosmos system, the key is 'cosmos'. The wallet will reject the connection if any requested chains are unsupported.chains: An array of chain IDs.defaultChain: (Optional) The default chain for the connection.
optionalNamespaces: Additional optional connection information. If chains are unsupported, the connection may still proceed.chains: An array of chain IDs.defaultChain: (Optional) The default chain.
sessionConfig: Configuration for the session.redirect: A URL to redirect to after a successful connection. For Mini Apps in Telegram, this can be set to a Telegram deep link (e.g., 'tg://resolve').
Return Value
A promise resolving to an object containing:
topic: A session identifier string.namespaces: Record of namespace information for the connection.chains: Array of connected chain information.accounts: Array of account details.methods: Array of methods supported by the wallet.defaultChain: (Optional) The default chain for the session.sessionConfig: Session configuration details.dappInfo: Information about the DApp, including name, icon, and optional redirect URL.
Example Workflow
Initiate the connection process by calling the connect method with the required parameters. Handle the promise to manage successful connections or errors.
Checking Wallet Connection Status
Determining whether a wallet is currently connected is crucial for managing user sessions and ensuring seamless interactions.
Return Value
- A boolean value:
trueif connected,falseotherwise.
Implementation Example
Use a simple method call to check the connection status and update your application's state accordingly.
Preparing Transactions
To prepare transactions, first create an OKXCosmosProvider object by passing the OKXUniversalProvider instance into its constructor. This step is essential for handling Cosmos-specific operations.
Retrieving Account Information
Fetching account details is a common requirement for displaying user-specific data or preparing transactions.
Request Parameters
chainId: The chain identifier for the request (e.g., 'cosmos:cosmoshub-4', 'cosmos:osmosis-1').
Return Value
An object containing:
algo: The algorithm used, typically 'secp256k1'.address: The wallet address.bech32Address: The Bech32-encoded wallet address.pubKey: The public key as a Uint8Array.
Example Usage
Call the account information method with the appropriate chain ID to retrieve and display user account details.
Signing Messages
Message signing is vital for authentication and verifying user actions.
Request Parameters
chain: The chain where the signing method is executed.signerAddress: The address of the wallet performing the signature.message: The message to be signed.
Return Value
A promise resolving to an object with:
pub_key: Public key details, including type and value.signature: The resulting signature string.
Step-by-Step Process
Invoke the sign method with the required parameters, handle the promise, and use the signature for further verification processes.
Using SignAmino for Transaction Signing
The SignAmino method is used for signing transactions in a format compatible with Cosmos SDK's Amino encoding.
Request Parameters
chainId: The chain identifier for the signature request.signerAddress: The wallet address.signDoc: The transaction information object in a fixed format, similar to cosmjs OfflineSigner's signAmino method.
Return Value
A promise resolving to an object containing:
signed: The signed transaction information.signature: The signature result.
Implementation Example
Ensure the signDoc is properly formatted before calling the SignAmino method to avoid errors.
Using SignDirect for Transaction Signing
SignDirect is used for signing transactions directly, providing a different approach compared to SignAmino.
Request Parameters
chainId: The chain identifier.signerAddress: The wallet address.signDoc: An object containing:bodyBytes: Uint8Array of the transaction body.authInfoBytes: Uint8Array of the authorization information.chainId: The chain identifier string.accountNumber: The account number string.
Return Value
A promise resolving to an object with:
signed: The signed transaction data.signature: The signature result.
Best Practices
Validate all parameters before initiating the SignDirect process to ensure transaction integrity.
Disconnecting the Wallet
Disconnecting a wallet removes the current session and is necessary when switching wallets or ending user sessions.
Procedure
Call the disconnect method to terminate the connection and clear session data. Always disconnect before attempting to connect a different wallet.
Handling Events
Events are crucial for managing real-time updates and user interactions within your DApp. Implement event listeners to handle connection changes, transaction statuses, and other relevant actions.
Understanding Error Codes
Various exceptions may be thrown during connection, transaction, or disconnection processes. Understanding these errors helps in debugging and providing user feedback.
Common Error Codes
OKX_CONNECT_ERROR_CODES.UNKNOWN_ERROR: An unspecified error occurred.OKX_CONNECT_ERROR_CODES.ALREADY_CONNECTED_ERROR: The wallet is already connected.OKX_CONNECT_ERROR_CODES.NOT_CONNECTED_ERROR: The wallet is not connected.OKX_CONNECT_ERROR_CODES.USER_REJECTS_ERROR: The user rejected the request.OKX_CONNECT_ERROR_CODES.METHOD_NOT_SUPPORTED: The method is not supported by the wallet.OKX_CONNECT_ERROR_CODES.CHAIN_NOT_SUPPORTED: The chain is not supported.OKX_CONNECT_ERROR_CODES.WALLET_NOT_SUPPORTED: The wallet is not supported.OKX_CONNECT_ERROR_CODES.CONNECTION_ERROR: A general connection error occurred.
Error Handling Tips
Implement try-catch blocks around critical operations to gracefully handle these errors and inform users appropriately.
Frequently Asked Questions
What is the minimum SDK version required for integration?
You need to use version 6.94.0 or later to ensure compatibility with all features described in this guide. Older versions may lack support for newer methods or security updates.
How do I handle unsupported chains during connection?
If a chain is not supported, the wallet may reject the connection. Use optionalNamespaces for chains that are not critical, allowing the connection to proceed even if some chains are unsupported.
What should I do if a user rejects a connection request?
Handle the USER_REJECTS_ERROR gracefully by informing the user and providing options to retry or cancel the operation. Ensure your UI remains user-friendly despite rejections.
Can I use SVG icons for my DApp's metadata?
No, SVG icons are not supported. You must use PNG or ICO formats, with a recommended size of 180x180px for the best display results.
How do I switch between connected wallets?
Always disconnect the current wallet first using the disconnect method. Then, initiate a new connection process for the desired wallet.
What is the difference between SignAmino and SignDirect?
SignAmino uses Amino encoding for transaction signing, while SignDirect signs transactions directly. Choose based on your DApp's requirements and the wallet's supported methods.
👉 Explore advanced integration techniques
By following this guide, you can efficiently integrate wallet connectivity into your Cosmos-based DApp, ensuring a robust and user-friendly experience. Always refer to the latest documentation for updates and additional features.