# SpaceComputer Orbitport Documentation > This file is designed to help AI assistants understand the SpaceComputer Orbitport documentation and assist developers in building applications with cosmic randomness. ## Project Overview SpaceComputer Orbitport is a gateway to orbital services such as cTRNG (cosmic True Random Number Generator) or spaceTEE, served by multiple providers & satellites to ensure high availability and reliability. cTRNG provides true random numbers harvested from hardware on satellites (cEDGE and Crypto2 by Aptos Orbital). The satellite signs the generated data to ensure authenticity and tamper-resistance. **Website**: https://spacecomputer.io **Documentation**: https://docs.spacecomputer.io **API Base URL**: https://op.spacecomputer.io ## Core Concepts ### What is cTRNG? Cosmic True Random Number Generation (cTRNG) is an orbital service that provides true random numbers harvested from cosmic radiation detected via satellite instrumentation. Unlike pseudo-random number generators (PRNGs), cTRNG produces genuinely unpredictable, cryptographically secure random numbers. ### Randomness Sources 1. **aptosorbital**: Space-based randomness from cEDGE or Crypto2 satellites (primary source) 2. **derived**: Fallback randomness derived from a cosmic seed using BIP32 key derivation ## Access Methods There are three ways to access cTRNG values: ### 1. Orbitport REST API (Authenticated) - **Endpoint**: `GET /api/v1/services/trng` - **Authentication**: OAuth2 Bearer token via Auth0 - **Response**: 32-byte hex string with cryptographic signature ```bash # Get access token curl --request POST --url "https://auth.spacecomputer.io/oauth/token" \ --header 'content-type: application/json' \ --data '{"client_id":"YOUR_CLIENT_ID","client_secret":"YOUR_CLIENT_SECRET","audience":"https://op.spacecomputer.io/api","grant_type":"client_credentials"}' # Fetch cTRNG curl --request GET --url https://op.spacecomputer.io/api/v1/services/trng \ --header "authorization: Bearer ACCESS_TOKEN" ``` **Response Format**: ```json { "service": "trng", "src": "aptosorbital", "data": "0a4c2ea21557418bbc1d57120142ad83e8fa6e030ad35125fe225b97929d2526", "signature": { "value": "3046022100da9e9dfbe4167da1bd7b824ab46e57506cfbebc50395fdf0bb3d3407c1d92451022100e33601c04b402fc57d8ffd22d41b01ec5315d4e1a1d2be97bf71323cc5cc3838", "pk": "" } } ``` ### 2. IPFS Beacon (No Authentication Required) - **URL**: `https://ipfs.io/ipns/k2k4r8lvomw737sajfnpav0dpeernugnryng50uheyk1k39lursmn09f` - **Update Frequency**: Every 60 seconds - **Features**: Block traversal for historical data, array of 3 cTRNG values per block ```javascript const response = await fetch('https://ipfs.io/ipns/k2k4r8lvomw737sajfnpav0dpeernugnryng50uheyk1k39lursmn09f'); const data = await response.json(); console.log(data.data.ctrng[0]); // First cTRNG value ``` **Response Format**: ```json { "previous": "/ipfs/bafkreial7oeangta7hakknhzsjzja4k2sehnsykx2u7bm6wdz46ug42me4", "data": { "sequence": 87963, "timestamp": 1769179239, "ctrng": [ "88943046891c6c971f185c7cd69a350d850fca480facf549777efc4602ec94a6", "802a5afa3b09c360ec56cbe67cb615e038f307c905d199993e28ce38c21e9108", "dbbe94501ed32c55acb4ad4512da0c3871f497930c4d2d9061bbe7bd634458fc" ] } } ``` ### 3. Orbitport SDK (TypeScript) - **Package**: `@spacecomputer-io/orbitport-sdk-ts` - **Install**: `npm i @spacecomputer-io/orbitport-sdk-ts` - **Features**: Automatic source selection, fallback to IPFS, full TypeScript support, error handling ```typescript import { OrbitportSDK } from "@spacecomputer-io/orbitport-sdk-ts"; // With API credentials (tries API first, falls back to IPFS) const sdk = new OrbitportSDK({ config: { clientId: "your-client-id", clientSecret: "your-client-secret", }, }); // Without credentials (IPFS only) const sdkIpfsOnly = new OrbitportSDK({ config: {} }); // Get random value const result = await sdk.ctrng.random(); console.log(result.data.data); // The cTRNG hex value // IPFS with specific index and block const historical = await sdk.ctrng.random({ src: "ipfs", block: 10012, index: 1 }); // Force IPFS usage const ipfsResult = await sdk.ctrng.random({ src: "ipfs" }); // Custom IPFS beacon path const customResult = await sdk.ctrng.random({ src: "ipfs", beaconPath: "/ipns/your-custom-beacon-cid" }); ``` **SDK Response Structure**: ```typescript interface ServiceResult { data: CTRNGResponse; metadata: { timestamp: number; request_id?: string; }; success: boolean; } interface CTRNGResponse { service: string; // "trng", "rng", or "ipfs-beacon" src: string; // "trng", "rng", or "ipfs" data: string; // The random value as a hexadecimal string signature?: { value: string; pk: string; }; // API only timestamp?: string; provider?: string; } ``` **Authentication Helpers**: ```typescript // Check if token is valid const isValid = await sdk.auth.isTokenValid(); // Get token information const tokenInfo = await sdk.auth.getTokenInfo(); ``` ## Common Implementation Patterns ### Server-Side Proxy Pattern For production applications, implement a server-side proxy to: - Keep API credentials secure (never expose to client) - Handle token lifecycle management - Implement rate limiting and caching - Provide fallback mechanisms ```typescript // pages/api/random.ts (Next.js API Route) import { NextApiRequest, NextApiResponse } from "next"; export default async function handler(req: NextApiRequest, res: NextApiResponse) { const accessToken = await getValidToken(); // Your token management logic const response = await fetch(`${process.env.ORBITPORT_API_URL}/api/v1/services/trng`, { headers: { Authorization: `Bearer ${accessToken}` }, }); const data = await response.json(); return res.status(200).json(data); } ``` ### Client-Side React Hook ```typescript // hooks/useOrbitport.ts import { useCallback } from "react"; export function useOrbitport() { const getRandomSeed = useCallback(async () => { const response = await fetch("/api/random"); return response.json(); }, []); return { getRandomSeed }; } ``` ### Token Management with Buffer ```typescript const TOKEN_EXPIRE_BUFFER = 300; // 5 minutes before expiry async function getValidToken(): Promise { const token = getCachedToken(); if (token && token.exp > Date.now()/1000 + TOKEN_EXPIRE_BUFFER) { return token.access_token; } return generateNewAccessToken(); } ``` ## Use Cases ### 1. Gaming & Lotteries Use cTRNG for fair, unbiased random selection in games, lotteries, and prize distributions. ```typescript const seedData = await getRandomSeed(); const players = ["Alice", "Bob", "Charlie"]; const winnerIndex = parseInt(seedData.data.slice(0, 8), 16) % players.length; const winner = players[winnerIndex]; ``` ### 2. Password Generation Generate secure passwords with cosmic entropy. ```typescript function generatePassword(seed: string, length: number): string { const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*"; const seedBytes = Buffer.from(seed, "hex"); let password = ""; for (let i = 0; i < length; i++) { password += chars[seedBytes[i % seedBytes.length] % chars.length]; } return password; } ``` ### 3. SIWE (Sign In with Ethereum) Nonces Generate secure nonces for Web3 authentication to prevent replay attacks. ```typescript // Server-side nonce generation const response = await fetch(`${ORBITPORT_API_URL}/api/v1/services/trng`, { headers: { Authorization: `Bearer ${accessToken}` }, }); const data = await response.json(); const nonce = data.data; // Use as SIWE nonce ``` ### 4. Cryptographic Key Generation Generate seeds for cryptographic key derivation. ```typescript const seedData = await sdk.ctrng.random(); const cryptoSeed = Buffer.from(seedData.data.data, "hex"); // Use cryptoSeed for key derivation (BIP32, etc.) ``` ## Environment Variables ```bash ORBITPORT_CLIENT_ID=your_client_id ORBITPORT_CLIENT_SECRET=your_client_secret ORBITPORT_AUTH_URL=https://auth.spacecomputer.io ORBITPORT_API_URL=https://op.spacecomputer.io ``` ## API Reference ### GET /api/v1/services/trng **Query Parameters**: - `src` (optional): Array of sources in priority order. Default: `[aptosorbital, derived]` - `aptosorbital`: Space-based randomness from satellites - `derived`: BIP32-derived randomness from cosmic seed **Response**: | Field | Type | Description | |-------|------|-------------| | service | string | Always "trng" | | src | string | Source used ("aptosorbital" or "derived") | | data | string | 32-byte random data as hex string | | signature.value | string | Cryptographic signature | | signature.pk | string | Public key for verification | ## SDK Configuration Options ```typescript interface OrbitportConfig { clientId?: string; // API client ID clientSecret?: string; // API client secret authUrl?: string; // Auth server URL apiUrl?: string; // API server URL timeout?: number; // Request timeout (default: 30000ms) retryAttempts?: number; // Retry attempts (default: 3) retryDelay?: number; // Retry delay (default: 1000ms) ipfs?: IPFSConfig; // Custom IPFS settings } interface IPFSConfig { gateway?: string; // Default: "https://ipfs.io" apiUrl?: string; // Default: "https://ipfs.io" timeout?: number; defaultBeaconPath?: string; // Default: "/ipns/k2k4r8lvomw737sajfnpav0dpeernugnryng50uheyk1k39lursmn09f" } ``` ## Error Handling ```typescript import { OrbitportSDKError, ERROR_CODES } from "@spacecomputer-io/orbitport-sdk-ts"; try { const result = await sdk.ctrng.random(); } catch (error) { if (error instanceof OrbitportSDKError) { switch (error.code) { case ERROR_CODES.AUTH_FAILED: // Handle authentication failure break; case ERROR_CODES.NETWORK_ERROR: // Handle network issues break; } } } ``` ## Best Practices 1. **Always use server-side authentication** - Never expose API credentials to client-side code 2. **Implement fallback mechanisms** - Use Node.js crypto or IPFS as fallback when API is unavailable 3. **Cache tokens with expiry buffer** - Refresh tokens 5 minutes before expiry 4. **Use the SDK when possible** - It handles authentication, fallback, and error handling automatically 5. **Verify signatures for critical applications** - The satellite signature proves data authenticity 6. **Consider IPFS for public applications** - No authentication required, updated every 60 seconds ## Recipes Practical, step-by-step implementation guides for common Orbitport use cases. Each recipe includes complete, working code examples with error handling and best practices. ### 1. Cosmic Randomness in Web3 Applications Core patterns for implementing cosmic randomness in applications using the Server-Side Proxy Pattern. - Secure server-side authentication with Orbitport - Token management with encrypted cookie storage and 5-minute expiry buffer - API route for random seeds (`pages/api/random.ts`) - Custom React hook (`useOrbitport`) for client-side integration - Random planet selector usage example **Architecture**: Server-Side Proxy Pattern - server acts as secure proxy between clients and Orbitport, centralizing authentication and error handling. **Blog Post**: https://blog.spacecomputer.io/building-with-spacecomputer-orbitport-a-guide-to-cosmic-randomness-in-web3/ ### 2. Cosmic Cipher Password Generator Build a secure password generator using cosmic randomness with a Hybrid Randomness Pattern. - Cosmic entropy from space combined with local generation - Flexible password generation with customizable character sets (uppercase, lowercase, numbers, symbols) - Minimum character requirements with Fisher-Yates shuffle - Node.js crypto fallback for offline resilience - Verifiable randomness with seed display **Architecture**: Hybrid Randomness Pattern - server-side cosmic seed retrieval with client-side password generation for privacy. **Blog Post**: https://blog.spacecomputer.io/generating-secure-passwords-with-verifiable-randomness-from-space/ **GitHub**: https://github.com/spacecomputer-io/cosmic-cipher ### 3. Secure Nonces for Sign In with Ethereum (SIWE) Generate secure nonces for SIWE authentication using cosmic randomness to prevent replay attacks. - Cosmic nonce generation with iron-session for secure storage - HTTP-only cookies prevent client-side nonce tampering - SIWE message verification endpoint - Wagmi integration with custom `useSIWE` hook - Session destruction after verification prevents nonce reuse - Fallback to standard CSPRNG (`generateNonce()` from `siwe` package) **Architecture**: Cosmic Nonce Pattern - server-side nonce generation and storage with session-based anti-replay protection. **Prerequisites**: `siwe`, `iron-session`, `wagmi`, `viem` **Blog Post**: https://blog.spacecomputer.io/generating-secure-nonces-for-sign-in-with-ethereum-using-verifiable-cosmic-randomness-from-space/ **GitHub**: https://github.com/spacecomputer-io/cosmic-siwe ## Getting API Access 1. Fill out the early access form: https://forms.gle/PojGGfX6579SnYRx8 2. Receive your `client_id` and `client_secret` via email 3. Configure environment variables 4. Start building with cosmic randomness ## Resources - **Documentation**: https://docs.spacecomputer.io - **SDK Package**: https://www.npmjs.com/package/@spacecomputer-io/orbitport-sdk-ts - **GitHub**: https://github.com/spacecomputer-io/docs - **Blog**: https://blog.spacecomputer.io - **Telegram**: https://t.me/SpaceComputerOfficial - **Twitter/X**: https://x.com/SpaceComputerIO ## Quick Start Code ```typescript // Minimal example to get cosmic randomness import { OrbitportSDK } from "@spacecomputer-io/orbitport-sdk-ts"; const sdk = new OrbitportSDK({ config: {} }); // Uses IPFS (no auth needed) async function getCosmicRandomness() { const result = await sdk.ctrng.random(); console.log("Cosmic random value:", result.data.data); return result.data.data; } getCosmicRandomness(); ```