FortiBlox LogoFortiBlox Docs
NexusComplete Examples

Complete API Examples

Every endpoint documented with real, working code you can copy and run immediately - JavaScript, Python, cURL, and Rust examples.

FortiBlox API - Complete Examples Library

Every endpoint documented with real, working code you can copy and run immediately.

Table of Contents

  1. RPC Methods - X1 Blockchain JSON-RPC API
  2. Geyser HTTP API - REST endpoints for blockchain data
  3. WebSocket Streaming - Real-time data
  4. gRPC Streaming - High-performance streaming

RPC Methods

All RPC calls use POST requests to https://nexus.fortiblox.com/rpc with JSON-RPC 2.0 format.

Example 1: Get Account Balance

What it does: Check how much SOL is in any wallet.

curl -X POST "https://nexus.fortiblox.com/rpc" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "getBalance",
    "params": ["vines1vzrYbzLMRdu58ou5XTby4qAqVRLmqo36NKPTg"]
  }'
// JavaScript/Node.js
const axios = require('axios');

async function getWalletBalance(walletAddress) {
  const response = await axios.post(
    'https://nexus.fortiblox.com/rpc',
    {
      jsonrpc: '2.0',
      id: 1,
      method: 'getBalance',
      params: [walletAddress]
    },
    {
      headers: {
        'X-API-Key': 'YOUR_API_KEY',
        'Content-Type': 'application/json'
      }
    }
  );

  const lamports = response.data.result.value;
  const sol = lamports / 1e9;  //  Convert to SOL

  console.log(`Balance: ${sol} SOL (${lamports.toLocaleString()} lamports)`);
  return sol;
}

// Usage
getWalletBalance('vines1vzrYbzLMRdu58ou5XTby4qAqVRLmqo36NKPTg');
# Python
import requests

def get_wallet_balance(wallet_address):
    response = requests.post(
        'https://nexus.fortiblox.com/rpc',
        json={
            'jsonrpc': '2.0',
            'id': 1,
            'method': 'getBalance',
            'params': [wallet_address]
        },
        headers={'X-API-Key': 'YOUR_API_KEY'}
    )

    lamports = response.json()['result']['value']
    sol = lamports / 1_000_000_000

    print(f'Balance: {sol} SOL ({lamports:,} lamports)')
    return sol

# Usage
get_wallet_balance('vines1vzrYbzLMRdu58ou5XTby4qAqVRLmqo36NKPTg')

Expected Response:

{
  "jsonrpc": "2.0",
  "result": {
    "context": { "slot": 123456789 },
    "value": 1500000000
  },
  "id": 1
}

Example 2: Get Recent Block Information

What it does: Fetch details about a specific block on the blockchain.

// JavaScript - Get latest block
async function getLatestBlock() {
  // First, get the latest slot number
  const slotResponse = await axios.post(
    'https://nexus.fortiblox.com/rpc',
    {
      jsonrpc: '2.0',
      id: 1,
      method: 'getSlot'
    },
    { headers: { 'X-API-Key': 'YOUR_API_KEY' } }
  );

  const slot = slotResponse.data.result;

  // Then get the block data
  const blockResponse = await axios.post(
    'https://nexus.fortiblox.com/rpc',
    {
      jsonrpc: '2.0',
      id: 2,
      method: 'getBlock',
      params: [slot, { encoding: 'json', maxSupportedTransactionVersion: 0 }]
    },
    { headers: { 'X-API-Key': 'YOUR_API_KEY' } }
  );

  const block = blockResponse.data.result;

  console.log(`Block ${slot}:`);
  console.log(`  Transactions: ${block.transactions.length}`);
  console.log(`  Block time: ${new Date(block.blockTime * 1000)}`);
  console.log(`  Previous block: ${block.previousBlockhash}`);

  return block;
}

getLatestBlock();
# Python - Get latest block
import requests
from datetime import datetime

def get_latest_block():
    # Get current slot
    slot_response = requests.post(
        'https://nexus.fortiblox.com/rpc',
        json={'jsonrpc': '2.0', 'id': 1, 'method': 'getSlot'},
        headers={'X-API-Key': 'YOUR_API_KEY'}
    )
    slot = slot_response.json()['result']

    # Get block data
    block_response = requests.post(
        'https://nexus.fortiblox.com/rpc',
        json={
            'jsonrpc': '2.0',
            'id': 2,
            'method': 'getBlock',
            'params': [slot, {'encoding': 'json', 'maxSupportedTransactionVersion': 0}]
        },
        headers={'X-API-Key': 'YOUR_API_KEY'}
    )

    block = block_response.json()['result']

    print(f"Block {slot}:")
    print(f"  Transactions: {len(block['transactions'])}")
    print(f"  Block time: {datetime.fromtimestamp(block['blockTime'])}")
    print(f"  Previous block: {block['previousBlockhash']}")

    return block

get_latest_block()

Example 3: Send SOL Transaction

What it does: Send SOL from one wallet to another.

// JavaScript - Send SOL (requires @solana/web3.js)
const { Connection, Keypair, Transaction, SystemProgram, LAMPORTS_PER_SOL } = require('@solana/web3.js');

