Skip to content

paulpeter32-coder/stellarkit

Repository files navigation

StellarKit API πŸš€

English πŸ‡ΊπŸ‡Έ | FranΓ§ais πŸ‡«πŸ‡· | EspaΓ±ol πŸ‡ͺπŸ‡Έ

A developer utility REST API for the Stellar blockchain β€” built with Express.js and the official Stellar SDK.

License: MIT Node.js Stellar PRs Welcome Security Audit

StellarKit API wraps the Stellar Horizon API into clean, developer-friendly REST endpoints. It helps developers building on Stellar quickly access fee estimates, account data, transaction history, network status, and asset metadata β€” without having to read through raw Horizon responses.


✨ Features

  • πŸ“Š Network Status β€” Latest ledger info, base fee, protocol version
  • πŸ’Έ Fee Estimation β€” Economy / Standard / Priority fee tiers for any operation count
  • πŸ‘€ Account Info β€” Balances (XLM + all assets), signers, thresholds, spendable balance
  • πŸ“œ Transaction History β€” Paginated transactions and operations per account
  • πŸͺ™ Asset Metadata β€” Stats for any Stellar asset, plus multi-issuer search
  • πŸ›‘οΈ Production-ready β€” Rate limiting, helmet security headers, centralised error handling
  • βœ… Tested β€” Jest test suite with coverage

πŸš€ Getting Started

Prerequisites

  • Node.js >= 18
  • npm >= 9

Installation

git clone https://github.com/stellarkit-lab-devtools/stellarkit-api.git
cd stellarkit-api
npm install
cp .env.example .env

Configuration

Edit .env:

STELLAR_NETWORK=testnet     # or "mainnet"
PORT=3000

Run

# Development (auto-reload)
npm run dev

# Production
npm start

The API will be available at http://localhost:3000.


πŸ“˜ TypeScript Support

stellarkit-api ships with full TypeScript type definitions. All response shapes are typed and exported from types/index.d.ts.

Installation

Types are included automatically β€” no @types/ package needed.

Usage

import type {
  AccountResponse,
  TransactionHistoryResponse,
  OperationHistoryResponse,
  FeeEstimateResponse,
  NetworkStatusResponse,
  AssetResponse,
  AssetSearchResponse,
  AccountBalancesResponse,
  AccountPaymentsResponse,
  AccountSummaryResponse,
  ApiError,
} from 'stellarkit-api'

// Example: typed API response
const response: AccountResponse = await fetch(
  'http://localhost:3000/account/GAAZI4TCR3TY5OJHCTJC2A4QSY6CJWJH5IAJTGKIN2ER7LBNVKOCCWN'
).then(r => r.json())

// Fully typed access to response fields
console.log(response.data.xlm.balance)
console.log(response.data.assets[0].assetCode)

Available Types

Type Description
AccountResponse Response from GET /account/:id
AccountBalancesResponse Response from GET /account/:id/balances
AccountSummaryResponse Response from GET /account/:id/summary
AccountPaymentsResponse Response from GET /account/:id/payments
TransactionHistoryResponse Response from GET /transactions/:id
OperationHistoryResponse Response from GET /transactions/:id/operations
FeeEstimateResponse Response from GET /fee-estimate
NetworkStatusResponse Response from GET /network-status
AssetResponse Response from GET /asset/:code/:issuer
AssetSearchResponse Response from GET /asset/search?code=:code
HealthResponse Response from GET /health
ApiError Standard error response shape
StellarPublicKey Stellar public key type alias
TransactionHash Transaction hash type alias
ISOTimestamp ISO 8601 timestamp type alias
StellarAmount Stellar amount (string) type alias
StellarAsset Stellar asset identifier
AccountBalances Account balances wrapper
XLMBalance XLM balance information
AssetBalance Non-native asset balance
Signer Signer information
Thresholds Account thresholds
AccountFlags Account flags
FeeTier Fee tier information
LedgerInfo Ledger information
TransactionRecord Transaction record
OperationRecord Operation record
PaginationMeta Pagination metadata

Type-Safe Error Handling

import type { ApiError } from 'stellarkit-api'

try {
  const response = await fetch('http://localhost:3000/account/invalid-key')
  const data = await response.json()
  
  if (!response.ok) {
    const error = data as ApiError
    console.error(error.error.type, error.error.message)
  }
} catch (err) {
  console.error('Network error:', err)
}

Query Parameter Types

For endpoints that accept query parameters, use the corresponding Params types:

import type { FeeEstimateParams, TransactionHistoryParams } from 'stellarkit-api'

const feeParams: FeeEstimateParams = {
  operations: 3,
  fresh: true,
}

const txParams: TransactionHistoryParams = {
  limit: 20,
  order: 'asc',
  cursor: 'paging-token-here',
}

πŸ“‘ API Endpoints

GET /

Returns the full list of available endpoints.


GET /health

Service health check.

Response:

{
  "success": true,
  "data": {
    "status": "ok",
    "service": "StellarKit API",
    "version": "1.0.0",
    "network": "testnet"
  }
}

GET /network-status

Returns the latest ledger info, fees, and protocol version.

Response:

{
  "success": true,
  "data": {
    "network": "testnet",
    "latestLedger": {
      "sequence": 123456,
      "closedAt": "2024-07-01T12:00:00Z",
      "transactionCount": 42,
      "operationCount": 89
    },
    "fees": {
      "baseFeeInStroops": 100,
      "baseFeeInXLM": "0.0000100"
    },
    "protocol": { "version": 21 }
  }
}

