OKX OS

OKX OS

A comprehensive onchain infrastructure suite for building and scaling applications.

Back

Overview

OKX OS is the most comprehensive onchain infrastructure suite that provides developers with a full set of tools, SDKs, and APIs to build and scale applications across over 100 chains without limitations. It leverages the same technology that powers the OKX Wallet, serving millions of users and processing more than 400 million daily API calls.

Features

  • One-stop solution: The most extensive suite of tools and APIs for building complex onchain experiences across any chain, from wallets to games, exchanges, and collections.
  • Multi-chain support and liquidity aggregation: Access to over 100 chains and aggregate liquidity across multiple networks, DEXs, and major marketplaces for maximum flexibility and faster market entry.
  • Bitcoin-friendly: Unique tools for Inscriptions, Ordinals, Runes, Fractal Bitcoin, and other emerging Bitcoin-based innovations.
  • Industry-leading security: Leverages OKX's robust security measures and audited processes, enabling developers to build with confidence.
  • Proven scalability: Designed for fast-growth applications, as evidenced by OKX's ecosystem serving millions of users and handling over 400 million daily API calls.

Getting Started

Developers can start using OKX OS for free today by visiting the OKX Build Portal. The platform provides comprehensive tools, SDKs, and APIs to help you quickly build and scale your applications across multiple chains.

Documentation

For detailed documentation and guides, please visit the OKX OS Documentation.

Use Cases

  • Building multi-chain wallets with seamless transaction management.
  • Integrating cross-chain swaps and liquidity aggregation into decentralized applications.
  • Creating NFT marketplaces with real-time data and marketplace integrations.
  • Developing blockchain games with in-game asset management across 100+ chains.
  • Accessing comprehensive onchain data APIs for actionable insights.

Building an On-Chain Data Dashboard for Avalanche C-Chain

This guide walks you through setting up a dashboard to track wallet assets and transactions on the Avalanche C-Chain. You'll use OKX OS's Wallet API to fetch and display this data.

Prerequisites

  • Node.js installed on your system
  • Basic understanding of JavaScript and async/await
  • An OKX Developer account

Setting Up Your Development Environment

  1. Log in to the Developer Portal: Sign up for an account on the OKX Developer Portal.

  2. Create a New Project: Click on the Create new project button and fill in the required details. Once the project is created, you will recieve a Project ID. Keep it for future reference.

  3. Generate API Keys: Once your project is created, click the Manage and then Create API key buttons to create a new API key. Fill in the required details and click Create. You will receive an API Key and API Secret. Keep your API Key, API Secret, and Passphrase for future use.

Note: Keep your Project ID, API Key, Secret, and Passphrase secure by storing them in environment variables or a secure storage solution. It is recommended to never share these credentials publicly or commit them to your codebase.

  1. Initialize a New Project: Run the following commands to create a new directory and initialize a Node.js project with default settings and required dependencies:
mkdir avalanche-dashboard
cd avalanche-dashboard
npm init -y
npm install crypto-js

Create three script files:

touch createAccount.js getAssets.js getTx.js

Create Wallet Account

You'll start by creating an account to track your Avalanche addresses with a simple Node.js script that interacts with the OKX Wallet API.

In the createAccount.js file:

const CryptoJS = require("crypto-js");
 
const createWallet = async () => {
    // Generate timestamp in ISO format
    const timestamp = new Date().toISOString();
    const method = "POST";
    const path = "/api/v5/wallet/account/create-wallet-account";
 
    // Prepare the body first as we need it for signature
    const body = {
        addresses: [
            {
                chainIndex: "43114",
                address: "0x2eFB50e952580f4ff32D8d2122853432bbF2E204",
            },
            // You can add more addresses and chain indexes
            // {
            //     chainIndex: "1",
            //     address: "0x2eFB50e952580f4ff32D8d2122853432bbF2E204",
            // },
            // {
            //     chainIndex: "43114",
            //     address: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
            // },
        ],
    };
 
    // Generate signature
    // timestamp + method + path + body
    const signString = timestamp + method + path + JSON.stringify(body);
    const signature = CryptoJS.enc.Base64.stringify(
        CryptoJS.HmacSHA256(signString, "YOUR API SECRET KEY"),
    );
 
    const response = await fetch(
        "https://www.okx.com/api/v5/wallet/account/create-wallet-account",
        {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "OK-ACCESS-PROJECT": "YOUR PROJECT ID",
                "OK-ACCESS-KEY": "YOUR API KEY",
                "OK-ACCESS-SIGN": signature,
                "OK-ACCESS-PASSPHRASE": "YOUR API PASSPHRASE",
                "OK-ACCESS-TIMESTAMP": timestamp,
            },
            body: JSON.stringify(body),
        },
    );
 
    const data = await response.json();
    return data;
};
 
// Example usage:
createWallet()
    .then((response) => console.log("Success:", response))
    .catch((error) => console.error("Error:", error));

Before running the script, replace these placeholder values with your actual credentials:

