Introduction to the OKX Bitcoin SDK
The OKX Bitcoin SDK provides a powerful set of tools for developers looking to integrate Bitcoin and Bitcoin-compatible chain functionality into their decentralized applications. This comprehensive solution enables seamless wallet connections, transaction processing, and secure signing operations through a well-documented API interface.
By implementing this SDK, developers can offer users a streamlined experience for managing Bitcoin assets, signing transactions, and interacting with various Bitcoin-based protocols. The SDK supports multiple namespace configurations, including both EVM-compatible chains and native Bitcoin implementations.
Installation and Initialization
To begin integrating OKX Connect into your DApp, ensure you're using version 6.92.0 or later. The installation process is straightforward using npm package management.
Before establishing wallet connections, you must first create a provider object that will handle all subsequent operations including wallet linking, transaction signing, and message transmission.
Request Parameters
dappMetaData - object
- name - string: Your application name (not used as unique identifier)
- icon - string: URL to your application icon. Must be in PNG, ICO, or similar format (SVG not supported). Recommended size is 180x180px PNG.
Return Value
- OKXUniversalProvider object instance
Implementation Example
// Example initialization code
const provider = new OKXUniversalProvider({
dappMetaData: {
name: "Your DApp Name",
icon: "https://yourdomain.com/icon.png"
}
});Connecting to Wallets
Establishing wallet connections is fundamental for obtaining wallet addresses, which serve as essential identifiers and are required for signing transactions.
okxUniversalProvider.connect(connectParams: ConnectParams);
Request Parameters
connectParams - ConnectParams
- namespaces - [namespace: string]: ConnectNamespace ; Optional connection information where EVM chains use "eip155" key and BTC chains use "btc" key. If any requested chain is unsupported, the wallet will reject the connection
- chains: string[]; Chain identification information
- defaultChain?: string; Default chain selection
- optionalNamespaces - [namespace: string]: ConnectNamespace; Optional connection information where unsupported chains won't prevent connection
- chains: string[]; Chain identification information
- defaultChain?: string; Default chain selection
- sessionConfig: object
- redirect: string Redirection parameter after successful connection. For Telegram Mini Apps, this can be set to Telegram's deeplink: "tg://resolve"
Return Value
Promise
<Session>- topic: string; Session identifier
- namespaces:
Record<string, Namespace>; Successfully connected namespace information - chains: string[]; Connected chain information
- accounts: string[]; Connected account information
- methods: string[]; Wallet-supported methods for current namespace
- defaultChain?: string; Current session's default chain
- sessionConfig?: SessionConfig
- dappInfo: object DApp information
- name:string
- icon:string
- redirect?:string, Redirection parameter after successful connection
Implementation Example
// Example connection code
try {
const session = await provider.connect({
namespaces: {
btc: {
chains: ["btc:mainnet"],
methods: ["signPsbt", "sendBitcoin"],
events: ["accountsChanged"]
}
}
});
console.log("Connected successfully:", session.accounts);
} catch (error) {
console.error("Connection failed:", error);
}Checking Wallet Connection Status
Determining whether a wallet is currently connected is essential for managing application state and user experience.
Return Value
- boolean: True if wallet is connected, false otherwise
Implementation Example
// Check connection status
const isConnected = provider.isConnected();
if (isConnected) {
// Proceed with authenticated operations
} else {
// Prompt user to connect wallet
}Transaction Preparation
Before executing transactions, you need to create an OKXBtcProvider object by passing your OKXUniversalProvider instance to the constructor. This specialized provider handles Bitcoin-specific operations and transaction formatting.
// Create Bitcoin provider
const btcProvider = new OKXBtcProvider(provider);Retrieving Account Information
Fetching account details is crucial for displaying user-specific data and preparing transaction parameters.
Request Parameters
- chainId: Requested chain identifier, e.g., "btc:mainnet", "fractal:mainnet"
Return Value
Object
- address: string Wallet address
- publicKey: string Public key
Implementation Example
// Get account information
const accountInfo = await btcProvider.getAccount("btc:mainnet");
console.log("Address:", accountInfo.address);
console.log("Public Key:", accountInfo.publicKey);Message Signing
Digital signatures provide authentication and verification for various operations within the Bitcoin ecosystem.
Request Parameters
- chain - string, Target chain for method execution
- signStr - string Message to be signed
- type - (optional) "ecdsa" | "bip322-simple", defaults to "ecdsa"
Return Value
- Promise
<string>: Signature result
Implementation Example
// Sign a message
const signature = await btcProvider.sign("btc:mainnet", "Hello, Bitcoin!", "ecdsa");
console.log("Signature:", signature);Sending Bitcoin Transactions
Transferring Bitcoin between addresses represents a core functionality for most financial applications.
Request Parameters
- chainId - string, Target chain for signing execution (required parameter, e.g., "btc:mainnet")
- toAddress - string, Recipient address
- satoshis - number, Amount in satoshis to send
options - Object (optional)
- feeRate - number (optional) Custom fee rate
Return Value
- Promise
<string>Transaction hash
Implementation Example
// Send Bitcoin transaction
const txHash = await btcProvider.sendBitcoin(
"btc:mainnet",
"recipient_address_here",
10000, // 0.0001 BTC
{ feeRate: 15 } // Optional custom fee rate
);
console.log("Transaction Hash:", txHash);PSBT Signing (Partially Signed Bitcoin Transactions)
PSBT signing enables complex transaction construction with multiple participants and conditions.
Request Parameters
- chain - string, Target chain for signing execution (required parameter, e.g., "btc:mainnet")
- psbtHex - string, Hexadecimal string of PSBT to be signed
options:
- autoFinalized - boolean: Whether to finalize PSBT after signing, defaults to true
toSignInputs - array:
- index - number: Input index to sign
- address - string: Address corresponding to private key for signing
- publicKey - string: Public key corresponding to private key for signing
- sighashTypes - number[]: (optional) Sighash types
- disableTweakSigner - boolean: (optional) When signing and unlocking Taproot addresses, tweakSigner is used by default to generate signatures. Enabling this option allows signing with raw private key
Return Value
- Promise
<string>Hexadecimal string of signed PSBT
Implementation Example
// Sign a PSBT
const signedPsbt = await btcProvider.signPsbt(
"btc:mainnet",
"psbt_hex_string_here",
{
autoFinalized: true,
toSignInputs: [
{
index: 0,
address: "signing_address_here",
publicKey: "public_key_here"
}
]
}
);Multiple PSBT Signing
Batch processing of multiple PSBTs improves efficiency for applications handling numerous transactions simultaneously.
Request Parameters
- chainId - string, Target chain for signing execution (required parameter, e.g., "btc:mainnet")
- psbtHex - string[], Array of PSBT hexadecimal strings to sign
options - object[]
- autoFinalized - boolean: Whether to finalize PSBT after signing, defaults to true
toSignInputs - array:
- index - number: Input index to sign
- address - string: Address corresponding to private key for signing
- publicKey - string: Public key corresponding to private key for signing
- sighashTypes - number[]: (optional) Sighash types
- disableTweakSigner - boolean: (optional) When signing and unlocking Taproot addresses, tweakSigner is used by default to generate signatures. Enabling this option allows signing with raw private key
Return Value
- Promise
<string[]>Array of signed PSBT hexadecimal strings
Implementation Example
// Sign multiple PSBTs
const signedPsbts = await btcProvider.signPsbts(
"btc:mainnet",
["psbt1_hex", "psbt2_hex"],
[
{
autoFinalized: true,
toSignInputs: [{ index: 0, address: "address1", publicKey: "pubkey1" }]
},
{
autoFinalized: true,
toSignInputs: [{ index: 0, address: "address2", publicKey: "pubkey2" }]
}
]
);Signing and Broadcasting PSBT Transactions
This combined operation streamlines the process of finalizing transactions and submitting them to the network.
App required: >= 6.93.0
Request Parameters
- chain - string, Target chain for signing execution (required parameter, e.g., "btc:mainnet")
- psbtHex - string, Hexadecimal string of PSBT to be signed
options: - object
- autoFinalized - boolean: Whether to finalize PSBT after signing, defaults to true
toSignInputs - array:
- index - number: Input index to sign
- address - string: Address corresponding to private key for signing
- publicKey - string: Public key corresponding to private key for signing
- sighashTypes - number[]: (optional) Sighash types
- disableTweakSigner - boolean: (optional) When signing and unlocking Taproot addresses, tweakSigner is used by default to generate signatures. Enabling this option allows signing with raw private key
Return Value
Promise
<object>- txhash Transaction hash
- signature Hexadecimal string of signed PSBT
Implementation Example
// Sign and broadcast PSBT
const result = await btcProvider.signAndPushPsbt(
"btc:mainnet",
"psbt_hex_string_here",
{
autoFinalized: true,
toSignInputs: [
{
index: 0,
address: "signing_address_here",
publicKey: "public_key_here"
}
]
}
);
console.log("Transaction Hash:", result.txhash);Disconnecting Wallets
Properly disconnecting wallets ensures clean session termination and is particularly important when switching between different wallet connections.
// Disconnect wallet
await provider.disconnect();Event Handling
The SDK provides various events that allow your application to respond to state changes, connection updates, and transaction status modifications. Implementing event listeners enhances user experience by providing real-time feedback.
Common events include:
- Session updates
- Account changes
- Transaction status changes
- Network modifications
Error Codes and Handling
Understanding potential errors during connection, transaction processing, and disconnection procedures is essential for building robust applications.
Common Exceptions
| Error Code | Description |
|---|---|
| OKX_CONNECT_ERROR_CODES.UNKNOWN_ERROR | Unknown or unexpected error |
| OKX_CONNECT_ERROR_CODES.ALREADY_CONNECTED_ERROR | Wallet already connected |
| OKX_CONNECT_ERROR_CODES.NOT_CONNECTED_ERROR | Wallet not connected |
| OKX_CONNECT_ERROR_CODES.USER_REJECTS_ERROR | User rejected the operation |
| OKX_CONNECT_ERROR_CODES.METHOD_NOT_SUPPORTED | Requested method not supported |
| OKX_CONNECT_ERROR_CODES.CHAIN_NOT_SUPPORTED | Requested chain not supported |
| OKX_CONNECT_ERROR_CODES.WALLET_NOT_SUPPORTED | Wallet not supported |
| OKX_CONNECT_ERROR_CODES.CONNECTION_ERROR | Connection-related issue |
Implement proper error handling to ensure graceful degradation and user-friendly error messages.
// Example error handling
try {
await provider.connect(connectParams);
} catch (error) {
switch (error.code) {
case OKX_CONNECT_ERROR_CODES.USER_REJECTS_ERROR:
console.log("User rejected connection request");
break;
case OKX_CONNECT_ERROR_CODES.CHAIN_NOT_SUPPORTED:
console.log("Requested chain not supported");
break;
default:
console.log("Connection failed:", error.message);
}
}Best Practices for Implementation
When integrating the OKX Bitcoin SDK, consider these best practices:
- User Experience: Always provide clear feedback during connection attempts and transaction processing
- Error Handling: Implement comprehensive error handling with user-friendly messages
- State Management: Properly manage connection state across application sessions
- Security: Validate all responses and implement appropriate security measures
- Testing: Thoroughly test all functionality across different network conditions
👉 Explore advanced integration techniques
Frequently Asked Questions
What is the minimum supported version for OKX Connect integration?
You need to ensure you're using at least version 6.92.0 of the OKX SDK to access all Bitcoin-related functionality. Earlier versions may lack support for certain Bitcoin operations or have limited compatibility with newer wallet features.
How do I handle different Bitcoin network types (mainnet vs testnet)?
The SDK supports both mainnet and testnet environments through proper chain identification. Use "btc:mainnet" for production environments and the appropriate testnet identifier for development and testing purposes to avoid accidental real transactions during development.
What image formats are supported for the application icon?
The SDK supports PNG, ICO, and other standard image formats, but specifically excludes SVG icons. For optimal display quality, provide a 180x180px PNG image URL that will be displayed consistently across different wallet interfaces and devices.
Can I customize the fee rate for Bitcoin transactions?
Yes, the SDK allows optional custom fee rate specification through the options parameter when sending Bitcoin transactions. This enables applications to balance between transaction confirmation speed and cost according to user preferences and network conditions.
How does PSBT signing differ from regular transaction signing?
PSBT (Partially Signed Bitcoin Transaction) format enables more complex transaction scenarios involving multiple parties and conditional signing. It's particularly useful for multisig wallets, coinjoin transactions, and other advanced Bitcoin protocols that require collaborative transaction construction.
What should I do if a user rejects a connection request?
Your application should gracefully handle rejection by providing clear feedback and potentially offering alternative connection methods or explaining why wallet connection is necessary for specific features. Avoid blocking essential application functionality behind mandatory wallet connections when possible.