Skip to content

Latest commit

 

History

History
615 lines (508 loc) · 12.5 KB

File metadata and controls

615 lines (508 loc) · 12.5 KB

Collateral Vault API Documentation

Overview

The Collateral Vault Backend provides a comprehensive REST API and WebSocket interface for managing collateral on Solana.

Base URL: http://127.0.0.1:3000
WebSocket: ws://127.0.0.1:3000/ws


Part 4: Integration & APIs

1. REST API Endpoints

System Endpoints

GET /

Get API overview and available endpoints.

Response:

{
  "service": "collateral-vault-backend",
  "version": "0.1.0",
  "status": "running",
  "endpoints": { ... }
}
GET /health

Health check endpoint.

Response:

{
  "status": "ok",
  "service": "vault-backend",
  "timestamp": "2026-01-12T18:49:40.136695300+00:00"
}
GET /api/status

Get system status including database and Solana connection.

Response:

{
  "database": {
    "status": "connected",
    "test": "6 tables found"
  },
  "solana_rpc": "http://127.0.0.1:8899",
  "vault_program_id": "Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS",
  "timestamp": "2026-01-12T18:49:40.136695300+00:00"
}

Vault API Endpoints

POST /vault/initialize

Create a new vault for a user.

Request Body:

{
  "user_pubkey": "9hQjYAiAeBpeCZ2yS1cuZorgcohnCG9qksa1V6pmev7h",
  "initial_deposit": 1000000  // optional, in lamports
}

Success Response (201):

{
  "success": true,
  "data": {
    "vault_id": 1,
    "user_pubkey": "9hQjYAiAeBpeCZ2yS1cuZorgcohnCG9qksa1V6pmev7h",
    "initial_balance": 1000000,
    "message": "Vault initialized successfully"
  },
  "error": null,
  "timestamp": "2026-01-12T18:49:40.136695300+00:00"
}
POST /vault/deposit

Deposit collateral into vault.

Request Body:

{
  "user_pubkey": "9hQjYAiAeBpeCZ2yS1cuZorgcohnCG9qksa1V6pmev7h",
  "amount": 500000,  // in lamports
  "token_mint": null  // optional, for SPL tokens
}

Success Response (200):

{
  "success": true,
  "data": {
    "transaction_id": 42,
    "amount": 500000,
    "new_balance": {
      "total": 1500000,
      "locked": 0,
      "available": 1500000
    },
    "message": "Deposit successful"
  },
  "error": null,
  "timestamp": "2026-01-12T18:49:40.136695300+00:00"
}
POST /vault/withdraw

Withdraw collateral from vault.

Request Body:

{
  "user_pubkey": "9hQjYAiAeBpeCZ2yS1cuZorgcohnCG9qksa1V6pmev7h",
  "amount": 200000,  // in lamports
  "destination": null  // optional, specific withdrawal address
}

Success Response (200):

{
  "success": true,
  "data": {
    "transaction_id": 43,
    "amount": 200000,
    "new_balance": {
      "total": 1300000,
      "locked": 0,
      "available": 1300000
    },
    "message": "Withdrawal successful"
  },
  "error": null,
  "timestamp": "2026-01-12T18:49:40.136695300+00:00"
}

Error Response (400):

{
  "success": false,
  "data": null,
  "error": "Insufficient available balance",
  "timestamp": "2026-01-12T18:49:40.136695300+00:00"
}
GET /vault/balance/:user

Get vault balance for a specific user.

Parameters:

  • user - Solana public key (44 characters base58)

Success Response (200):

{
  "success": true,
  "data": {
    "user": "9hQjYAiAeBpeCZ2yS1cuZorgcohnCG9qksa1V6pmev7h",
    "total": 1300000,
    "locked": 300000,
    "available": 1000000,
    "last_updated": "2026-01-12T18:49:40.136695300+00:00"
  },
  "error": null,
  "timestamp": "2026-01-12T18:49:40.136695300+00:00"
}
GET /vault/transactions/:user

Get transaction history for a user.

Parameters:

  • user - Solana public key

Success Response (200):

{
  "success": true,
  "data": [
    {
      "id": 43,
      "user_pubkey": "9hQjYAiAeBpeCZ2yS1cuZorgcohnCG9qksa1V6pmev7h",
      "transaction_type": "withdraw",
      "amount": 200000,
      "signature": null,
      "status": "confirmed",
      "created_at": "2026-01-12T18:49:40.136695300+00:00"
    },
    {
      "id": 42,
      "user_pubkey": "9hQjYAiAeBpeCZ2yS1cuZorgcohnCG9qksa1V6pmev7h",
      "transaction_type": "deposit",
      "amount": 500000,
      "signature": null,
      "status": "confirmed",
      "created_at": "2026-01-12T18:48:30.136695300+00:00"
    }
  ],
  "error": null,
  "timestamp": "2026-01-12T18:49:40.136695300+00:00"
}
GET /vault/tvl