"YOUR API SECRET KEY" → Your API Secret
"YOUR PROJECT ID" → Your Project ID
"YOUR API KEY" → Your API Key
"YOUR API PASSPHRASE" → Your Passphrase

Run your script:

node createAccount.js

You should see a success message with the response data if the account is created successfully.

For example,

Success: { code: '0', message: 'success', data: { accountId : 'Y7489xxxx-xxxx-xxxx-xxxx-xxxxxxaa652c' } }

Check Wallet Assets

Now that we have an account, you can fetch the token balances. This script will show you all tokens held by your tracked addresses.

In your getAssets.js file:

  1. Copy this code to getAssets.js:
const CryptoJS = require("crypto-js");
 
    const getRequestUrl = (baseUrl, path, params = null) => {
        const url = new URL(baseUrl + path);
        if (params) {
            Object.keys(params).forEach((key) =>
                url.searchParams.append(key, params[key]),
            );
        }
        return url.toString();
    };
 
    const apiBaseUrl = "https://www.okx.com";
    const getAssetsParams = {
        accountId: "ACCOUNT ID FROM PREVIOUS STEP", // Replace with your accountId
    };
 
    const timestamp = new Date().toISOString();
    const method = "GET";
    const path = "/api/v5/wallet/asset/wallet-all-token-balances";
    const queryString = `?accountId=${getAssetsParams.accountId}`;
 
    // Generate signature
    const signString = timestamp + method + path + queryString;
    const signature = CryptoJS.enc.Base64.stringify(
        CryptoJS.HmacSHA256(signString, "YOUR API SECRET KEY"),
    );
 
    const headersParams = {
        "Content-Type": "application/json",
        "OK-ACCESS-PROJECT": "YOUR PROJECT ID",
        "OK-ACCESS-KEY": "YOUR API KEY",
        "OK-ACCESS-SIGN": signature,
        "OK-ACCESS-PASSPHRASE": "YOUR API PASSPHRASE",
        "OK-ACCESS-TIMESTAMP": timestamp,
    };
 
    const getAssetsData = async () => {
        const apiRequestUrl = getRequestUrl(apiBaseUrl, path, getAssetsParams);
 
        const response = await fetch(apiRequestUrl, {
            method: "GET",
            headers: headersParams,
        });
 
        return response.json();
    };
 
    // Use it
    getAssetsData()
        .then(({ data }) => {
            console.log("\n=== Wallet Assets ===\n");
 
            data.forEach((wallet) => {
                // Convert timestamp to readable date
                const date = new Date(parseInt(wallet.timeStamp));
                console.log(`Last Updated: ${date.toLocaleString()}\n`);
 
                console.log("Token Assets:");
                wallet.tokenAssets.forEach((token) => {
                    console.log(`
    Token: ${token.symbol}
    Chain: ${token.chainIndex}
    Balance: ${token.balance}
    -----------------------------`);
                });
            });
        })
        .catch((error) => console.error("Error:", error));

Make sure to:

  • Update the accountId with the one you received in Step 1
  • Replace the API credentials with yours

Run the asset checker:

node getAssets.js

You should see the assets of the wallet account if the request is successful.

For example,

=== Wallet Assets ===
 
Last Updated: 10/24/2024, 7:23:20 PM
 
Token Assets:
 
Token: AVAX
Chain: 43114
Balance: 882338.9729422927
-----------------------------
 
Token: Sword
Chain: 43114
Balance: 100000
-----------------------------
 
Token: ERGC
Chain: 43114
Balance: 100000
-----------------------------
 
 
Token: MILO
Chain: 43114
Balance: 500000
-----------------------------

View Transaction Details

Finally, you can set up transaction viewing. This script provides detailed information about any transaction on the Avalanche C-Chain.

In your getTx.js file:

const CryptoJS = require("crypto-js");
 
const getRequestUrl = (baseUrl, path, params = null) => {
    const url = new URL(baseUrl + path);
    if (params) {
        Object.keys(params).forEach((key) =>
            url.searchParams.append(key, params[key]),
        );
    }
    return url.toString();
};
 
const apiBaseUrl = "https://www.okx.com";
const params = {
    txHash: '0xaf54d1cb2c21bed094095bc503ec76128f80c815db8631fd74c6e49781b94bd1', // Changed from txhash to txHash
    chainIndex: '43114'
};
 
const timestamp = new Date().toISOString();
const method = "GET";
const path = '/api/v5/wallet/post-transaction/transaction-detail-by-txhash';
const queryString = `?txHash=${params.txHash}&chainIndex=${params.chainIndex}`; // Changed from txhash to txHash
 
const signString = timestamp + method + path + queryString;
const signature = CryptoJS.enc.Base64.stringify(
    CryptoJS.HmacSHA256(signString, "YOUR API SECRET"),
);
 
const headersParams = {
    "Content-Type": "application/json",
    "OK-ACCESS-PROJECT": "YOUR PROJECT ID",
    "OK-ACCESS-KEY": "YOUR API KEY",
    "OK-ACCESS-SIGN": signature,
    "OK-ACCESS-PASSPHRASE": "YOUR API PASSPHRASE",
    "OK-ACCESS-TIMESTAMP": timestamp,
};
 
