CHAPTER 5

Phase 2: API Interface

Building Robust Cryptocurrency APIs

As cryptocurrency systems mature beyond basic data structures, the need for standardized, secure, and efficient API interfaces becomes paramount. Phase 2 of the WIA Cryptocurrency Standard focuses on defining the API layer that enables applications, wallets, and exchanges to interact with blockchain networks in a consistent and reliable manner.

This chapter explores the comprehensive API interface specification, covering wallet operations, exchange integrations, node communications, authentication mechanisms, and rate limiting strategies. Whether you're building a mobile wallet app, integrating cryptocurrency payments into an e-commerce platform, or developing a trading platform, understanding these API patterns is essential for creating secure and scalable cryptocurrency applications.

1. API Architecture Overview

The WIA Cryptocurrency API architecture follows RESTful principles with JSON-based request/response formats, providing a clear separation between client applications and blockchain infrastructure. This design enables flexibility, scalability, and ease of integration across diverse platforms and programming languages.

Core Architecture Principles

API Layer Purpose Primary Users Key Features
Wallet API User account & transaction management Mobile apps, Web wallets Balance queries, Send/Receive, History
Exchange API Trading operations Trading platforms, Bots Order management, Market data, Trades
Node API Blockchain interaction Infrastructure operators Block data, Network status, Mempool
Market Data API Price & volume information Analytics platforms, Dashboards Tickers, Charts, Historical data

2. Wallet API Specification

The Wallet API provides a comprehensive interface for managing cryptocurrency accounts, enabling applications to create wallets, check balances, send and receive transactions, and query transaction history. This API is designed with security as the foremost priority, implementing multiple layers of protection for private keys and sensitive operations.

Account Management Endpoints

// Create New Wallet
POST /api/v1/wallets
Request:
{
  "currency": "BTC",
  "label": "My Bitcoin Wallet",
  "password": "securePassword123"
}

Response:
{
  "walletId": "wlt_8f3a7b2c9d1e",
  "address": "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa",
  "publicKey": "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f",
  "createdAt": "2025-01-15T10:30:00Z",
  "balance": "0.00000000"
}

// Get Wallet Balance
GET /api/v1/wallets/{walletId}/balance

Response:
{
  "walletId": "wlt_8f3a7b2c9d1e",
  "currency": "BTC",
  "confirmed": "1.25000000",
  "unconfirmed": "0.05000000",
  "total": "1.30000000",
  "fiatValue": {
    "USD": 58500.00,
    "EUR": 49200.00
  },
  "lastUpdated": "2025-01-15T12:45:30Z"
}

// List All Wallets
GET /api/v1/wallets?currency=BTC&limit=50&offset=0

Response:
{
  "wallets": [
    {
      "walletId": "wlt_8f3a7b2c9d1e",
      "label": "My Bitcoin Wallet",
      "address": "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa",
      "currency": "BTC",
      "balance": "1.30000000"
    }
  ],
  "total": 1,
  "limit": 50,
  "offset": 0
}

Transaction Operations

// Send Transaction
POST /api/v1/wallets/{walletId}/send
Request:
{
  "toAddress": "3J98t1WpEZ73CNmYviecrnyiWrnqRhWNLy",
  "amount": "0.05000000",
  "fee": "0.00001000",
  "note": "Payment for services",
  "password": "securePassword123"
}

Response:
{
  "transactionId": "tx_a3f7e2b8c1d4",
  "txHash": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
  "status": "pending",
  "fromAddress": "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa",
  "toAddress": "3J98t1WpEZ73CNmYviecrnyiWrnqRhWNLy",
  "amount": "0.05000000",
  "fee": "0.00001000",
  "confirmations": 0,
  "estimatedConfirmationTime": "2025-01-15T13:00:00Z"
}

// Get Transaction History
GET /api/v1/wallets/{walletId}/transactions?limit=20&offset=0

Response:
{
  "transactions": [
    {
      "transactionId": "tx_a3f7e2b8c1d4",
      "type": "send",
      "amount": "0.05000000",
      "address": "3J98t1WpEZ73CNmYviecrnyiWrnqRhWNLy",
      "confirmations": 3,
      "timestamp": "2025-01-15T12:30:00Z",
      "status": "confirmed"
    }
  ],
  "total": 15,
  "limit": 20,
  "offset": 0
}