async function sendSOL(fromKeypair, toAddress, amountSOL) {
  // Create connection using FortiBlox RPC
  const connection = new Connection('https://nexus.fortiblox.com/rpc', {
    httpHeaders: { 'X-API-Key': 'YOUR_API_KEY' }
  });

  // Create transaction
  const transaction = new Transaction().add(
    SystemProgram.transfer({
      fromPubkey: fromKeypair.publicKey,
      toPubkey: toAddress,
      lamports: amountSOL * LAMPORTS_PER_SOL
    })
  );

  // Sign and send
  const signature = await connection.sendTransaction(transaction, [fromKeypair]);

  console.log(`Transaction sent!`);
  console.log(`   Signature: ${signature}`);
  console.log(`   Explorer: https://explorer.solana.com/tx/${signature}`);

  // Wait for confirmation
  await connection.confirmTransaction(signature);
  console.log(`Transaction confirmed!`);

  return signature;
}

// Usage
const fromWallet = Keypair.fromSecretKey(YOUR_SECRET_KEY);
const toWallet = 'RECIPIENT_WALLET_ADDRESS';
sendSOL(fromWallet, toWallet, 0.1); // Send 0.1 SOL

Example 4: Get Transaction Details

What it does: Look up any transaction by its signature.

// JavaScript - Get transaction details
async function getTransaction(signature) {
  const response = await axios.post(
    'https://nexus.fortiblox.com/rpc',
    {
      jsonrpc: '2.0',
      id: 1,
      method: 'getTransaction',
      params: [signature, { encoding: 'json', maxSupportedTransactionVersion: 0 }]
    },
    { headers: { 'X-API-Key': 'YOUR_API_KEY' } }
  );

  const tx = response.data.result;

  console.log(`Transaction ${signature}:`);
  console.log(`  Block: ${tx.slot}`);
  console.log(`  Status: ${tx.meta.err ? 'Failed' : 'Success'}`);
  console.log(`  Fee: ${tx.meta.fee / 1e9} SOL`);
  console.log(`  Timestamp: ${new Date(tx.blockTime * 1000)}`);

  return tx;
}

// Usage
getTransaction('YOUR_TRANSACTION_SIGNATURE_HERE');

Geyser HTTP API

REST endpoints for querying blockchain data.

Example 5: Get Latest Blocks

What it does: Fetch the most recent blocks on X1 Blockchain.

curl -X GET "https://nexus.fortiblox.com/geyser/blocks?limit=10" \
  -H "X-API-Key: YOUR_API_KEY"
// JavaScript - Get and display latest blocks
async function getLatestBlocks(limit = 10) {
  const response = await axios.get(
    `https://nexus.fortiblox.com/geyser/blocks?limit=${limit}`,
    { headers: { 'X-API-Key': 'YOUR_API_KEY' } }
  );

  console.log(`Latest ${limit} Blocks:`);
  console.log('─'.repeat(80));

  response.data.data.forEach((block, index) => {
    console.log(`\n${index + 1}. Slot: ${block.slot}`);
    console.log(`   Hash: ${block.blockhash}`);
    console.log(`   Transactions: ${block.transaction_count}`);
    console.log(`   Time: ${new Date(block.block_time * 1000).toLocaleString()}`);
  });

  return response.data.data;
}

getLatestBlocks(10);
# Python - Get latest blocks
import requests
from datetime import datetime

def get_latest_blocks(limit=10):
    response = requests.get(
        f'https://nexus.fortiblox.com/geyser/blocks?limit={limit}',
        headers={'X-API-Key': 'YOUR_API_KEY'}
    )

    blocks = response.json()['data']

    print(f'Latest {limit} Blocks:')
    print('─' * 80)

    for index, block in enumerate(blocks, 1):
        print(f"\n{index}. Slot: {block['slot']}")
        print(f"   Hash: {block['blockhash']}")
        print(f"   Transactions: {block['transaction_count']}")
        print(f"   Time: {datetime.fromtimestamp(block['block_time'])}")

    return blocks

get_latest_blocks(10)

Example 6: Search Transactions

What it does: Find transactions matching specific criteria.

// JavaScript - Search for transactions by wallet
async function searchTransactions(walletAddress, limit = 20) {
  const response = await axios.get(
    'https://nexus.fortiblox.com/geyser/transactions',
    {
      params: {
        address: walletAddress,
        limit: limit
      },
      headers: { 'X-API-Key': 'YOUR_API_KEY' }
    }
  );

  console.log(`Transactions for ${walletAddress}:`);

  response.data.data.forEach((tx, index) => {
    const status = tx.err ? 'Failed' : 'Success';
    console.log(`\n${index + 1}. ${status} ${tx.signature.slice(0, 20)}...`);
    console.log(`   Slot: ${tx.slot}`);
    console.log(`   Time: ${new Date(tx.block_time * 1000).toLocaleString()}`);
  });

  return response.data.data;
}

// Usage
searchTransactions('YOUR_WALLET_ADDRESS', 20);

Example 7: Get Account Data

What it does: Fetch complete account information.

// JavaScript - Get account data
async function getAccountData(accountAddress) {
  const response = await axios.get(
    `https://nexus.fortiblox.com/geyser/accounts/${accountAddress}`,
    { headers: { 'X-API-Key': 'YOUR_API_KEY' } }
  );

  const account = response.data.data;

  console.log(`Account: ${accountAddress}`);
  console.log(`   Owner: ${account.owner}`);
  console.log(`   Balance: ${account.lamports / 1e9} SOL`);
  console.log(`   Executable: ${account.executable ? 'Yes (Program)' : 'No'}`);
  console.log(`   Data size: ${account.data.length} bytes`);

  return account;
}

getAccountData('YOUR_ACCOUNT_ADDRESS');

WebSocket Streaming

Real-time blockchain data streaming.

Example 8: Stream New Transactions

What it does: Get notified instantly when new transactions occur.

// JavaScript - Stream transactions in real-time
const WebSocket = require('ws');

function streamTransactions() {
  const ws = new WebSocket('wss://nexus.fortiblox.com/stream', {
    headers: { 'X-API-Key': 'YOUR_API_KEY' }
  });

  ws.on('open', () => {
    console.log('Connected to FortiBlox WebSocket');

    // Subscribe to transaction stream
    ws.send(JSON.stringify({
      method: 'subscribe',
      params: ['transactions']
    }));
  });

  ws.on('message', (data) => {
    const tx = JSON.parse(data);
    console.log(`\nNew Transaction!`);
    console.log(`   Signature: ${tx.signature}`);
    console.log(`   Slot: ${tx.slot}`);
    console.log(`   Status: ${tx.err ? 'Failed' : 'Success'}`);
  });

  ws.on('error', (error) => {
    console.error('WebSocket error:', error);
  });

  ws.on('close', () => {
    console.log('WebSocket connection closed');
  });
}

streamTransactions();
# Python - Stream transactions
import websocket
import json

def on_message(ws, message):
    tx = json.loads(message)
    status = 'Failed' if tx['err'] else 'Success'
    print(f"\nNew Transaction!")
    print(f"   Signature: {tx['signature']}")
    print(f"   Slot: {tx['slot']}")
    print(f"   Status: {status}")

def on_open(ws):
    print('Connected to FortiBlox WebSocket')
    ws.send(json.dumps({
        'method': 'subscribe',
        'params': ['transactions']
    }))

ws = websocket.WebSocketApp(
    'wss://nexus.fortiblox.com/stream',
    header={'X-API-Key': 'YOUR_API_KEY'},
    on_message=on_message,
    on_open=on_open
)

ws.run_forever()

Example 9: Monitor Specific Wallet

What it does: Get real-time notifications when a specific wallet receives or sends SOL.

// JavaScript - Monitor wallet activity
function monitorWallet(walletAddress) {
  const ws = new WebSocket('wss://nexus.fortiblox.com/stream', {
    headers: { 'X-API-Key': 'YOUR_API_KEY' }
  });

  ws.on('open', () => {
    console.log(`Monitoring wallet: ${walletAddress}`);

    ws.send(JSON.stringify({
      method: 'subscribe',
      params: ['account_updates', { addresses: [walletAddress] }]
    }));
  });

  ws.on('message', (data) => {
    const update = JSON.parse(data);
    const newBalance = update.lamports / 1e9;

    console.log(`\nBalance Update:`);
    console.log(`   New balance: ${newBalance} SOL`);
    console.log(`   Slot: ${update.slot}`);
  });
}

monitorWallet('YOUR_WALLET_ADDRESS');

Error Handling

Always handle errors properly in production code:

// JavaScript - Complete error handling example
async function robustAPICall(method, params = []) {
  try {
    const response = await axios.post(
      'https://nexus.fortiblox.com/rpc',
      { jsonrpc: '2.0', id: 1, method, params },
      {
        headers: { 'X-API-Key': process.env.FORTIBLOX_API_KEY },
        timeout: 30000  // 30 second timeout
      }
    );

    // Check for JSON-RPC errors
    if (response.data.error) {
      throw new Error(`RPC Error: ${response.data.error.message}`);
    }

    return response.data.result;

  } catch (error) {
    if (error.response) {
      // Handle HTTP errors
      if (error.response.status === 429) {
        console.error('Rate limit exceeded. Upgrade your plan or wait.');
        const resetTime = error.response.headers['x-ratelimit-reset'];
        console.log(`   Resets at: ${new Date(resetTime * 1000)}`);
      } else if (error.response.status === 401) {
        console.error('Invalid API key. Check your credentials.');
      } else {
        console.error(`HTTP ${error.response.status}: ${error.response.data.message}`);
      }
    } else if (error.request) {
      // Network error
      console.error('Network error. Check your connection.');
    } else {
      // Other errors
      console.error('Error:', error.message);
    }
    throw error;
  }
}

// Usage with automatic retry
async function callWithRetry(method, params, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await robustAPICall(method, params);
    } catch (error) {
      if (attempt === maxRetries) throw error;
      console.log(`   Retry ${attempt}/${maxRetries}...`);
      await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
    }
  }
}

Next Steps


Need more examples? Check out our GitHub repository with 100+ code samples!