Get Total Value Locked across all vaults.

Success Response (200):

{
  "success": true,
  "data": {
    "total_value_locked": 15000000,
    "total_users": 25,
    "total_locked": 5000000,
    "total_available": 10000000,
    "timestamp": "2026-01-12T18:49:40.136695300+00:00"
  },
  "error": null,
  "timestamp": "2026-01-12T18:49:40.136695300+00:00"
}

Internal API Endpoints

These endpoints are used by other Solana programs to interact with the vault via CPI (Cross-Program Invocation).

POST /internal/lock

Lock collateral for a position.

Request Body:

{
  "caller_program": "PositionMgrProgram1234567890123456789012345",
  "user_pubkey": "9hQjYAiAeBpeCZ2yS1cuZorgcohnCG9qksa1V6pmev7h",
  "amount": 300000
}

Success Response (200):

{
  "success": true,
  "signature": "5j7s...transaction_signature",
  "locked_amount": 300000,
  "new_locked_balance": 300000
}
POST /internal/unlock

Unlock collateral from a position.

Request Body:

{
  "caller_program": "LiquidationEngine123456789012345678901234",
  "user_pubkey": "9hQjYAiAeBpeCZ2yS1cuZorgcohnCG9qksa1V6pmev7h",
  "amount": 100000
}
POST /internal/transfer

Transfer collateral between users (for settlements).

Request Body:

{
  "caller_program": "SettlementRelayer12345678901234567890123",
  "user_pubkey": "9hQjYAiAeBpeCZ2yS1cuZorgcohnCG9qksa1V6pmev7h",
  "amount": 50000
}

2. WebSocket Streams

Connect to ws://127.0.0.1:3000/ws for real-time updates.

Connection

const ws = new WebSocket('ws://127.0.0.1:3000/ws');

ws.onopen = () => {
  console.log('Connected to vault WebSocket');
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Event:', data);
};

Event Types

Connected Event

Sent immediately upon connection.

{
  "type": "Connected",
  "data": {
    "message": "Connected to Collateral Vault WebSocket",
    "timestamp": "2026-01-12T18:49:40Z"
  }
}
Balance Update Event

Real-time balance updates for a user.

{
  "type": "BalanceUpdate",
  "data": {
    "user": "9hQjYAiAeBpeCZ2yS1cuZorgcohnCG9qksa1V6pmev7h",
    "total": 1300000,
    "locked": 300000,
    "available": 1000000,
    "timestamp": "2026-01-12T18:49:40Z"
  }
}
Deposit Event

Notification when a deposit occurs.

{
  "type": "Deposit",
  "data": {
    "user": "9hQjYAiAeBpeCZ2yS1cuZorgcohnCG9qksa1V6pmev7h",
    "amount": 500000,
    "transaction_id": 42,
    "timestamp": "2026-01-12T18:49:40Z"
  }
}
Withdraw Event

Notification when a withdrawal occurs.

{
  "type": "Withdraw",
  "data": {
    "user": "9hQjYAiAeBpeCZ2yS1cuZorgcohnCG9qksa1V6pmev7h",
    "amount": 200000,
    "transaction_id": 43,
    "timestamp": "2026-01-12T18:49:40Z"
  }
}
Lock Event

Notification when collateral is locked.

{
  "type": "Lock",
  "data": {
    "user": "9hQjYAiAeBpeCZ2yS1cuZorgcohnCG9qksa1V6pmev7h",
    "amount": 300000,
    "caller_program": "PositionMgrProgram1234567890123456789012345",
    "timestamp": "2026-01-12T18:49:40Z"
  }
}
Unlock Event

Notification when collateral is unlocked.

{
  "type": "Unlock",
  "data": {
    "user": "9hQjYAiAeBpeCZ2yS1cuZorgcohnCG9qksa1V6pmev7h",
    "amount": 100000,
    "caller_program": "LiquidationEngine123456789012345678901234",
    "timestamp": "2026-01-12T18:49:40Z"
  }
}
Transfer Event

Notification when collateral is transferred.

{
  "type": "Transfer",
  "data": {
    "from": "9hQjYAiAeBpeCZ2yS1cuZorgcohnCG9qksa1V6pmev7h",
    "to": "5kFjE8QvP2sT1bNuLx9aRwZ3cYh6Ke7mP2qR4tYvWs8X",
    "amount": 50000,
    "timestamp": "2026-01-12T18:49:40Z"
  }
}
TVL Event

Total Value Locked updates (broadcast periodically).