3. Exchange API Interface

Exchange APIs enable trading operations across cryptocurrency markets, providing access to order books, market data, and trading functionality. These APIs must handle high-frequency requests while maintaining data consistency and security.

Market Data Endpoints

// Get Market Ticker
GET /api/v1/markets/BTC-USD/ticker

Response:
{
  "symbol": "BTC-USD",
  "lastPrice": "45000.00",
  "bidPrice": "44995.00",
  "askPrice": "45005.00",
  "volume24h": "1250.50000000",
  "high24h": "45800.00",
  "low24h": "44200.00",
  "priceChange24h": "+2.5",
  "timestamp": "2025-01-15T12:45:00Z"
}

// Get Order Book
GET /api/v1/markets/BTC-USD/orderbook?depth=20

Response:
{
  "symbol": "BTC-USD",
  "bids": [
    ["44995.00", "0.50000000"],
    ["44990.00", "1.25000000"],
    ["44985.00", "0.75000000"]
  ],
  "asks": [
    ["45005.00", "0.45000000"],
    ["45010.00", "1.10000000"],
    ["45015.00", "0.80000000"]
  ],
  "timestamp": "2025-01-15T12:45:00Z",
  "sequenceId": 1234567890
}

Trading Operations

Order Type Description Use Case Parameters
Market Order Execute immediately at best price Quick entry/exit symbol, side, quantity
Limit Order Execute at specified price or better Price control symbol, side, price, quantity
Stop-Loss Trigger at specified price Risk management symbol, side, stopPrice, quantity
Stop-Limit Limit order after stop triggered Controlled exit symbol, side, stopPrice, limitPrice, quantity
// Place Limit Order
POST /api/v1/orders
Request:
{
  "symbol": "BTC-USD",
  "type": "limit",
  "side": "buy",
  "price": "44500.00",
  "quantity": "0.10000000",
  "timeInForce": "GTC"
}

Response:
{
  "orderId": "ord_7b3e9f2a8c1d",
  "symbol": "BTC-USD",
  "type": "limit",
  "side": "buy",
  "price": "44500.00",
  "quantity": "0.10000000",
  "status": "open",
  "filled": "0.00000000",
  "remaining": "0.10000000",
  "createdAt": "2025-01-15T12:50:00Z"
}

// Cancel Order
DELETE /api/v1/orders/{orderId}

Response:
{
  "orderId": "ord_7b3e9f2a8c1d",
  "status": "cancelled",
  "cancelledAt": "2025-01-15T13:00:00Z"
}

4. Node API Communication

Node APIs provide direct access to blockchain infrastructure, allowing developers to query block data, submit transactions to the network, and monitor network health. These APIs are essential for building blockchain explorers, validators, and custom infrastructure tools.

Blockchain Query Endpoints

// Get Block by Height
GET /api/v1/blocks/750000

Response:
{
  "height": 750000,
  "hash": "00000000000000000003dc5b1b70d6b00e2a87e1b6e0c5c5c0a2e4e0a5c1b0e3",
  "previousHash": "00000000000000000001a8f7b9c3d5e2f0a8b6c4d2e0f8a6b4c2d0e8f6a4b2c",
  "merkleRoot": "a7b3c2d1e0f9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b9c8d7e6f5a4b",
  "timestamp": "2025-01-15T12:00:00Z",
  "difficulty": 23137439666472.00,
  "nonce": 2758542859,
  "transactions": 2543,
  "size": 1245678,
  "confirmations": 125
}

// Get Transaction Details
GET /api/v1/transactions/{txHash}

Response:
{
  "txHash": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
  "blockHeight": 749875,
  "confirmations": 125,
  "timestamp": "2025-01-15T11:30:00Z",
  "inputs": [
    {
      "address": "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa",
      "value": "0.06000000"
    }
  ],
  "outputs": [
    {
      "address": "3J98t1WpEZ73CNmYviecrnyiWrnqRhWNLy",
      "value": "0.05000000"
    },
    {
      "address": "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa",
      "value": "0.00999000"
    }
  ],
  "fee": "0.00001000",
  "size": 225
}

Network Status Monitoring

// Get Network Info
GET /api/v1/network/info

Response:
{
  "network": "mainnet",
  "version": "23.0.0",
  "protocolVersion": 70016,
  "blocks": 750125,
  "connections": 8,
  "difficulty": 23137439666472.00,
  "hashrate": "180.5 EH/s",
  "mempool": {
    "size": 15234,
    "bytes": 45678901,
    "usage": 85234567
  },
  "warnings": []
}

// Get Mempool Transactions
GET /api/v1/mempool?limit=50

Response:
{
  "transactions": [
    {
      "txHash": "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b",
      "size": 225,
      "fee": "0.00002500",
      "feeRate": "11.11",
      "firstSeen": "2025-01-15T12:45:00Z"
    }
  ],
  "total": 15234
}

5. Authentication Mechanisms

Securing API access is critical in cryptocurrency systems where unauthorized access can lead to financial loss. The WIA standard supports multiple authentication methods, each appropriate for different use cases and security requirements.

API Key Authentication

API keys provide a simple yet effective authentication method for server-to-server communication and automated systems. Each API key consists of a public identifier and a private secret that must be kept secure.

// API Key Generation
POST /api/v1/auth/keys
Request:
{
  "name": "Trading Bot Key",
  "permissions": ["read", "trade"],
  "ipWhitelist": ["203.0.113.0/24"]
}

Response:
{
  "keyId": "key_9a8b7c6d5e4f",
  "apiKey": "wia_pk_REPLACE_WITH_YOUR_API_KEY_PLACEHOLDER",
  "apiSecret": "wia_sk_REPLACE_WITH_YOUR_API_KEY_PLACEHOLDER",
  "permissions": ["read", "trade"],
  "createdAt": "2025-01-15T13:00:00Z",
  "expiresAt": "2026-01-15T13:00:00Z"
}

// Using API Key in Requests
GET /api/v1/wallets
Headers:
  X-API-Key: wia_pk_REPLACE_WITH_YOUR_API_KEY_PLACEHOLDER
  X-API-Signature: sha256_hmac(request_data, api_secret)
  X-API-Timestamp: 1642251600000
⚠️ API Key Security: Never expose API secrets in client-side code or public repositories. Store secrets in environment variables or secure key management systems. Rotate keys regularly and immediately revoke compromised keys.

OAuth 2.0 Integration

OAuth 2.0 provides delegated authorization, allowing third-party applications to access user resources without exposing credentials. This is the preferred method for web and mobile applications where users need to grant limited access to their accounts.

OAuth Flow Use Case Security Level Token Lifetime
Authorization Code Web applications High Access: 1h, Refresh: 90d
PKCE Mobile/SPA apps High Access: 1h, Refresh: 90d
Client Credentials Server-to-server Medium Access: 24h
Refresh Token Token renewal High 90 days

6. Rate Limiting Strategies

Rate limiting protects API infrastructure from abuse and ensures fair resource allocation among users. The WIA standard implements tiered rate limiting based on account type, endpoint sensitivity, and authentication method.

Rate Limit Tiers

Account Tier Requests/Minute Requests/Hour Burst Limit WebSocket Connections
Anonymous 10 100 20 1
Free Tier 60 1,000 100 5
Pro Tier 300 10,000 500 25
Enterprise 1,000 100,000 2,000 100

Rate Limit Headers

// Response Headers for Rate Limiting
HTTP/1.1 200 OK
X-RateLimit-Limit: 300
X-RateLimit-Remaining: 245
X-RateLimit-Reset: 1642252200
X-RateLimit-Window: 60
Retry-After: 45

// Rate Limit Exceeded Response
HTTP/1.1 429 Too Many Requests
{
  "error": "rate_limit_exceeded",
  "message": "API rate limit exceeded",
  "limit": 300,
  "remaining": 0,
  "resetAt": "2025-01-15T13:10:00Z",
  "retryAfter": 45
}

7. WebSocket Real-Time APIs

For applications requiring real-time updates—such as trading platforms displaying live price feeds or wallets showing instant transaction confirmations—WebSocket connections provide efficient, low-latency bidirectional communication.

