Integrating with the NEAR Blockchain Using the OKX Injected Provider API

·

The OKX Injected Provider API is a powerful JavaScript tool that enables decentralized applications (DApps) to interact seamlessly with the OKX Wallet browser extension. When a user with the OKX Wallet installed visits your DApp, this API is automatically injected into the website's environment, allowing you to request user accounts, read on-chain data, and facilitate the signing of messages and transactions on supported blockchains like NEAR.

This guide provides a comprehensive overview of how to integrate and utilize this API to connect your DApp to the NEAR blockchain via OKX Wallet.

Accessing the Injected Provider

Your DApp can access the OKX Wallet provider object through the global window object. We recommend using the primary method for better stability and forward compatibility.

It is good practice to check for the existence of the provider before attempting to call its methods to ensure the user has OKX Wallet installed.

if (typeof window.okxwallet !== 'undefined') {
    // OKX Wallet is installed, proceed with integration
    const provider = window.okxwallet.near;
}

Establishing a Connection

The connection process is a crucial first step for any user interaction. The API provides methods to manage the user's authentication state.

Initiating a Sign-In Request

The requestSignIn() method prompts the user to connect their OKX Wallet to your DApp. You can call it with varying parameters depending on the level of access your application requires.

Basic Account Connection

To simply retrieve the user's NEAR account ID, you can call the method without any arguments.

// Request connection to the user's wallet
await window.okxwallet.near.requestSignIn();

The returned value upon success is the user's NEAR account ID string (e.g., 'yourname.near').

Requesting an Access Key

For DApps that need to interact with smart contracts, you can request an access key with specific permissions. This is done by passing the contract ID and the required method names to requestSignIn().

// Request connection with specific contract permissions
const signInResult = await window.okxwallet.near.requestSignIn({
    contractId: 'example-contract.near',
    methodNames: ['view_method', 'change_method'] // Array of method names
});

The return value includes the access key object, which grants your DApp the specified permissions for that contract.

Checking Connection Status

Before performing actions, it's often necessary to check the user's current connection status.

// Check if a user is connected
const isUserConnected = await window.okxwallet.near.isSignedIn();

// Get the current account ID
const currentAccount = await window.okxwallet.near.getAccountId();

Signing Out a User

The signOut() method disconnects the user's wallet from your DApp. Note that the wallet itself can also initiate a disconnection.

// Disconnect the user's wallet
await window.okxwallet.near.signOut();

Message Signing

Message signing is a fundamental operation for verifying ownership of an account without executing a blockchain transaction. The signMessage() method allows users to sign an arbitrary message.

// Prepare the message parameters
const messageParams = {
    message: "Hello, NEAR! Please sign this message to verify your identity.", // Message to be signed
    recipient: "your-dapp.near", // Your DApp's receiving account
    nonce: Buffer.from("unique_nonce").toString('base64'), // A unique nonce
    callbackUrl: 'https://yourdapp.com/callback' // Optional URL for redirect
};

// Request the message signature
const signature = await window.okxwallet.near.signMessage(messageParams);

The return value is the signed message object, which contains the signature and other details that your DApp's backend can verify.

Interacting with Smart Contracts

To change the state of the blockchain or execute functions that require gas, your DApp needs to create and send transactions.

Signing and Sending a Single Transaction

The signAndSendTransaction() method is used to construct, sign, and broadcast a single transaction to the NEAR network.

// Define the transaction actions
const transaction = {
    receiverId: 'example-contract.near', // The smart contract address
    actions: [
        {
            type: 'FunctionCall',
            params: {
                methodName: 'transfer',
                args: { recipient_id: 'friend.near', amount: '1000000000000000000000000' },
                gas: '30000000000000',
                deposit: '0'
            }
        }
    ]
};

// Sign and send the transaction
const transactionResult = await window.okxwallet.near.signAndSendTransaction(transaction);

The return value includes the transaction hash (txHash). Your DApp is responsible for using this hash to query the network and confirm the transaction's status and outcome. 👉 Explore advanced transaction monitoring tools

Requesting to Sign Multiple Transactions

For complex operations, you may need the user to sign several transactions at once. The requestSignTransactions() method prompts the user to sign a batch of transactions.

Important Note: This method only signs the transactions. Your DApp must handle the logic of broadcasting each signed transaction to the network.

// Define an array of transactions
const transactions = [
    {
        receiverId: 'contractA.near',
        actions: [ ... ]
    },
    {
        receiverId: 'contractB.near',
        actions: [ ... ]
    }
];

// Request signature for the batch
const signedTransactions = await window.okxwallet.near.requestSignTransactions(transactions);

The return value is an array of signed transaction objects, which your application must then broadcast.

Listening for Wallet Events

The OKX Provider API emits events that allow your DApp to react to changes in the wallet's state, providing a dynamic and responsive user experience.

Handling the Sign-In Event

Listen for the signIn event to detect when a user successfully connects their wallet to your application.

// Add an event listener for sign-in
window.okxwallet.near.on('signIn', (account) => {
    console.log('Wallet connected: ', account);
    // Update your UI to show the connected state
});

Handling the Sign-Out Event

Similarly, the signOut event notifies your DApp when the user disconnects their wallet.

// Add an event listener for sign-out
window.okxwallet.near.on('signOut', () => {
    console.log('Wallet disconnected');
    // Update your UI to show the disconnected state
});

Handling Account Changes

The accountChanged event is crucial for handling scenarios where a user switches accounts within their OKX Wallet while your DApp is open.

// Add an event listener for account changes
window.okxwallet.near.on('accountChanged', (newAccount) => {
    if (newAccount) {
        console.log('User switched to account: ', newAccount);
        // Refresh the DApp's data for the new account
    } else {
        // Handle the case where the account is no longer available
    }
});

Frequently Asked Questions

What is the OKX Injected Provider API?
The OKX Injected Provider API is a JavaScript interface injected into websites by the OKX Wallet browser extension. It allows DApps to securely request user accounts, read blockchain data, and ask users to sign transactions and messages on networks like NEAR, enabling a seamless Web3 experience.

How do I check if a user has OKX Wallet installed?
You can check for the existence of the window.okxwallet object. If it is defined and contains the near property, the user has the wallet installed and the API is available for use. It's best practice to guide users to install the wallet if it's not detected.

What is the difference between signAndSendTransaction and requestSignTransactions?
signAndSendTransaction handles the entire lifecycle of a single transaction: signing it with the user's private key and immediately broadcasting it to the network. requestSignTransactions is used for batch signing multiple transactions but only handles the signing part; your DApp is responsible for broadcasting each signed transaction to the network afterwards.

Why is my DApp not receiving the accountChanged event?
Ensure your event listeners are set up correctly immediately after detecting the provider. The event will only fire if the user actively switches accounts within the wallet interface while your DApp is open. Also, verify you are using the recommended window.okxwallet.near provider object.

Can I use this API with other NEAR wallets?
The API is specifically injected by the OKX Wallet extension. While other wallets may inject a similar object (often at window.near), their implementations might differ. For maximum compatibility, you should implement support for multiple wallet providers and allow the user to choose.

How can I get the result of a transaction after it is sent?
When you use signAndSendTransaction, it returns a promise that resolves with an object containing the transaction hash (txHash). You must use this hash to query a NEAR blockchain indexer or node RPC endpoint to get the final status and outcome of the transaction. 👉 Get detailed methods for tracking transaction status