# 📡 API Reference

> **External integrations and protocol implementations** powering Ario's decentralized architecture with Nostr protocol, Lightning Network, and third-party service APIs.

## Table of Contents

- [[#Protocol Implementations]]
- [[#External APIs]]
- [[#Service Integrations]]
- [[#SDK References]]
- [[#Authentication & Security]]
- [[#Rate Limits & Best Practices]]

## Protocol Implementations

### **Nostr Protocol** 
**Specification:** [NIPs (Nostr Implementation Possibilities)](https://github.com/nostr-protocol/nips)  
**Client Library:** `nostr-tools` v2.x  
**Implementation:** Custom RelayHub service with connection pooling

**Supported NIPs:**
- **NIP-01** - Basic protocol flow and event structure
- **NIP-02** - Contact list and petnames
- **NIP-04** - Encrypted direct messages
- **NIP-05** - Mapping Nostr keys to DNS-based internet identifiers
- **NIP-09** - Event deletion
- **NIP-10** - Conventions for clients' use of `e` and `p` tags
- **NIP-19** - bech32-encoded entities
- **NIP-25** - Reactions

**Core Event Types:**
```typescript
interface NostrEvent {
  id: string           // Event ID (32-bytes hex)
  pubkey: string       // Author public key (32-bytes hex)  
  created_at: number   // Unix timestamp in seconds
  kind: number         // Event kind (0=metadata, 1=text, 3=contacts, etc.)
  tags: string[][]     // Tags array
  content: string      // Event content
  sig: string          // Event signature (64-bytes hex)
}

// Common event kinds
enum EventKind {
  Metadata = 0,        // User profile information
  TextNote = 1,        // Short text note
  RecommendRelay = 2,  // Recommend relay
  Contacts = 3,        // Contact list
  EncryptedDM = 4,     // Encrypted direct message
  EventDeletion = 5,   // Event deletion
  Repost = 6,          // Repost/boost
  Reaction = 7,        // Like/reaction
  BadgeAward = 8,      // Badge award
  GroupChatMessage = 9, // Group chat message
}
```

**See:** [[nostr-protocol|📖 Nostr Protocol Implementation]]

### **Lightning Network**
**Protocol:** BOLT specifications for Lightning Network  
**Browser Integration:** WebLN API for wallet communication  
**Backend Integration:** LNbits for invoice generation and payment processing

**WebLN API Integration:**
```typescript
interface WebLN {
  enable(): Promise<void>
  getInfo(): Promise<GetInfoResponse>
  sendPayment(paymentRequest: string): Promise<SendPaymentResponse>
  makeInvoice(args: RequestInvoiceArgs): Promise<RequestInvoiceResponse>
  signMessage(message: string): Promise<SignMessageResponse>
}

// Payment workflow
async function processLightningPayment(invoice: string): Promise<PaymentResult> {
  if (!window.webln) {
    throw new Error('WebLN not available')
  }
  
  await window.webln.enable()
  const result = await window.webln.sendPayment(invoice)
  
  return {
    preimage: result.preimage,
    paymentHash: result.paymentHash,
    paid: true
  }
}
```

**Invoice Generation:**
```typescript
interface LightningInvoice {
  payment_request: string    // BOLT11 invoice string
  payment_hash: string      // Payment hash (32-bytes hex)
  amount: number           // Amount in millisats
  description: string      // Invoice description
  expires_at: number       // Expiration timestamp
  created_at: number       // Creation timestamp
}
```

**See:** [[lightning-integration|📖 Lightning Network Integration]]

## External APIs

### **LNbits API**
**Purpose:** Lightning wallet backend and invoice management  
**Documentation:** [LNbits API Docs](https://legend.lnbits.com/docs)  
**Base URL:** Configurable via environment variables

**Key Endpoints:**

#### **Wallet Management**
```typescript
// Get wallet information
GET /api/v1/wallet
Authorization: X-Api-Key: {admin_key}

interface WalletInfo {
  id: string
  name: string
  balance: number  // Balance in millisats
}
```

#### **Invoice Operations**
```typescript
// Create invoice
POST /api/v1/payments
Content-Type: application/json
Authorization: X-Api-Key: {invoice_key}

interface CreateInvoiceRequest {
  out: false              // Incoming payment
  amount: number         // Amount in sats
  memo: string          // Invoice description
  expiry?: number       // Expiry in seconds
}

interface CreateInvoiceResponse {
  payment_hash: string
  payment_request: string  // BOLT11 invoice
  checking_id: string
}
```

#### **Payment Verification**
```typescript
// Check payment status
GET /api/v1/payments/{checking_id}
Authorization: X-Api-Key: {invoice_key}

interface PaymentStatus {
  paid: boolean
  checking_id: string
  amount: number
  fee: number
  memo: string
  time: number
}
```

**See:** [[lnbits-api|📖 LNbits API Integration]]

### **Nostr Relay APIs**
**Protocol:** WebSocket-based communication following Nostr specification  
**Connection Management:** Custom RelayHub with connection pooling and failover

**Relay Communication Protocol:**
```typescript
// Client to relay messages
type ClientMessage = 
  | ['EVENT', NostrEvent]           // Publish event
  | ['REQ', string, ...Filter[]]    // Request events
  | ['CLOSE', string]               // Close subscription

// Relay to client messages  
type RelayMessage =
  | ['EVENT', string, NostrEvent]   // Event received
  | ['OK', string, boolean, string] // Event acceptance
  | ['EOSE', string]                // End of stored events
  | ['NOTICE', string]              // Relay notice
```

**Event Filters:**
```typescript
interface Filter {
  ids?: string[]        // Event IDs
  authors?: string[]    // Author pubkeys
  kinds?: number[]      // Event kinds
  since?: number        // Events after timestamp
  until?: number        // Events before timestamp
  limit?: number        // Maximum number of events
  search?: string       // Text search (if supported)
  [key: string]: any    // Tag filters (#e, #p, etc.)
}
```

**Relay Information (NIP-11):**
```typescript
// GET https://relay.example.com (Accept: application/nostr+json)
interface RelayInformation {
  name: string
  description: string
  pubkey?: string
  contact?: string
  supported_nips?: number[]
  software?: string
  version?: string
  limitation?: {
    max_message_length?: number
    max_subscriptions?: number
    max_filters?: number
    max_subid_length?: number
    min_pow_difficulty?: number
    auth_required?: boolean
    payment_required?: boolean
  }
}
```

**See:** [[relay-communication|📖 Relay Communication Protocol]]

## Service Integrations

### **QR Code Generation**
**Library:** `qrcode` for QR code generation  
**Use Cases:** Lightning invoices, contact sharing, event tickets

```typescript
interface QRCodeOptions {
  width?: number
  margin?: number
  color?: {
    dark?: string
    light?: string
  }
  errorCorrectionLevel?: 'L' | 'M' | 'Q' | 'H'
}

async function generateQRCode(data: string, options?: QRCodeOptions): Promise<string> {
  return QRCode.toDataURL(data, {
    width: options?.width || 256,
    margin: options?.margin || 2,
    color: {
      dark: options?.color?.dark || '#000000',
      light: options?.color?.light || '#FFFFFF'
    },
    errorCorrectionLevel: options?.errorCorrectionLevel || 'M'
  })
}
```

### **Cryptography Services**
**Library:** `nostr-tools` cryptographic functions  
**Use Cases:** Key generation, event signing, message encryption

```typescript
// Key generation
function generateKeyPair(): { privateKey: string; publicKey: string } {
  const privateKey = generatePrivateKey()
  const publicKey = getPublicKey(privateKey)
  return { privateKey, publicKey }
}

// Event signing
function signEvent(event: UnsignedEvent, privateKey: string): NostrEvent {
  const id = getEventHash(event)
  const sig = getSignature(id, privateKey)
  return { ...event, id, sig }
}

// Message encryption (NIP-04)
async function encryptMessage(
  message: string, 
  recipientPubkey: string, 
  senderPrivkey: string
): Promise<string> {
  return encrypt(senderPrivkey, recipientPubkey, message)
}
```

### **Storage Services**
**Browser APIs:** localStorage, IndexedDB  
**Abstraction:** StorageService with user-scoped keys

```typescript
interface StorageService {
  // User-scoped operations
  setUserData<T>(key: string, data: T): void
  getUserData<T>(key: string, defaultValue?: T): T | undefined
  removeUserData(key: string): void
  clearUserData(): void
  
  // Global application data
  setAppData<T>(key: string, data: T): void
  getAppData<T>(key: string, defaultValue?: T): T | undefined
}
```

## SDK References

### **Nostr-tools Reference**
**Documentation:** [nostr-tools GitHub](https://github.com/nbd-wtf/nostr-tools)  
**Version:** 2.x

**Key Functions:**
```typescript
import {
  generatePrivateKey,
  getPublicKey,
  getEventHash,
  getSignature,
  validateEvent,
  verifySignature,
  SimplePool,
  Filter,
  Event as NostrEvent,
  nip04,
  nip19
} from 'nostr-tools'

// Pool management
const pool = new SimplePool()
const events = await pool.list(relays, [filter])
const sub = pool.sub(relays, [filter])
```

### **Vue 3 Integration**
**Framework:** Vue 3 Composition API  
**State Management:** Pinia stores  
**Reactivity:** Vue reactive primitives

```typescript
// Reactive Nostr client integration
export function useNostrClient() {
  const isConnected = ref(false)
  const connectedRelays = ref<string[]>([])
  
  const connect = async (relays: string[]) => {
    // Connection logic
    isConnected.value = true
    connectedRelays.value = relays
  }
  
  return {
    isConnected: readonly(isConnected),
    connectedRelays: readonly(connectedRelays),
    connect
  }
}
```

## Authentication & Security

### **Key Management**
**Security Model:** Client-side key generation and storage  
**Storage:** Encrypted localStorage with user passphrase  
**No Server Storage:** Private keys never leave the client

```typescript
interface AuthenticationFlow {
  // Key generation
  generateNewUser(): Promise<{ privateKey: string; publicKey: string }>
  
  // Import existing key
  importUser(privateKey: string): Promise<UserProfile>
  
  // Session management
  login(privateKey: string, remember?: boolean): Promise<void>
  logout(): Promise<void>
  
  // Key security
  encryptPrivateKey(privateKey: string, passphrase: string): string
  decryptPrivateKey(encrypted: string, passphrase: string): string
}
```

### **Event Validation**
**Signature Verification:** All received events are cryptographically verified  
**Content Filtering:** Optional content moderation and filtering  
**Spam Prevention:** Rate limiting and reputation-based filtering

```typescript
function validateNostrEvent(event: NostrEvent): ValidationResult {
  // 1. Check event structure
  if (!event.id || !event.pubkey || !event.sig) {
    return { valid: false, error: 'Missing required fields' }
  }
  
  // 2. Verify event ID
  const expectedId = getEventHash(event)
  if (event.id !== expectedId) {
    return { valid: false, error: 'Invalid event ID' }
  }
  
  // 3. Verify signature
  const signatureValid = verifySignature(event)
  if (!signatureValid) {
    return { valid: false, error: 'Invalid signature' }
  }
  
  return { valid: true }
}
```

## Rate Limits & Best Practices

### **Relay Communication**
- **Connection Limits** - Maximum 10 concurrent relay connections
- **Subscription Limits** - Maximum 20 active subscriptions per relay
- **Event Publishing** - Rate limited to prevent spam (1 event/second per kind)
- **Reconnection Strategy** - Exponential backoff with maximum 30-second intervals

### **Lightning Payments**
- **Invoice Expiry** - Default 1 hour expiry for generated invoices
- **Payment Verification** - Poll payment status every 5 seconds for 5 minutes
- **Amount Limits** - Configurable minimum/maximum payment amounts
- **Error Handling** - Graceful handling of payment failures and timeouts

### **API Usage Guidelines**

#### **LNbits Integration**
```typescript
const API_CONFIG = {
  baseUrl: process.env.VITE_LNBITS_URL,
  timeout: 30000,           // 30 second timeout
  retryAttempts: 3,         // Retry failed requests
  retryDelay: 1000,         // 1 second between retries
  
  rateLimits: {
    invoiceCreation: 10,    // Max 10 invoices per minute
    paymentCheck: 60,       // Max 60 payment checks per minute
  }
}
```

#### **Nostr Relay Usage**
```typescript
const RELAY_CONFIG = {
  maxConnections: 10,       // Maximum concurrent connections
  maxSubscriptions: 20,     // Maximum active subscriptions
  connectionTimeout: 10000, // 10 second connection timeout
  
  publishLimits: {
    textNote: 5,            // Max 5 text notes per minute
    reaction: 30,           // Max 30 reactions per minute
    directMessage: 10,      // Max 10 DMs per minute
  },
  
  reconnection: {
    attempts: 5,            // Maximum reconnection attempts
    delay: 1000,           // Initial delay (1 second)
    backoffMultiplier: 2,  // Exponential backoff
    maxDelay: 30000,       // Maximum delay (30 seconds)
  }
}
```

## See Also

### Protocol Documentation
- **[[nostr-protocol|📡 Nostr Protocol Implementation]]** - Detailed NIP implementation
- **[[lightning-integration|⚡ Lightning Network Integration]]** - WebLN and payment processing
- **[[lnbits-api|🔗 LNbits API Reference]]** - Lightning backend integration
- **[[events-api|📅 Events System API]]** - Event ticketing API reference

### Implementation Guides
- **[[../03-core-services/index|⚙️ Core Services]]** - Service implementations using these APIs
- **[[../02-modules/index|📦 Module System]]** - How modules integrate with external APIs
- **[[../04-development/index|💻 Development Guide]]** - Testing and debugging API integrations

---

**Tags:** #api #integration #nostr #lightning #protocols  
**Last Updated:** 2025-09-06  
**Author:** Development Team