Integrating a TON wallet into your decentralized application (DApp) is a crucial step for enabling blockchain interactions. This guide provides a comprehensive overview of the SDK installation, connection processes, and key functionalities for seamless wallet integration.
Whether you are building a new DApp or enhancing an existing one, understanding these procedures will help you create a smooth user experience. The following sections break down each step in detail.
SDK Installation Methods
You can install the necessary SDK using one of two primary methods: via a CDN or through npm. The choice depends on your project's requirements and development environment.
Using a CDN for Installation
For quick setup, include the following script tag in your HTML file. You can specify a version number or use "latest" for the most recent release.
<script src="https://sdk.web3.okx.com/ton-connect/latest/tonconnect.js"></script>After adding the script, the SDK becomes available as a global object. You can then create a connector instance to start integrating wallet functionalities.
const connector = new OKXTonConnectSDK.OKXTonConnect();Installation via npm
For projects managed with npm, install the package using the command line. This method is ideal for applications built with modern JavaScript frameworks.
npm install @okx/web3-connectorOnce installed, import and initialize the connector in your application code to begin the integration process.
Initializing the SDK
Before connecting to a wallet, you must create an instance of the SDK. This setup requires basic metadata about your application to identify it within the wallet interface.
Required Parameters
metaData: An object containing application details.
- name: A string representing your application's name (does not need to be unique).
- icon: A URL pointing to your application's icon (recommended format: 180x180px PNG).
Return Value
The initialization function returns an okxTonConnect instance, which serves as the primary interface for all subsequent wallet operations.
Example Code Snippet
const tonConnect = new OKXTonConnect({
metaData: {
name: "My DApp",
icon: "https://example.com/icon.png"
}
});Establishing a Wallet Connection
The connection process allows your DApp to retrieve the user's wallet address and necessary parameters for transaction signing. This step is essential for any blockchain interaction.
Connection Request Parameters
request: An optional object for customizing the connection behavior.
- tonProof: Optional signature information.
- redirect: An optional deeplink URL for redirecting users after wallet events (particularly useful in Telegram environments).
- openUniversalLink: A boolean indicating whether to open the OKX App via universal link (recommended for mobile browsers).
Return Value and Recommendations
The method returns a Promise that resolves to a connection string. On PC browsers, this string can generate a QR code for scanning with a mobile wallet. For mobile environments, setting openUniversalLink to true provides a smoother user experience.
👉 Explore more connection strategies
Managing Connection States
Maintaining and managing wallet connections is vital for user experience. The SDK provides methods to restore previous connections, check connection status, and properly disconnect wallets.
Restoring Previous Connections
If a user has previously connected their wallet, you can restore the session without requiring them to go through the full connection process again. This method enhances user convenience.
tonConnect.restoreConnection();Checking Connection Status
You can verify whether a wallet is currently connected to your DApp using the connected method. This is useful for displaying appropriate UI elements based on connection state.
Proper Disconnection Procedures
When users need to switch wallets or logout, use the disconnect method to terminate the current session gracefully. This ensures clean state management and prevents conflicts.
Transaction Handling and Operations
Sending transactions is a core functionality of wallet integration. The SDK provides a comprehensive method for constructing and sending transactions with various parameters.
Transaction Parameters
transaction: The main transaction object containing:
- validUntil: Unix timestamp for transaction expiration
- from: Optional sender address (defaults to connected wallet)
- messages: Array of output messages (1-4 messages supported)
- options: Additional options including callback functions
Message Structure
Each message in the transaction requires:
- address: Destination address
- amount: Amount to be sent
- stateInit: Optional initial state cell
- payload: Optional payload data
Return Value
The method returns a Promise that resolves to the signed transaction result in BOC format.
Monitoring Wallet State Changes
Tracking wallet state changes allows your DApp to respond dynamically to connection events, transaction statuses, and other important updates.
Status Change Callback
The onStatusChange method accepts a callback function that receives wallet information whenever the state changes. This includes details about the connected device, supported features, and account information.
Error Handling
An optional error handler can be provided to catch and process exceptions that may occur during state changes. This helps in creating robust error management systems.
Resource Management
The method returns an unsubscribe function that should be called when monitoring is no longer needed. This prevents memory leaks and optimizes performance.
Event Listening System
The SDK provides a comprehensive event system that notifies your DApp of important milestones in the wallet interaction process.
Key Events
- Connection events (started, completed, error)
- Connection restoration events
- Disconnection events
- Transaction signing events
- Error events
Implementation Example
tonConnect.on('OKX_TON_CONNECTION_COMPLETED', (data) => {
// Handle successful connection
});Account and Wallet Information
Retrieving information about connected accounts and wallets helps personalize the user experience and display relevant data within your DApp.
Account Information
The SDK provides methods to access currently connected account details, including address, chain information, and public key.
Wallet Information
You can retrieve information about the connected wallet, including its name, version, platform, and supported features. This helps in adapting functionality based on wallet capabilities.
Error Code Reference
Understanding error codes is crucial for proper exception handling and user communication. The SDK provides standardized error codes for common scenarios.
Common Error Codes
- Connection errors
- User rejection errors
- Method not supported errors
- Chain compatibility errors
- General unknown errors
Error Handling Best Practices
Implement comprehensive error handling that provides meaningful feedback to users while maintaining security and privacy standards.
Frequently Asked Questions
What is the difference between CDN and npm installation?
CDN installation is quicker for simple projects and prototypes, while npm installation is better for complex applications built with modern JavaScript frameworks. The CDN method adds the SDK as a global object, while npm allows for module imports and better integration with build tools.
How do I handle users who don't have the wallet app installed?
When openUniversalLink is set to true and the wallet app isn't installed, users are redirected to the appropriate download page. You should implement fallback mechanisms and clear instructions to guide users through the installation process.
What are the security considerations for wallet integration?
Always validate returned data, implement proper error handling, and never store sensitive information client-side. Ensure your application verifies signatures and follows security best practices for blockchain interactions.
Can I support multiple wallets simultaneously?
The SDK is designed to manage one wallet connection at a time. To switch between wallets, you must first disconnect the current wallet before initiating a new connection. Each connection maintains its own session state.
How do I test the integration during development?
Use testnet environments and demo applications to verify your implementation. Most wallets provide testnet versions that allow you to experiment without using real assets. Implement comprehensive logging for debugging purposes.
What happens if a transaction fails or is rejected?
The SDK provides specific error codes for failed transactions. Your application should handle these scenarios by providing clear feedback to users and offering options to retry or cancel the operation. Always implement timeout mechanisms for transaction requests.