// WebSocket Connection
ws://api.wiacrypto.com/v1/stream

// Subscribe to Price Updates
{
  "action": "subscribe",
  "channels": ["ticker.BTC-USD", "ticker.ETH-USD"]
}

// Receive Price Updates
{
  "channel": "ticker.BTC-USD",
  "data": {
    "symbol": "BTC-USD",
    "price": "45125.50",
    "volume": "1250.75",
    "timestamp": "2025-01-15T13:15:30.500Z"
  }
}

// Subscribe to Transaction Confirmations
{
  "action": "subscribe",
  "channels": ["tx.1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa"]
}

// Receive Confirmation Updates
{
  "channel": "tx.1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa",
  "data": {
    "txHash": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
    "confirmations": 3,
    "blockHeight": 749875,
    "timestamp": "2025-01-15T13:15:35.000Z"
  }
}

8. Error Handling and Response Codes

Consistent error handling helps developers quickly diagnose and resolve issues. The WIA API standard uses HTTP status codes combined with detailed error messages in JSON format.

HTTP Code Error Type Description Action
400 Bad Request Invalid parameters or malformed request Check request format and parameters
401 Unauthorized Missing or invalid authentication Provide valid API key or OAuth token
403 Forbidden Insufficient permissions Request higher permissions or use different account
404 Not Found Resource doesn't exist Verify resource ID or endpoint
429 Rate Limited Too many requests Wait and retry, upgrade tier
500 Server Error Internal server error Retry with exponential backoff
503 Service Unavailable Temporary service disruption Check status page, retry later
// Error Response Format
{
  "error": {
    "code": "insufficient_balance",
    "message": "Wallet balance insufficient for transaction",
    "details": {
      "required": "0.05001000",
      "available": "0.03000000",
      "currency": "BTC"
    },
    "requestId": "req_a1b2c3d4e5f6",
    "timestamp": "2025-01-15T13:20:00Z",
    "documentation": "https://docs.wiacrypto.com/errors/insufficient_balance"
  }
}

9. API Versioning and Deprecation

As cryptocurrency standards evolve, maintaining backward compatibility while introducing new features requires careful API versioning and deprecation policies.

Versioning Strategy: The WIA standard uses URL-based versioning (e.g., /api/v1/, /api/v2/) to clearly separate API versions. Versions are maintained for a minimum of 12 months after deprecation announcement, giving developers ample time to migrate.

Version Migration Path

// Deprecation Warning Header
HTTP/1.1 200 OK
X-API-Version: v1
X-API-Deprecated: true
X-API-Sunset: 2026-01-15T00:00:00Z
X-API-Migrate-To: /api/v2/wallets
Link: <https://docs.wiacrypto.com/migration/v1-to-v2>; rel="migration-guide"

// Version Information Endpoint
GET /api/version

Response:
{
  "current": "v2",
  "supported": ["v1", "v2"],
  "deprecated": {
    "v1": {
      "sunsetDate": "2026-01-15T00:00:00Z",
      "migrationGuide": "https://docs.wiacrypto.com/migration/v1-to-v2"
    }
  }
}

10. API Security Best Practices

Security in cryptocurrency APIs extends beyond authentication to encompass request validation, data encryption, audit logging, and protection against common attacks.

Security Checklist

🔒 Critical Security Warning: Cryptocurrency APIs are prime targets for attackers. Implement defense in depth with multiple security layers. Never trust client-side validation alone. Always validate on the server, use parameterized queries, and implement proper access controls.

📚 Chapter Summary

Key Takeaways:

❓ Review Questions

  1. Explain the difference between API key authentication and OAuth 2.0. When would you choose each method for a cryptocurrency application?
  2. Describe the structure and purpose of a wallet API balance query. What information does it return and why are both confirmed and unconfirmed balances important?
  3. What are the four main order types supported by exchange APIs? Provide use cases for each and explain how they differ in execution.
  4. How does rate limiting protect cryptocurrency API infrastructure? Design a rate limiting strategy for a three-tier system (free, pro, enterprise) and justify your limits.
  5. Explain the WebSocket real-time API pattern. What advantages does it offer over traditional REST polling for cryptocurrency price feeds?
  6. What security measures should be implemented to protect cryptocurrency APIs beyond basic authentication? List at least five best practices and explain their importance.