GET /fee-estimate

Returns Economy / Standard / Priority fee tiers based on live network stats.

Query params:

Param Type Default Description
operations number 1 Number of operations in your transaction

Example:

GET /fee-estimate?operations=3

Response:

{
  "success": true,
  "data": {
    "operationCount": 3,
    "perOperation": {
      "economy":  { "stroops": 100, "xlm": "0.0000100" },
      "standard": { "stroops": 200, "xlm": "0.0000200" },
      "priority": { "stroops": 500, "xlm": "0.0000500" }
    },
    "totalFee": {
      "economy":  { "stroops": 300, "xlm": "0.0000300" },
      "standard": { "stroops": 600, "xlm": "0.0000600" },
      "priority": { "stroops": 1500, "xlm": "0.0001500" }
    }
  }
}

GET /account/:id

Returns full account details for a Stellar public key.

Example:

GET /account/GAAZI4TCR3TY5OJHCTJC2A4QSY6CJWJH5IAJTGKIN2ER7LBNVKOCCWN

Response:

{
  "success": true,
  "data": {
    "accountId": "GAAZI4...",
    "sequence": "12345678",
    "xlm": {
      "balance": "100.0000000",
      "minimumBalance": "1.0000000",
      "spendableBalance": "99.0000000"
    },
    "assets": [...],
    "signers": [...],
    "flags": {...}
  }
}

GET /transactions/:id

Returns paginated transaction history for an account.

Query params:

Param Type Default Description
limit number 10 Number of results (max 200)
order string desc asc or desc
cursor string β€” Pagination cursor from previous response

GET /transactions/:id/operations

Returns paginated operation history for an account. Same query params as above.


GET /asset/:code/:issuer

Returns metadata and statistics for a specific Stellar asset.

Example:

GET /asset/USDC/GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN

GET /asset/:code/:issuer/holders

Returns paginated accounts holding a trustline for a specific Stellar asset.

Query params:

Param Type Default Description
limit number 10 Number of holders (max 200)
order string desc asc or desc
cursor string β€” Pagination cursor from previous response

Example:

GET /asset/USDC/GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN/holders

GET /asset/search?code=:code

Searches for all assets with a given code across all issuers.

Example:

GET /asset/search?code=USDC

πŸ“‘ Streaming & WebSockets

WS /stream/ledgers

Establishes a live, real-time WebSocket connection to stream Stellar ledger updates. As new ledgers are closed on the Stellar blockchain, the API receives them via the Stellar Horizon SDK subscription, parses them, and immediately broadcasts them to connected WebSocket clients.

Client Connection Example (Vanilla JS)

const ws = new WebSocket('ws://localhost:3000/stream/ledgers');

ws.onopen = () => {
  console.log('Connected to StellarKit ledger stream!');
};

ws.onmessage = (event) => {
  const ledger = JSON.parse(event.data);
  console.log('New ledger closed:', ledger);
  // Example output:
  // {
  //   "sequence": 51234567,
  //   "closedAt": "2026-05-26T20:15:00Z",
  //   "baseFee": 100,
  //   "transactionCount": 54
  // }
};

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

ws.onclose = () => {
  console.log('WebSocket connection closed.');
};

Development

To create a funded Stellar testnet account for local development/testing, run:

npm run seed

This script:

  • generates a new keypair
  • funds the public key on Stellar testnet using Friendbot
  • prints the public/private keys to the console

Note: keep the printed private key secret.


πŸ§ͺ Running Tests

npm test

Tests use Jest + Supertest. Coverage report is generated at coverage/.


🀝 Contributing

Contributions are very welcome! This project participates in the Stellar Wave Program on Drips β€” you can earn rewards for solving open issues.

To contribute:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feat/your-feature
  3. Commit your changes: git commit -m "feat: add your feature"
  4. Push and open a Pull Request

Please read CONTRIBUTING.md before submitting.


πŸ“ Project Structure

stellarkit-api/
β”œβ”€β”€ scripts/
β”‚   └── ws-client-demo.js  # Runnable CLI demo for real-time ledger stream
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ config/
β”‚   β”‚   └── stellar.js         # Stellar SDK + Horizon setup
β”‚   β”œβ”€β”€ middleware/
β”‚   β”‚   β”œβ”€β”€ errorHandler.js    # Centralised error formatting
β”‚   β”‚   └── rateLimiter.js     # Rate limiting
β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   β”œβ”€β”€ account.js         # /account endpoints
β”‚   β”‚   β”œβ”€β”€ asset.js           # /asset endpoints
β”‚   β”‚   β”œβ”€β”€ feeEstimate.js     # /fee-estimate endpoint
β”‚   β”‚   β”œβ”€β”€ networkStatus.js   # /network-status endpoint
β”‚   β”‚   └── transactions.js    # /transactions endpoints
β”‚   β”œβ”€β”€ utils/
β”‚   β”‚   β”œβ”€β”€ response.js        # Response helpers
β”‚   β”‚   └── validators.js      # Input validation helpers
β”‚   β”œβ”€β”€ index.js               # App entry point
β”‚   └── websocket.js           # WebSocket stream handler
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ api.test.js
β”‚   └── websocket.test.js      # WebSocket stream integration tests
β”œβ”€β”€ .env.example
β”œβ”€β”€ package.json
└── README.md

🌐 Stellar Resources


πŸ“„ License

MIT

About

issue solving

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors