DEV Community

Cover image for Building with Fractal Bitcoin: OKX OS Integration Guide
Julian Martinez
Julian Martinez

Posted on • Edited on

Building with Fractal Bitcoin: OKX OS Integration Guide

Introduction

site-demo

In this guide, you'll walk through building a Bitcoin Ordinals explorer using the OKX OS APIs. The application will be built with React and TypeScript, following the code examples provided in the official documentation. This will allow users to:

By the end of this tutorial, you'll have a fully functional Ordinals explorer that integrates with the OKX platform. The code will be available on Repl and GitHub for your reference.

Let's get started!

Quick Links πŸ”—

Project Setup πŸ› οΈ

Prerequisites

Installation

# Clone repository
git clone https://github.com/Julian-dev28/ordinals-react-app-ts.git

# Install dependencies
npm install

# Configure environment variables
OKX_API_KEY=your_key
OKX_API_SECRET=your_secret
OKX_API_PASSPHRASE=your_passphrase

# Start the proxy server
node ordinals-server.cjs

# Run the app
npm run dev
Enter fullscreen mode Exit fullscreen mode

Project Structure πŸ“

./
β”œβ”€β”€ ordinals-server.cjs           # Proxy server for OKX API
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ components/              
β”‚   β”‚   β”œβ”€β”€ OrdinalsFetcher.tsx   # Collections explorer
β”‚   β”‚   β”œβ”€β”€ RetrieveInscriptions  # Inscriptions viewer 
β”‚   β”‚   └── TradeHistory.tsx      # Trade history tracker
β”‚   └── services/
β”‚       └── okxServices.ts        # API service layer
Enter fullscreen mode Exit fullscreen mode

Implementation Guide πŸ“š

1. Proxy Server (ordinals-server.cjs)

This server handles authentication and signing of requests to OKX API. It exposes three main endpoints:

// Get Collections
// Actual API endpoint: https://www.okx.com/api/v5/mktplace/nft/fractal-ordinals/collections
GET /api/ordinals
{
    "limit": "20",      // default: 20
    "slug": "string",   // optional
    "isBrc20": false    // default: false
}

// Get Inscriptions
// Actual API endpoint: https://www.okx.com/api/v5/mktplace/nft/fractal-ordinals/get-valid-inscriptions
POST /api/inscriptions
{
    "slug": "string",
    "walletAddress": "string",
    "limit": "10",         // default: 10
    "isBrc20": false,      // optional
    "cursor": "string",    // optional
    "sort": "string"       // optional
}

// Get Trade History
// Actual API endpoint: https://www.okx.com/api/v5/mktplace/nft/fractal-ordinals/trade-history
POST /api/trade-history
{
    "slug": "string",
    "limit": "10",                    // default: 10
    "sort": "desc",                   // default: desc
    "isBrc20": true,                  // default: true
    "cursor": "string",               // optional
    "tradeWalletAddress": "string",   // optional
    "type": "string",                 // optional
    "orderSource": "string"           // optional
}
Enter fullscreen mode Exit fullscreen mode

2. Service Layer (okxServices.ts)

The service layer handles API calls to our proxy server:

// Example service implementation
class OKXService {
    // Get collections
   // Actual API endpoint: https://www.okx.com/api/v5/mktplace/nft/fractal-ordinals/collections
    async getOrdinals(params: OrdinalParams = {}) {
        return axios.get('/api/ordinals', { params });
    }

    // Get inscriptions
   // Actual API endpoint: https://www.okx.com/api/v5/mktplace/nft/fractal-ordinals/get-valid-inscriptions
    async getInscriptions(params: InscriptionParams) {
        return axios.post('/api/inscriptions', params);
    }

    // Get trade history
   // Actual API endpoint: https://www.okx.com/api/v5/mktplace/nft/fractal-ordinals/trade-history
    async getTradeHistory(params: TradeHistoryParams) {
        return axios.post('/api/trade-history', params);
    }
}
Enter fullscreen mode Exit fullscreen mode

3. React Components

The app uses three main components:

Collections Explorer (OrdinalsFetcher.tsx)

// Displays Ordinals collections with filters for:
// - Collection slug
// - Limit
// - BRC-20 status
Enter fullscreen mode Exit fullscreen mode

Inscriptions Viewer (RetrieveInscriptions.tsx)

// Shows inscriptions for a wallet with:
// - Collection filtering
// - BRC-20 filtering
// - Sort options
Enter fullscreen mode Exit fullscreen mode

Trade History (TradeHistory.tsx)

// Displays trading activity with:
// - Transaction type filtering
// - Wallet address filtering
// - Sort options
// - BRC-20 filtering
// - Collection filtering
Enter fullscreen mode Exit fullscreen mode

Security Features πŸ”’

CORS (Cross-Origin Resource Sharing) enabled:

The server-side code (ordinals-server.cjs) implements CORS by using the cors middleware:

const cors = require('cors');
app.use(cors());
Enter fullscreen mode Exit fullscreen mode
  • This allows the React application to make requests to the server from a different domain.

Request signing with CryptoJS:

  • The okxService.ts file doesn't directly handle the request signing, but it sends the necessary parameters to the server.
  • The server-side code (ordinals-server.cjs) contains the implementation of request signing using CryptoJS:
function preHash(timestamp, method, path, body) {
  const bodyStr = body ? JSON.stringify(body) : '';
  const message = `${timestamp}${method}${path}${bodyStr}`;
  return message;
}

function sign(message, secret) {
  return cryptoJS.enc.Base64.stringify(
    cryptoJS.HmacSHA256(message, secret)
  );
}
Enter fullscreen mode Exit fullscreen mode
  • The preHash function creates a message by combining the timestamp, HTTP method, request path, and request body (if present).
  • The sign function generates a signature by applying the HMAC-SHA256 algorithm to the pre-hash message using the API secret key.
  • The signature is then included in the request headers to ensure the integrity and authenticity of the request.

Environment variables for sensitive data:

  • The server-side code (ordinals-server.cjs) loads environment variables using the dotenv package:
require('dotenv').config();
Enter fullscreen mode Exit fullscreen mode
  • Sensitive information such as the API key, API secret, and API passphrase are stored as environment variables and accessed using process.env:
process.env.OKX_API_KEY
process.env.OKX_API_SECRET
process.env.OKX_API_PASSPHRASE
Enter fullscreen mode Exit fullscreen mode
  • This ensures that sensitive data is not exposed in the codebase and can be securely managed through environment configuration.

Error handling and logging:

  • The okxService.ts and ordinals-server.cjs files include error handling and logging for the API requests
  • Each API request is wrapped in a try-catch block to catch any errors that may occur.

Quick Tips ⚑

  1. Always use environment variables for API credentials
  2. Monitor API response codes in console
  3. Handle pagination for large datasets
  4. Implement proper error handling

Conclusion

Congratulations! You've successfully built a Bitcoin Ordinals explorer using the OKX OS APIs and React with TypeScript. Throughout this guide, we covered:

  • Setting up the project structure and dependencies
  • Integrating the Collections, Inscriptions, and Trade History APIs
  • Implementing features like filtering, sorting, and pagination
  • Applying security best practices such as CORS, request signing, and environment variables
  • Handling errors and edge cases for a smooth user experience

Community & Support 🀝


Found this helpful? Don't forget to check out the resources at the beginning of the article, including the boilerplate code and documentation. Join the OKX OS Community to connect with other developers, and follow Julian on Twitter for more Web3 development content!


This content is provided for informational purposes only and may cover products that are not available in your region. It represents the views of the author(s) and it does not represent the views of OKX. It is not intended to provide (i) investment advice or an investment recommendation; (ii) an offer or solicitation to buy, sell, or hold digital assets, or (iii) financial, accounting, legal, or tax advice. Digital asset holdings, including stablecoins and NFTs, involve a high degree of risk and can fluctuate greatly. You should carefully consider whether trading or holding digital assets is suitable for you in light of your financial condition. Please consult your legal/tax/investment professional for questions about your specific circumstances. Information (including market data and statistical information, if any) appearing in this post is for general information purposes only. While all reasonable care has been taken in preparing this data and graphs, no responsibility or liability is accepted for any errors of fact or omission expressed herein. Both OKX Web3 Wallet and OKX NFT Marketplace are subject to separate terms of service at www.okx.com.

Β© 2024 OKX. This article may be reproduced or distributed in its entirety, or excerpts of 100 words or less of this article may be used, provided such use is non-commercial. Any reproduction or distribution of the entire article must also prominently state: β€œThis article is Β© 2024 OKX and is used with permission.” Permitted excerpts must cite to the name of the article and include attribution, for example β€œBuilding with Fractal Bitcoin: OKX OS Integration Guide, Julian Martinez, Β© 2024 OKX.” No derivative works or other uses of this article are permitted.

Top comments (0)