This guide provides a structured approach to integrating the OKX Connect SDK with Starknet, enabling your decentralized application (DApp) to connect to wallets, sign messages, and send transactions efficiently.
Why Integrate OKX Connect with Starknet?
Starknet is a leading Layer 2 scaling solution for Ethereum, offering high throughput and low transaction costs. Integrating a secure wallet connection is crucial for any DApp. OKX Connect provides a streamlined SDK that simplifies this process, allowing developers to focus on building their application's core features rather than complex wallet infrastructure.
The integration facilitates seamless user onboarding, secure transaction signing, and efficient blockchain interactions, which are essential for a positive user experience in the Web3 ecosystem.
Prerequisites and Installation
Before you begin, ensure your development environment is set up correctly. You will need Node.js and npm (or yarn) installed on your machine.
To start integrating OKX Connect into your DApp, install the required package using npm. Make sure you are using version 6.98.0 or later to access the latest features and security updates.
npm install @okx/web3-connectInitialization is the first critical step. Before connecting to a wallet, you must create a provider object that will handle subsequent operations like connecting to the wallet and sending transactions.
Request Parameters
dappMetaData - object
- 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 icons are not supported. For best results, provide a URL that points to a 180x180px PNG icon.
Returns
- OKXUniversalProvider: The initialized provider object for all future interactions.
Example Code Snippet
// Example initialization code
import { OKXUniversalProvider } from '@okx/web3-connect';
const dappMetaData = {
name: "Your DApp Name",
icon: "https://yourdomain.com/path/to/icon.png"
};
const provider = new OKXUniversalProvider(dappMetaData);Establishing a Wallet Connection
Connecting to a user's wallet is essential for obtaining their wallet address, which acts as a primary identifier, and for gathering necessary parameters required for signing transactions.
Request Parameters
connectParams - ConnectParams
namespaces -
[namespace: string]: ConnectNamespace; Optional information for the requested connection. For Starknet, the key is 'starknet'. Currently, only 'starknet:mainnet' is supported. If a requested chain is not supported by the wallet, the connection will be rejected.- chains: string[]; An array of chain IDs.
- defaultChain?: string; An optional default chain.
- optionalNamespaces -
[namespace: string]: ConnectNamespace; Optional connection parameters. Similar tonamespaces, but if a chain is not supported, the connection may still proceed. sessionConfig: object
- redirect: string; A URL to redirect to after a successful connection. For Telegram Mini Apps, this can be set to a Telegram deep link (e.g., 'tg://resolve').
Return Value
Promise
<Session>- topic: string; The unique session identifier.
- namespaces:
Record<string, Namespace>; Namespace information for the established connection. - chains: string[]; The chain information for the connection.
- accounts: string[]; The connected account addresses.
- methods: string[]; The methods supported by the wallet within the current namespace.
- defaultChain?: string; The default chain for this session.
- sessionConfig?: SessionConfig;
dappInfo: object; Information about your DApp.
- name: string;
- icon: string;
- redirect?: string; The redirect URL after a successful connection.
Example Connection Flow
// Example connection code
const connectParams = {
namespaces: {
starknet: {
chains: ['starknet:mainnet'],
defaultChain: 'starknet:mainnet'
}
},
sessionConfig: {
redirect: 'https://yourdapp.com/success' // Or 'tg://resolve' for Telegram
}
};
try {
const session = await provider.connect(connectParams);
console.log("Connected successfully:", session.accounts);
} catch (error) {
console.error("Connection failed:", error);
}Preparing and Sending Transactions
After a successful connection, you can prepare transactions for the user to sign and broadcast to the Starknet network.
First, create a dedicated OKXStarknetProvider object by passing your initialized OKXUniversalProvider instance to its constructor. This specialized provider offers methods tailored for Starknet interactions.
👉 Explore advanced transaction methods
Retrieving Account Information
Before initiating transactions, you may need to fetch the user's account details.
Request Parameters
- chainId: string; The chain you are querying, e.g., 'starknet:mainnet'.
Return Value
Object
- address: string; The user's wallet address.
- pubKey: string; The user's public key.
Example
const accountInfo = await starknetProvider.getAccountInfo('starknet:mainnet');
console.log("Address:", accountInfo.address);Signing Messages
Message signing is a key function for verifying ownership and authentication.
Request Parameters
- signerAddress - string: The wallet address of the signer.
- typedData - object: The message to be signed, structured in a specific format (Starknet's typed data format).
- chain? - string: The chain on which the signing method should be executed.
Return Value
- Promise
[string, string]- The signature result, comprising componentsrandv.
Example
const signature = await starknetProvider.signMessage(signerAddress, typedData, 'starknet:mainnet');
console.log("Signature:", signature);Sending a Transaction
This method constructs, signs, and sends a transaction to the Starknet network.
Request Parameters
- signerAddress - string: The wallet address initiating the transaction.
- transaction - object: The transaction information to be signed and sent, in a fixed format.
- chainId? - string: The chain for which the transaction is intended.
Return Value
- Promise
string- The transaction hash, which can be used to track the transaction on the blockchain.
Example
const txHash = await starknetProvider.sendTransaction(signerAddress, transaction, 'starknet:mainnet');
console.log("Transaction Hash:", txHash);Managing the Wallet Session
Proper session management ensures a secure and user-friendly experience.
Disconnecting a Wallet
To disconnect the connected wallet and delete the current session, call the disconnect method. If you need to switch wallets, you must first disconnect the current wallet and then initiate a new connection.
await provider.disconnect();
console.log("Wallet disconnected.");Handling Events and Errors
Robust applications handle events and errors gracefully.
Event Listening
The SDK emits events for various lifecycle stages (e.g., connection, disconnection, chain changed). Listen to these events to update your UI accordingly.
provider.on('accountsChanged', (accounts) => {
console.log("Accounts changed:", accounts);
});Common Error Codes
Exceptions may be thrown during connection, transaction signing, or disconnection. Here are some common error codes:
| Error Code | Description |
|---|---|
| UNKNOWN_ERROR | An unknown, unexpected error occurred. |
| ALREADY_CONNECTED_ERROR | A wallet connection is already active. |
| NOT_CONNECTED_ERROR | The requested operation requires an active wallet connection. |
| USER_REJECTS_ERROR | The user rejected the connection or transaction request. |
| METHOD_NOT_SUPPORTED | The wallet does not support the requested method. |
| CHAIN_NOT_SUPPORTED | The requested blockchain network is not supported. |
| WALLET_NOT_SUPPORTED | The wallet is not supported by the SDK. |
| CONNECTION_ERROR | A general error occurred during the connection process. |
Always wrap your calls in try-catch blocks to handle these errors and provide feedback to the user.
try {
// Attempt an operation
await someWalletOperation();
} catch (error) {
if (error.code === 'USER_REJECTS_ERROR') {
alert("You rejected the transaction.");
} else {
console.error("Operation failed:", error);
}
}👉 Get detailed error handling strategies
Frequently Asked Questions
What is the minimum SDK version required for OKX Connect with Starknet?
You need to be using version 6.98.0 or later of the OKX Web3 Connect SDK. This version includes the necessary methods and stability improvements for seamless Starknet integration.
Which Starknet networks are currently supported?
Currently, the integration primarily supports 'starknet:mainnet'. Always check the latest documentation for updates on support for testnets or other networks.
What should I do if a user rejects the connection request?
Your application should gracefully handle the USER_REJECTS_ERROR code. Inform the user that the action was cancelled and provide them with an option to try again without causing any application errors.
How can I switch between connected wallets?
To switch wallets, you must first programmatically disconnect the current active session using the disconnect() method. Once disconnected, you can prompt the user to connect a different wallet by calling the connect() method again.
Why is my SVG application icon not displaying?
The OKX Connect SDK requires application icons in PNG or ICO format. SVG icons are not supported. Convert your icon to a PNG (ideally 180x180 pixels) and host it at a publicly accessible URL.
Where can I find the transaction after it is sent?
Upon successful execution, the sendTransaction method returns a transaction hash. You can use this hash to look up the transaction's status and details on any Starknet block explorer.