const getTransactionDetailData = async () => {
    const apiRequestUrl = getRequestUrl(apiBaseUrl, path, params);
 
    const response = await fetch(apiRequestUrl, {
        method: "GET",
        headers: headersParams,
    });
 
    return response.json();
};
 
const formatDate = (timestamp) => {
    return new Date(parseInt(timestamp)).toLocaleString();
};
 
const formatGas = (gas) => {
    return parseFloat(gas).toLocaleString();
};
 
getTransactionDetailData()
    .then((response) => {
        console.log('\n=== Transaction Details ===\n');
 
        if (response.code === "0" && response.data && response.data.length > 0) {
            const tx = response.data[0];
 
            // Transaction Basic Info
            console.log('📝 Basic Information');
            console.log('------------------');
            console.log(`Hash: ${tx.txhash}`);
            console.log(`Status: ${tx.txStatus.toUpperCase()}`);
            console.log(`Block: ${formatGas(tx.height)}`);
            console.log(`Time: ${formatDate(tx.txTime)}`);
            console.log(`Method ID: ${tx.methodId}`);
            console.log(`Chain: ${tx.chainIndex} (${tx.symbol})`);
 
            // Gas Info
            console.log('\n⛽ Gas Information');
            console.log('----------------');
            console.log(`Gas Limit: ${formatGas(tx.gasLimit)}`);
            console.log(`Gas Used: ${formatGas(tx.gasUsed)}`);
            console.log(`Gas Price: ${formatGas(tx.gasPrice)} Wei`);
            console.log(`Nonce: ${tx.nonce}`);
 
            // From Address
            console.log('\n📤 From Address');
            console.log('-------------');
            tx.fromDetails.forEach(from => {
                console.log(`Address: ${from.address}`);
                console.log(`Type: ${from.isContract ? 'Contract' : 'Wallet'}`);
            });
 
            // To Address
            console.log('\n📥 To Address');
            console.log('-----------');
            tx.toDetails.forEach(to => {
                console.log(`Address: ${to.address}`);
                console.log(`Type: ${to.isContract ? 'Contract' : 'Wallet'}`);
            });
 
            // Token Transfers
            if (tx.tokenTransferDetails && tx.tokenTransferDetails.length > 0) {
                console.log('\n🔄 Token Transfers');
                console.log('---------------');
                tx.tokenTransferDetails.forEach((transfer, index) => {
                    console.log(`\nTransfer #${index + 1}:`);
                    console.log(`Token: ${transfer.symbol}`);
                    console.log(`Amount: ${transfer.amount}`);
                    console.log(`From: ${transfer.from} ${transfer.isFromContract ? '(Contract)' : '(Wallet)'}`);
                    console.log(`To: ${transfer.to} ${transfer.isToContract ? '(Contract)' : '(Wallet)'}`);
                    console.log(`Contract: ${transfer.tokenContractAddress}`);
                });
            }
 
            // Internal Transactions (if any)
            if (tx.internalTransactionDetails && tx.internalTransactionDetails.length > 0) {
                console.log('\n💱 Internal Transactions');
                console.log('--------------------');
                tx.internalTransactionDetails.forEach((internal, index) => {
                    console.log(`\nInternal Transfer #${index + 1}:`);
                    console.log(`From: ${internal.from}`);
                    console.log(`To: ${internal.to}`);
                    console.log(`Amount: ${internal.amount} ${tx.symbol}`);
                    console.log(`Status: ${internal.state}`);
                });
            }
 
        } else {
            console.log('Status:', response.code);
            console.log('Message:', response.msg);
            console.log('Data:', response.data);
        }
    })
    .catch(error => console.error('Error:', error));

Update the script with:

  • Your API credentials
  • Any transaction hash you want to investigate

Check a transaction:

node getTx.js

You'll see a detailed breakdown including:

  • Transaction basics
  • Gas info
  • Addresses involved
  • Token transfers
  • Internal transactions

Conclusion

The Wallet API is one of 4 strong pillars within the OKX OS infrastructure, complemented by the DEX API for decentralized trading capabilities, the Marketplace API for NFT functionalities, and the Explorer API for comprehensive blockchain data access and analysis. Together, these APIs form a complete toolkit that enables developers to build sophisticated Web3 applications with enterprise-grade reliability and performance.

By leveraging OKX OS's powerful infrastructure suite, developers can build and scale innovative onchain applications quickly and efficiently. With its extensive tools, multi-chain support, and proven scalability, OKX OS continues to drive the future of Web3 development, making it easier than ever to create seamless experiences across the blockchain ecosystem.

Developer:

OKX

Categories:

Wallet SDKs

Available For:

C-Chain

Website:

https://www.okx.com/web3/build

Documentation:

https://www.okx.com/web3/build/docs/waas/okx-waas-what-is-waas
Edit on Github