🔮 Looking Ahead to Chapter 6

With a solid understanding of the API interface layer, we'll dive deeper into the underlying blockchain infrastructure in Chapter 6: Phase 3 Protocol. We'll explore P2P networking fundamentals, consensus mechanisms (Proof of Work, Proof of Stake, Delegated Proof of Stake), transaction propagation across the network, and block validation processes. Understanding these protocol-level concepts is essential for building robust cryptocurrency systems and debugging network-related issues.

Korea Standardization Infrastructure Mapping

Korea operates a comprehensive standards governance system through inter-ministerial cooperation. National Standards Council (under Prime Minister's Office, per Framework Act on National Standards Article 5) coordinates KATS (Korean Agency for Technology and Standards), MFDS (Ministry of Food and Drug Safety), MOTIE (Ministry of Trade, Industry and Energy), MSIT (Ministry of Science and ICT), MOIS (Ministry of the Interior and Safety), MOE (Ministry of Environment), MOHW (Ministry of Health and Welfare), MND (Ministry of National Defense), MCST (Ministry of Culture, Sports and Tourism), MOFA (Ministry of Foreign Affairs), MOJ (Ministry of Justice), and FSC (Financial Services Commission). Accreditation and Testing: KOLAS (Korea Laboratory Accreditation Scheme) accredits 800+ testing laboratories. KAS (Korea Accreditation System) accredits 50+ certification bodies. KTC (Korea Testing Certification), KTR (Korea Testing & Research Institute), KTL (Korea Testing Laboratory), and KCL (Korea Conformity Laboratories) provide conformance testing. Telecom and Cyber: KCC (Korea Communications Commission), KCA (Korea Communications Agency), TTA (Telecommunications Technology Association), IITP (Institute for Information & Communications Technology Planning & Evaluation), NIPA (National IT Industry Promotion Agency), KISA (Korea Internet & Security Agency), KCMVP (Korea Cryptographic Module Validation Program), NIS (National Intelligence Service), NSR (National Security Research Institute), and NCSC (National Cyber Security Center). National R&D Centers: KIST, ETRI, KAIST, Seoul National University, Yonsei University, Korea University, POSTECH, UNIST, GIST, DGIST, KISTI, KIER, KIMM, KRICT, KFRI, KRIBB. International Standards Cooperation: ISO TC/SC Korean secretariats, IEC TC/SC Korean secretariats, ITU-T Study Group Korean chairs, 3GPP RAN/SA Korean chairs, IEEE 802 Korean chairs, W3C Korea office, OASIS Korea office, IETF Korea cooperation, OECD CSTP, UN ESCAP, APEC SCSC Korean cooperation. Korean Industrial Standards (KS) Catalog: KS X (Information) 25,000+, KS A (Basic) 15,000+, KS B (Machinery) 25,000+, KS C (Electrical) 18,000+, KS D (Metallurgy) 12,000+, KS E (Mining) 5,000+, KS F (Construction) 18,000+, KS H (Food) 8,000+, KS I (Environment) 5,000+, KS J (Biology) 3,000+, KS K (Textile) 15,000+, KS L (Ceramics) 7,000+, KS M (Chemistry) 12,000+, KS P (Medical) 5,000+, KS Q (Quality Mgmt) 4,000+, KS R (Transport) 12,000+, KS S (Service) 3,000+, KS T (Packaging) 4,000+, KS V (Shipbuilding) 5,000+, KS W (Aerospace) 3,000+ — totaling 220,000+ Korean Industrial Standards. Key Acts: Personal Information Protection Act (Act 19234, effective Sept 15, 2024), Electronic Government Act, Electronic Signature Act, Act on Promotion of Information and Communications Network Utilization and Information Protection, Information and Communications Infrastructure Protection Act, Data Industry Act, Public Data Act, AI Framework Act (Act 20212, effective July 2026), Industrial Technology Innovation Promotion Act, Framework Act on Science and Technology — 70+ Korean standardization-related laws.