{
  "type": "TVL",
  "data": {
    "total_value_locked": 15000000,
    "total_users": 25,
    "total_locked": 5000000,
    "total_available": 10000000,
    "timestamp": "2026-01-12T18:49:40Z"
  }
}
Ping Event

Heartbeat sent every 30 seconds.

{
  "type": "Ping",
  "data": {
    "timestamp": "2026-01-12T18:49:40Z"
  }
}

3. Internal Interfaces

Position Manager Interface

Used by position management programs to lock/unlock collateral.

Lock Collateral:

// From Position Manager program
POST /internal/lock
{
  "caller_program": "<position_manager_pubkey>",
  "user_pubkey": "<user_pubkey>",
  "amount": <lamports>
}

Unlock Collateral:

POST /internal/unlock
{
  "caller_program": "<position_manager_pubkey>",
  "user_pubkey": "<user_pubkey>",
  "amount": <lamports>
}

Liquidation Engine Interface

Used by liquidation engine to unlock and transfer collateral.

Unlock for Liquidation:

POST /internal/unlock
{
  "caller_program": "<liquidation_engine_pubkey>",
  "user_pubkey": "<liquidated_user_pubkey>",
  "amount": <lamports>
}

Settlement Relayer Interface

Used by settlement system to transfer collateral.

Transfer for Settlement:

POST /internal/transfer
{
  "caller_program": "<settlement_relayer_pubkey>",
  "user_pubkey": "<user_pubkey>",
  "amount": <lamports>
}

Error Responses

All endpoints return consistent error responses:

{
  "success": false,
  "data": null,
  "error": "Error message here",
  "timestamp": "2026-01-12T18:49:40.136695300+00:00"
}

Common HTTP Status Codes

  • 200 OK - Request successful
  • 201 Created - Resource created successfully
  • 400 Bad Request - Invalid request parameters
  • 404 Not Found - Resource not found
  • 409 Conflict - Resource already exists
  • 500 Internal Server Error - Server error
  • 503 Service Unavailable - Database or service unavailable

Example Usage

cURL Examples

# Initialize vault
curl -X POST http://127.0.0.1:3000/vault/initialize \
  -H "Content-Type: application/json" \
  -d '{"user_pubkey":"9hQjYAiAeBpeCZ2yS1cuZorgcohnCG9qksa1V6pmev7h","initial_deposit":1000000}'

# Deposit
curl -X POST http://127.0.0.1:3000/vault/deposit \
  -H "Content-Type: application/json" \
  -d '{"user_pubkey":"9hQjYAiAeBpeCZ2yS1cuZorgcohnCG9qksa1V6pmev7h","amount":500000}'

# Get balance
curl http://127.0.0.1:3000/vault/balance/9hQjYAiAeBpeCZ2yS1cuZorgcohnCG9qksa1V6pmev7h

# Get TVL
curl http://127.0.0.1:3000/vault/tvl

# Get transactions
curl http://127.0.0.1:3000/vault/transactions/9hQjYAiAeBpeCZ2yS1cuZorgcohnCG9qksa1V6pmev7h

JavaScript/TypeScript Example

// Initialize client
const BASE_URL = 'http://127.0.0.1:3000';

async function initializeVault(userPubkey: string, initialDeposit?: number) {
  const response = await fetch(`${BASE_URL}/vault/initialize`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ user_pubkey: userPubkey, initial_deposit: initialDeposit })
  });
  return await response.json();
}

async function deposit(userPubkey: string, amount: number) {
  const response = await fetch(`${BASE_URL}/vault/deposit`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ user_pubkey: userPubkey, amount })
  });
  return await response.json();
}

async function getBalance(userPubkey: string) {
  const response = await fetch(`${BASE_URL}/vault/balance/${userPubkey}`);
  return await response.json();
}

// WebSocket connection
const ws = new WebSocket('ws://127.0.0.1:3000/ws');
ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Vault Event:', data);
};

Rate Limiting & Performance

  • WebSocket: Max 10,000 queued events per connection
  • REST API: No rate limiting (add nginx/middleware as needed)
  • Database connection pool: 50 max connections, 5 min connections
  • WebSocket heartbeat: 30 second interval, 60 second timeout

Security Considerations

  1. Authentication: Add JWT or API key authentication for production
  2. CORS: Configure appropriate CORS headers
  3. Rate Limiting: Implement rate limiting for production
  4. Input Validation: All pubkeys validated (44 char base58)
  5. SQL Injection: Using parameterized queries via sqlx
  6. WebSocket Security: Consider authentication tokens for WS connections

Next Steps

  1. Add Solana RPC integration for on-chain operations
  2. Implement JWT authentication
  3. Add rate limiting middleware
  4. Deploy with HTTPS/WSS in production
  5. Add monitoring and metrics endpoints