In the world of decentralized applications (DApps), seamless interaction with blockchain networks is crucial. The Injected Provider API serves as a vital bridge, allowing DApps to communicate directly with a user's Web3 wallet. This JavaScript-based interface enables applications to request account access, read on-chain data, and facilitate message or transaction signing without compromising user security.
For developers building on Starknet, understanding and implementing this API correctly is essential for creating smooth, user-friendly experiences. This guide will walk you through the fundamental concepts, properties, methods, and practical implementation of the Injected Provider API.
Accessing the Injected Object
When a user visits your DApp with a compatible Web3 wallet installed, the wallet injects a provider object into the browser's window environment. Your application can access this object through either of these two properties:
window.okxwallet.starknetwindow.starknet_okxwallet
Both properties reference the same underlying object, providing flexibility for developers. Using either of these direct access methods ensures your DApp specifically references the intended wallet's Starknet object, preventing potential conflicts with other wallet injections.
For developers utilizing third-party libraries like get-starknet, the injected provider remains fully compatible, allowing for integration with existing Starknet development workflows.
Properties and Methods of the Injected Object
The injected provider object contains several important properties and methods that enable DApp functionality:
Core Properties
- name (string): Identifies the wallet provider with the value 'OKX Wallet'
- icon (string): Provides the wallet's icon for UI display purposes
- version (string): Indicates the current version of the wallet implementation
- isConnected (boolean): Shows whether the wallet is currently connected to your DApp
- selectedAddress (string): Contains the user's currently selected wallet address
- account (Account): Provides access to the account object, inheriting from starknet.js's Account class with all associated properties and methods
- chainId (string): Specifies the connected network - currently supports only mainnet with value
SN_MAIN - provider (Provider): Offers access to the provider object using starknet.js's RpcProvider implementation
Essential Methods
- enable() => [string]: Initiates the wallet connection process, triggering the wallet's connection interface where users can approve or reject the connection request. Returns a single-item array containing the selected address upon successful connection.
on(event, callback) => void: Adds event listeners for important wallet events:
accountsChanged: Triggered when users switch accounts, providing an array of new addresses, or an empty array when disconnecting
- off(event, callback) => void: Removes previously established event listeners
👉 Explore advanced integration techniques
Establishing Wallet Connection
Implementing wallet connection in your DApp involves calling the enable() method, which prompts users to authorize the connection. Here's a basic implementation approach:
async function connectWallet() {
try {
if (typeof window.okxwallet !== 'undefined') {
const [address] = await window.okxwallet.starknet.enable();
console.log('Connected with address:', address);
return address;
} else {
alert('Please install a compatible Web3 wallet');
}
} catch (error) {
console.error('Connection failed:', error);
}
}This simple implementation checks for wallet availability, initiates the connection flow, and handles both success and error scenarios. For production applications, you'll want to implement more robust error handling and user feedback mechanisms.
Contract Interactions and Execution
The injected provider enables sophisticated contract interactions through the execute method:
window.okxwallet.starknet.account.execute(transactions [, abi])
This method executes one or multiple contract calls. For single transactions, pass a transaction object; for multiple transactions, provide an array of transaction objects.
Transaction Parameters
The transaction object structure includes:
- contractAddress (string): The target contract's address
- entrypoint (string): The specific contract function to execute
- calldata (array): Data passed to the function call
- signature (array): Cryptographic signature for transaction authorization
The abi parameter is optional but recommended for better error handling and type safety.
Return Values
The method returns a result object containing:
- transaction_hash (string): The unique hash identifying the executed transaction
Practical Implementation Example
const transaction = {
contractAddress: '0x1234...',
entrypoint: 'transfer',
calldata: [recipientAddress, amount],
signature: [] // Typically generated by the wallet
};
try {
const result = await window.okxwallet.starknet.account.execute(transaction);
console.log('Transaction hash:', result.transaction_hash);
} catch (error) {
console.error('Transaction failed:', error);
}Message Signing Functionality
Message signing is essential for authentication and verification purposes in DApps. The injected provider provides a straightforward method:
window.okxwallet.starknet.account.signMessage(data)
Signing Parameters
- data (object): The message or data object requiring cryptographic signature
Return Values
The method returns a signature array containing two components that together form the complete signature.
Implementation Example
const message = {
// Your message data structure
domain: {
name: 'Example DApp',
version: '1',
chainId: 'SN_MAIN'
},
types: {
StarkNetDomain: [
{ name: 'name', type: 'string' },
{ name: 'version', type: 'string' },
{ name: 'chainId', type: 'string' }
],
Message: [
{ name: 'content', type: 'string' }
]
},
primaryType: 'Message',
message: {
content: 'Hello, please sign this message to verify your identity'
}
};
try {
const signature = await window.okxwallet.starknet.account.signMessage(message);
console.log('Signature:', signature);
} catch (error) {
console.error('Signing failed:', error);
}Advanced Usage and Considerations
For more advanced functionality beyond the core methods described, developers can explore the full capabilities available through the starknet.account and starknet.provider objects. The starknet.js documentation provides comprehensive information on additional properties and methods available through these objects.
When implementing the Injected Provider API, consider these best practices:
- Always check for wallet availability before attempting to call methods
- Implement proper error handling for connection rejections and transaction failures
- Provide clear user feedback throughout the interaction process
- Respect user privacy and only request necessary permissions
- Test thoroughly across different network conditions and wallet versions
👉 Access comprehensive developer resources
Frequently Asked Questions
What is the Injected Provider API?
The Injected Provider API is a JavaScript interface that Web3 wallets inject into visited websites, allowing DApps to request account access, read blockchain data, and facilitate transaction signing without compromising security.
How do I ensure my DApp uses the correct wallet provider?
You can directly access specific provider objects using window.okxwallet.starknet or window.starknet_okxwallet to avoid potential conflicts with other wallet injections.
What networks does the injected provider support?
Currently, the provider supports only the Starknet mainnet, identified by the chainId SN_MAIN. Developers should check for network compatibility before executing transactions.
How should I handle wallet connection errors?
Implement comprehensive error handling that checks for wallet availability, connection rejections, and network issues. Provide clear user feedback suggesting solutions like wallet installation or connection retry.
Can I use this API with other Starknet development libraries?
Yes, the injected provider is compatible with popular Starknet libraries like get-starknet and starknet.js, allowing integration into existing development workflows.
What events can I listen for with the provider?
The primary event available is accountsChanged, which triggers when users switch accounts or disconnect. This helps your DApp maintain accurate account information and respond to connection changes.