Integrating a secure and user-friendly wallet connection is a crucial step for any decentralized application (DApp) operating on the Solana blockchain or its compatible chains, such as Sonic. This guide provides a detailed overview of utilizing a provided UI interface to connect your DApp to various wallet options, including mobile app wallets and mini-wallets within platforms like Telegram. By leveraging this UI, you can offer users a seamless experience for authentication, transaction signing, and account management without compromising on security or functionality.
Installation and Initialization
To begin the integration process, ensure you have the necessary tools updated. The first step involves installing the required package via npm.
npm install @okx/web3-connectBefore initiating any wallet connection, you must create a configuration object. This object will manage the UI for operations like connecting wallets and sending transactions. The initialization requires specific parameters to tailor the experience to your DApp.
Key Configuration Parameters
dappMetaData (object): Contains metadata about your DApp.
name(string): The name of your application. Note that this is for display purposes and not a unique identifier.icon(string): A URL pointing to your application's icon. The image must be in a format like PNG or ICO (SVG is not supported). For optimal display, use a 180x180px PNG image.
actionsConfiguration (object): Configures how certain actions are handled.
modals(array or string): Defines when to display alert modals during transactions. Options are'before','success','error', or'all'. The default is'before'.returnStrategy(string): For app wallets, this defines the deep link strategy after a user signs or rejects a request. Use'none'or a custom schema liketg://resolve.tmaReturnUrl(string): Specifically for Telegram Mini App wallets, this sets the return strategy. Use'back'to close the wallet and return to the DApp,'none'for no action, or a custom deep link. The default is'back'.
uiPreferences (object): Controls the visual aspects of the UI.
theme: Sets the color theme. Options includeTHEME.DARK,THEME.LIGHT, or'SYSTEM'to match the user's device settings.language: Sets the UI language. Supports numerous locales like'en_US','zh_CN','es_ES', etc. Defaults to'en_US'.
Return Value
The initialization function returns an OKXUniversalConnectUI object, which serves as your main interface for all subsequent wallet operations.
Connecting to a Wallet
The primary function is to establish a connection between your DApp and a user's wallet. This process retrieves the wallet address, which acts as a user identifier, and other parameters necessary for signing transactions.
Connection Parameters (connectParams)
You must define the blockchain namespaces your DApp requires to function. For Solana and compatible chains, the namespace key is 'solana'.
namespaces (object): Essential chains your DApp needs. If the wallet does not support any of these, the connection will be rejected.
chains(string[]): An array of chain IDs (e.g.,['solana:mainnet']).defaultChain(string, optional): The default chain ID to use.
optionalNamespaces (object): Additional chains your DApp can use but does not require. If these are unsupported, the connection will still proceed.
chains(string[]): An array of optional chain IDs.defaultChain(string, optional): The default chain ID for this optional namespace.
Return Value
The connect function returns a Promise that resolves to a session object containing:
topic: A unique session identifier.namespaces: Details of the successfully connected namespaces.accounts: The connected wallet addresses.methods: The list of wallet methods supported in the current session.dappInfo: The DApp metadata you provided during initialization.
Connecting and Signing in a Single Request
For a more streamlined user experience, you can combine the connection and signing processes into a single request. The result of the signature request is handled via a specific event callback.
Request Parameters
This method uses the same connectParams detailed above for establishing the connection. Additionally, it requires a signRequest parameter.
signRequest (array): An array containing a single signing request object.
method(string): The signing method to call (e.g.,'solana_signMessage').chainId(string): The chain ID on which to execute the method. This must be one of the chains requested inconnectParams.params(array/object): The parameters required by the specific signing method.
The return value is the same session object as the standard connect method. The signature result itself is delivered via the 'connect_signResponse' event.
Checking Wallet Connection Status
You can easily check if a wallet is currently connected to your DApp. This is useful for conditionally rendering UI elements.
Method and Return Value
Call the .connected() method on your UI instance. It returns a simple boolean value (true or false) indicating the connection status.
Preparing and Sending Transactions
Once connected, you can create a provider object specifically for Solana operations. This provider, when called, will handle triggering the UI modals for signing based on your initial actionsConfiguration settings.
Signing Messages and Transactions
The core functionality allows users to sign data and authorize transactions directly from your DApp's interface.
Signing a Message
Parameters:
message(string): The message data to be signed.chain(string): The chain ID for the request. This is mandatory when multiple chains are connected.
- Returns: A Promise resolving to an object containing the
publicKeyand thesignature(as a Uint8Array).
Signing a Single Transaction
Parameters:
transaction(Transaction | VersionedTransaction): The Solana transaction object to sign.chain(string): The relevant chain ID.
- Returns: A Promise resolving to the signed transaction object.
๐ Explore advanced transaction signing methods
Signing Multiple Transactions
Parameters:
transactions(array): An array of transaction objects to sign.chain(string): The relevant chain ID.
- Returns: A Promise resolving to an array of signed transaction objects.
Signing and Broadcasting a Transaction
This method handles both signing the transaction and immediately broadcasting it to the blockchain.
- Parameters: (Same as signing a single transaction).
- Returns: A Promise resolving to the
transactionHashstring of the broadcasted transaction.
Retrieving Wallet Account Information
You can fetch the active wallet account information for the connected session.
Parameters and Return Value
- Parameters:
chain(string, optional): The chain ID to query. If omitted, the first connected SVM (Solana Virtual Machine) address is used. - Returns: An object containing the wallet's
address(string) andpublicKey.
Disconnecting a Wallet
To end the current session, perhaps to allow a user to switch wallets, you must explicitly disconnect. This function disconnects the wallet and deletes the current session data.
Handling Events and Errors
The UI integration emits various events to help you manage the application state, such as session updates and request responses. Error handling follows standardized codes, providing clear feedback for issues like rejected connection requests or failed transactions. For a detailed list of events and error codes, you can refer to the documentation for EVM-compatible chains, as the patterns and codes are consistent across different blockchain integrations.
Frequently Asked Questions
What is the difference between namespaces and optionalNamespaces?namespaces define the essential blockchains your DApp requires to function. If a wallet doesn't support one of these chains, the connection will fail. optionalNamespaces define additional chains your DApp can utilize for enhanced functionality, but their absence won't prevent a successful connection.
How do I handle users rejecting a signature request?
The process is managed through the event system. A rejected request will trigger an error event. Your application should listen for these events and update the UI accordingly to inform the user that the action was cancelled or failed.
Can I customize the appearance of the connection UI?
Yes, to a significant degree. During initialization, you can set the theme (dark, light, or system) and the language of the UI elements. However, extensive branding or layout changes beyond these preferences are not supported through the basic UI configuration.
What happens if a user's wallet is not updated?
For the best experience, users should have the latest version of their wallet app. If a wallet is outdated and lacks support for the methods or chains your DApp requests, the connection may fail or certain features might be unavailable. It's good practice to guide users to update their wallets if necessary.
Is it possible to connect to multiple wallets simultaneously?
The typical workflow involves managing a single active wallet connection per session. To switch wallets, you should first disconnect the current wallet using the disconnect method before initiating a new connection request.
How do I specify which chain to use for an operation if multiple are connected?
Most methods, like signMessage or signTransaction, accept a chain parameter. You must pass the specific chain ID for the chain you want the operation to execute on. This is mandatory when a user has connected multiple chains to your DApp.