### Complete E-commerce Setup and Checkout Source: https://docs.ondb.ai/llms-full.txt A comprehensive example showing index configuration for both standard queries and PriceIndex payments, followed by a checkout function implementation. ```typescript import { createClient } from '@ondb/sdk'; const client = createClient({ endpoint: 'https://api.ondb.io', appId: 'my-store', appKey: process.env.ONDB_APP_KEY }); async function setupStore() { const db = client.database('my-store'); await db.createIndex({ name: 'idx_products_category', collection: 'products', field_name: 'category', index_type: 'hash' }); await db.createIndex({ name: 'idx_products_price', collection: 'products', field_name: 'price', index_type: 'btree' }); await db.createIndex({ name: 'idx_orders_totalPrice', collection: 'orders', field_name: 'totalPrice', index_type: 'Price' }); } async function checkout(cart, userWallet, paymentTxHash) { const orderTotal = cart.items.reduce((sum, item) => sum + (item.price * item.quantity), 0); return await client.store({ collection: 'orders', data: [{ customerId: userWallet, items: cart.items, totalPrice: orderTotal, status: 'confirmed', createdAt: new Date().toISOString() }] }, async (quote) => ({ txHash: paymentTxHash, network: quote.network, sender: userWallet, chainType: quote.chainType, paymentMethod: 'native' }), true); } ``` -------------------------------- ### OnDB SDK Quick Start Source: https://docs.ondb.ai/llms-full.txt Provides a quick example of how to initialize the OnDB client and perform basic CRUD operations like creating, reading, updating, and soft-deleting documents. ```APIDOC ## Quick Example This example demonstrates initializing the OnDB client and performing common CRUD operations. ### Initialization ```typescript import { createClient } from '@ondb/sdk'; const client = createClient({ endpoint: 'https://api.ondb.io', appId: 'my-app', appKey: 'your-app-key' }); ``` ### Create Document ```typescript const createResult = await client.store( { collection: 'users', data: [{ email: 'alice@example.com', name: 'Alice', active: true }] }, async (quote) => { const txHash = await processPayment(quote); return { txHash, network: quote.network, sender: walletAddress, chainType: quote.chainType, paymentMethod: 'native' }; }, true // waitForConfirmation ); ``` ### Read Single Document ```typescript const found = await client.queryBuilder() .collection('users') .whereField('email').equals('alice@example.com') .executeUnique(); console.log('Found:', found?.name); ``` ### Read Multiple Documents ```typescript const activeUsers = await client.queryBuilder() .collection('users') .whereField('active').isTrue() .orderBy('createdAt', 'DESC') .limit(10) .execute(); ``` ### Update Document (Append New Version) ```typescript if (found) { await client.store( { collection: 'users', data: [{ ...found, name: 'Alice Smith' }] }, paymentCallback, true ); } ``` ### Soft Delete Document ```typescript if (found) { await client.store( { collection: 'users', data: [{ ...found, deleted: true, deletedAt: new Date().toISOString() }] }, paymentCallback, true ); } ``` ### Payment Callback Structure All write operations require a payment callback: ```typescript await client.store( { collection: 'users', data: [...] }, async (quote) => { // quote contains: totalCost, brokerAddress, tokenSymbol, network, chainType const txHash = await processPayment(quote); return { txHash, network: quote.network, sender: walletAddress, chainType: quote.chainType, paymentMethod: 'native' }; }, true // waitForConfirmation ); ``` ``` -------------------------------- ### List All Collections (Example) Source: https://docs.ondb.ai/llms-full.txt Shows how to list all collections associated with a specific application using a GET request to the /api/apps/:app_id/collections endpoint. ```http GET /api/apps/:app_id/collections ``` -------------------------------- ### Create Collection (Example) Source: https://docs.ondb.ai/llms-full.txt Example of a POST request to create a new collection within an application. The endpoint is /api/apps/:app_id/collections. ```http POST /api/apps/:app_id/collections ``` -------------------------------- ### Install OnDB SDK Source: https://docs.ondb.ai/llms-full.txt Instructions for installing the OnDB SDK using common package managers. This is the first step to integrating OnDB into a TypeScript project. ```npm npm install @ondb/sdk ``` ```yarn yarn add @ondb/sdk ``` -------------------------------- ### Install OnDB SDK using npm or yarn Source: https://docs.ondb.ai/llms-full.txt Installs the necessary OnDB SDK package for your project. This is the first step to integrating OnDB into your application. ```bash npm install @ondb/sdk # or yarn add @ondb/sdk ``` -------------------------------- ### List Records with QueryExecutor (Example) Source: https://docs.ondb.ai/llms-full.txt An example of a POST request to the /list endpoint, which is used for listing records with the QueryExecutor. This endpoint facilitates retrieving multiple records based on specified criteria. ```http POST /list ``` -------------------------------- ### OnDB Query Builder Usage Examples (TypeScript) Source: https://docs.ondb.ai/llms-full.txt Demonstrates practical usage of the OnDB Query Builder for common scenarios. Examples include case-insensitive searches, range queries, and boolean checks, showcasing the flexibility of the API for specific data filtering needs. ```typescript const products = await client.queryBuilder() .collection('products') .whereField('productDisplayName') .includesCaseInsensitive('shirt') .limit(20) .execute(); const affordableProducts = await client.queryBuilder() .collection('products') .whereField('price') .between(10, 100) .execute(); const activeUsers = await client.queryBuilder() .collection('users') .whereField('active') .isTrue() .execute(); ``` -------------------------------- ### Create a Named Query with Advanced Options Source: https://docs.ondb.ai/llms-full.txt Demonstrates creating a named query with additional metadata for documentation and versioning. This includes specifying a version, example request, and example response, which aids in understanding and testing the query. The `parameters` array defines input fields for the query. ```typescript await client.createQuery({ name: 'top_products', source_collection: 'products', base_query: { find: { in_stock: { is: true } }, sort: ['-rating'], select: { name: true, rating: true, price: true } }, parameters: [ { name: 'category', field_path: 'category', required: false, default: 'all' } ], description: 'Top rated products by category', version: 1, example_request: { category: 'electronics' }, example_response: [{ name: 'Widget', rating: 4.9, price: 29.99 }] }); ``` -------------------------------- ### Store Data (Example) Source: https://docs.ondb.ai/llms-full.txt An example of a POST request to the /store endpoint for storing data. This endpoint is designed for 'app::collection' based data storage. ```http POST /store ``` -------------------------------- ### Get Specific Collection (Example) Source: https://docs.ondb.ai/llms-full.txt An example of a GET request to retrieve details of a specific collection identified by its ID. The endpoint is /api/apps/:app_id/collections/:collection_id. ```http GET /api/apps/:app_id/collections/:collection_id ``` -------------------------------- ### Setup Ondb Collections with Indexes Source: https://docs.ondb.ai/payments/price-index This asynchronous JavaScript function, `setupStore`, shows how to set up collections within the Ondb database. It assumes a `client` object is already initialized and ready for use. ```javascript // Setup: Create collections with indexes async function setupStore() { const db = client.db // Further collection setup logic would go here } ``` -------------------------------- ### Complete Example: Creating Collections and Indexes Source: https://docs.ondb.ai/llms-full.txt Demonstrates the complete process of initializing the OnDB client, creating collections with primary and sort columns, and adding various types of indexes (hash, btree, Price) to these collections. ```typescript import { createClient } from '@ondb/sdk'; const client = createClient({ endpoint: 'https://api.ondb.io', appId: 'my-ecommerce-app', appKey: 'your-app-key' }); const db = client.database('my-ecommerce-app'); // Create users collection with indexes await db.createCollection('users', { namespace: 'users', primary_column: 'id', sort_column: 'createdAt' }); await db.createIndex({ name: 'idx_users_email', collection: 'users', field_name: 'email', index_type: 'hash', options: { unique: true } }); await db.createIndex({ name: 'idx_users_createdAt', collection: 'users', field_name: 'createdAt', index_type: 'btree' }); // Create orders collection with indexes await db.createCollection('orders', { namespace: 'orders', primary_column: 'id', sort_column: 'createdAt' }); await db.createIndex({ name: 'idx_orders_userId', collection: 'orders', field_name: 'userId', index_type: 'hash' }); await db.createIndex({ name: 'idx_orders_status', collection: 'orders', field_name: 'status', index_type: 'hash' }); // PriceIndex for payment-based pricing await db.createIndex({ name: 'idx_orders_totalPrice', collection: 'orders', field_name: 'totalPrice', index_type: 'Price' }); ``` -------------------------------- ### Retrieve Blob Data (Example) Source: https://docs.ondb.ai/llms-full.txt An example of a GET request to retrieve binary data (blobs) from a specific collection and blob ID within an application. The endpoint is /api/apps/:app_id/blobs/:collection/:blob_id. ```http GET /api/apps/:app_id/blobs/:collection/:blob_id ``` -------------------------------- ### Query Collection Data (Example) Source: https://docs.ondb.ai/llms-full.txt An example of a GET request to query data from a specific collection within an application. This endpoint accepts query parameters that match indexed fields for filtering results. No authentication is required. ```http GET /api/apps/:app_id/collections/:collection/data?email=test@example.com&status=active ``` -------------------------------- ### Initialize OnDB Client and Configure Indexes Source: https://docs.ondb.ai/payments/price-index Demonstrates how to initialize the OnDB client and create various index types, including BTree for product ranges and PriceIndex for order totals. This setup is essential for enabling efficient querying and payment-based indexing. ```javascript import { createClient } from '@ondb/sdk'; const client = createClient({ endpoint: 'https://api.ondb.io', appId: 'my-store', appKey: process.env.ONDB_APP_KEY }); async function setupStore() { const db = client.database('my-store'); await db.createIndex({ name: 'idx_products_category', collection: 'products', field_name: 'category', index_type: 'hash' }); await db.createIndex({ name: 'idx_products_price', collection: 'products', field_name: 'price', index_type: 'btree' }); await db.createIndex({ name: 'idx_orders_totalPrice', collection: 'orders', field_name: 'totalPrice', index_type: 'Price' }); } ``` -------------------------------- ### Sharding Setup with syncCollection Source: https://docs.ondb.ai/llms-full.txt Demonstrates how to set up sharding for a collection using the `syncCollection` method, including defining fields, sharding keys, and shard size limits. ```APIDOC ## Setting Up Sharding with syncCollection ### Description Configures sharding for a collection using the `syncCollection` method. This is the recommended approach for new collections, allowing definition of fields, indexing, and sharding strategy. ### Method `syncCollection(schema: SimpleCollectionSchemaWithSharding): Promise` ### Endpoint N/A (This is a client-side SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **schema** (SimpleCollectionSchemaWithSharding) - The schema definition for the collection, including sharding configuration. - **name** (string) - The name of the collection. - **fields** (object) - Defines the fields and their types, including indexing. - **market** (object) - Field definition for 'market'. - **type** (string) - 'string'. - **index** (boolean) - `true` to index this field. - **timestamp** (object) - Field definition for 'timestamp'. - **type** (string) - 'number'. - **index** (boolean) - `true` to index this field. - **mid_price** (object) - Field definition for 'mid_price'. - **type** (string) - 'number'. - **spread** (object) - Field definition for 'spread'. - **type** (string) - 'number'. - **sharding** (object) - Sharding configuration. - **keys** (array) - An array of sharding key definitions. - **field** (string) - The field to shard on (e.g., 'market', 'timestamp'). - **type** (string) - The sharding strategy ('discrete', 'time_range', 'hash_distributed'). - **granularity** (string, optional) - Required for 'time_range' type (e.g., 'minute', 'hour', 'day'). - **enforce_in_queries** (boolean) - If true, queries must include shard key fields. - **max_shard_size** (number) - The maximum size of a shard in bytes. ### Request Example ```typescript import { createClient } from '@ondb/sdk'; const client = createClient({ endpoint: 'https://api.ondb.io', appId: 'my-app', appKey: 'your-app-key', }); await client.syncCollection({ name: 'orderbook_snapshots', fields: { market: { type: 'string', index: true }, timestamp: { type: 'number', index: true }, mid_price: { type: 'number' }, spread: { type: 'number' }, }, sharding: { keys: [ { field: 'market', type: 'discrete' }, { field: 'timestamp', type: 'time_range', granularity: 'hour' }, ], enforce_in_queries: true, max_shard_size: 50_000_000, // 50MB per shard }, }); ``` ### Response #### Success Response (200) - **sharding_configured** (boolean) - Indicates whether sharding was successfully applied to the collection. #### Response Example ```json { "sharding_configured": true } ``` ``` -------------------------------- ### API Request Example with Headers (ShellScript) Source: https://docs.ondb.ai/concepts/security Demonstrates how to make an API request using curl, including the necessary 'X-App-Key' and 'X-User-Key' headers. This is crucial for authenticating and authorizing requests to the OnDB API. ```shellscript curl -X POST https://api.ondb.io/v1/store \\ -H "X-App-Key: your_app_key_here" \\ -H "X-User-Key: optional ``` -------------------------------- ### Get Distinct Field Values with QueryBuilder Source: https://docs.ondb.ai/llms-full.txt This example demonstrates how to extract all unique values from a specified field within a collection. The `distinctBy(field)` method is used, returning an array of strings, where each string is a unique value. ```typescript const categories = await client.queryBuilder() .collection('products') .distinctBy('category'); // Returns: string[] ``` -------------------------------- ### GET /api/apps/:app_id/indexes/encrypted-quote Source: https://docs.ondb.ai/llms-full.txt Gets a quote for creating an encrypted index, part of the x402 payment flow. ```APIDOC ## GET /api/apps/:app_id/indexes/encrypted-quote ### Description Retrieves a quote for the cost associated with creating an encrypted index. This is part of the x402 payment flow. ### Method GET ### Endpoint /api/apps/:app_id/indexes/encrypted-quote ### Parameters #### Path Parameters - **app_id** (string) - Required - The ID of the application. ### Response #### Success Response (200) - **cost** (number) - The estimated cost for creating the encrypted index. - **currency** (string) - The currency of the cost. - **payment_requirements** (object) - Details about payment requirements if applicable. #### Response Example ```json { "cost": 5.00, "currency": "USD", "payment_requirements": { "payment_needed": true, "payment_method": "X-PAYMENT header" } } ``` ``` -------------------------------- ### Execute SQL Query (Example) Source: https://docs.ondb.ai/llms-full.txt Demonstrates how to execute SQL queries against collections using the /query/sql endpoint. The SQL query must reference tables using the 'app::collection' format. The request body contains the SQL query string. ```http POST /query/sql Body: { "sql": "SELECT ... FROM app::collection WHERE ..." } ``` -------------------------------- ### Get Application Details Source: https://docs.ondb.ai/payments/price-index Retrieves detailed information for a specific application identified by its 'app_id'. Supports GET requests. ```yaml openapi.yaml get /api/apps/{app_id} ``` -------------------------------- ### Initialize Query Builder Source: https://docs.ondb.ai/llms-full.txt Demonstrates how to instantiate the fluent query builder using the ONDB client. ```TypeScript const builder = client.queryBuilder(); ``` -------------------------------- ### Get App Wallet Information (GET) Source: https://docs.ondb.ai/llms-full.txt Retrieves the wallet information for a specific application. Requires the application ID. ```OpenAPI get /api/apps/{app_id}/wallet ``` -------------------------------- ### Insert Data using SQL (Example) Source: https://docs.ondb.ai/llms-full.txt Shows how to perform SQL INSERT statements via the /insert/sql endpoint. This handler translates SQL INSERT statements into JSON data and utilizes the store_data handler. Requires the X-App-Key header for write authorization. ```http POST /insert/sql Body: { "sql": "INSERT INTO app::collection (col1, col2) VALUES (val1, val2)" } Headers: X-App-Key (required for write authorization) ``` -------------------------------- ### Patch Collection (Example) Source: https://docs.ondb.ai/llms-full.txt Example of a PATCH request to modify collection properties. The endpoint is /api/apps/:app_id/collections/:collection_id. ```http PATCH /api/apps/:app_id/collections/{collection_id} ``` -------------------------------- ### Setup Database and Create Product Category Index (JavaScript) Source: https://docs.ondb.ai/payments/price-index This JavaScript code snippet initializes a database connection named 'db' to a store called 'my-store'. It then proceeds to create an index named 'idx_products_category' on the 'category' field within the 'products' collection. This index is optimized for range queries on product categories. ```javascript async function setupStore() { const db = client.database('my-store'); // Products - use btree for price range queries await db.createIndex({ name: 'idx_products_category', collection: 'products', field_name: 'category', }) ``` -------------------------------- ### Build E-commerce App with OnDB SDK Source: https://docs.ondb.ai/llms-full.txt Demonstrates initializing the OnDB client, creating indexes for products and orders, and performing store operations with integrated payment callbacks. ```typescript import { createClient } from '@ondb/sdk'; const client = createClient({ endpoint: 'https://api.ondb.io', appId: 'my-store', appKey: process.env.ONDB_APP_KEY }); const db = client.database('my-store'); await db.createIndex({ name: 'idx_products_category', collection: 'products', field_name: 'category', index_type: 'hash' }); await db.createIndex({ name: 'idx_orders_total', collection: 'orders', field_name: 'totalPrice', index_type: 'Price' }); await client.store( { collection: 'products', data: [{ name: 'Widget', price: 1000000, category: 'electronics' }] }, paymentCallback, true ); await client.store( { collection: 'orders', data: [{ customerId: userAddress, items: cartItems, totalPrice: orderTotal }] }, paymentCallback, true ); ``` -------------------------------- ### GET /api/tasks/:ticket_id - Get task status by ticket ID Source: https://docs.ondb.ai/payments/price-index Retrieves the status of a task using its unique ticket ID. ```APIDOC ## GET /api/tasks/:ticket_id ### Description Retrieves the status of a task using its unique ticket ID. ### Method GET ### Endpoint /api/tasks/:ticket_id ### Parameters #### Path Parameters - **ticket_id** (string) - Required - The unique identifier for the task ticket. ### Response #### Success Response (200) - **status** (string) - The current status of the task (e.g., 'pending', 'completed', 'failed'). #### Response Example ```json { "status": "completed" } ``` ``` -------------------------------- ### Get App Wallet Transactions (GET) Source: https://docs.ondb.ai/llms-full.txt Retrieves a list of transactions associated with an application's wallet. Requires the application ID. ```OpenAPI get /api/apps/{app_id}/wallet/transactions ``` -------------------------------- ### Initialize OnDB Client Source: https://docs.ondb.ai/llms-full.txt Demonstrates how to initialize the OnDB client using environment variables for secure server-side configuration. ```typescript // Server-side (Node.js) const client = createClient({ endpoint: process.env.ONDB_ENDPOINT, appId: process.env.ONDB_APP_ID, appKey: process.env.ONDB_APP_KEY }); ``` -------------------------------- ### Get a Specific Collection Source: https://docs.ondb.ai/payments/price-index Retrieves details for a specific collection identified by its 'collection_id' within an application identified by 'app_id'. Supports GET requests. ```yaml openapi.yaml get /api/apps/{app_id}/collections/{collection_id} ``` -------------------------------- ### SQL syntax examples Source: https://docs.ondb.ai/llms-full.txt Common SQL patterns for querying and inserting data into OnDB collections using the app_id::collection format. ```sql -- Select with filtering and sorting SELECT * FROM my_app::products WHERE price > 10 ORDER BY price ASC LIMIT 20 -- Select specific fields SELECT name, email, created_at FROM my_app::users WHERE active = true -- Pagination SELECT * FROM my_app::logs ORDER BY timestamp DESC LIMIT 50 OFFSET 100 -- Insert a record INSERT INTO my_app::users (email, name, active) VALUES ("bob@example.com", "Bob", true) ``` -------------------------------- ### setupSharding API Source: https://docs.ondb.ai/llms-full.txt Adds sharding to an existing collection that already contains data. It allows specifying shard keys and enforcing query constraints. ```APIDOC ## POST /collections/{collectionName}/sharding ### Description Adds sharding to an existing collection with data. This method allows you to define how data should be partitioned across shards for better performance and manageability. ### Method POST ### Endpoint `/collections/{collectionName}/sharding` ### Parameters #### Path Parameters - **collectionName** (string) - Required - The name of the collection to add sharding to. #### Request Body - **keys** (array[ShardKey]) - Required - An ordered list of shard keys, defining the sharding hierarchy. - **enforce_in_queries** (boolean) - Required - If true, all queries must include all shard key fields. - **max_shard_size** (number) - Optional - The maximum size in bytes per shard. ### Request Example ```json { "keys": [ { "field": "market", "type": "discrete" }, { "field": "timestamp", "type": "time_range", "granularity": "hour" } ], "enforce_in_queries": true } ``` ### Response #### Success Response (200) - **message** (string) - Indicates the sharding setup was successful. #### Response Example ```json { "message": "Sharding setup completed successfully." } ``` ### ShardKey Configuration #### ShardKey Object - **field** (string) - Required - The name of the field to shard by. Must be an indexed field. - **type** (string) - Required - The sharding type. Can be 'discrete', 'time_range', or 'hash_distributed'. - **granularity** (string) - Optional - Required for 'time_range' type. Specifies the time granularity ('minute', 'hour', 'day', 'week', 'month'). - **num_buckets** (number) - Optional - Required for 'hash_distributed' type. Specifies the number of hash buckets. ``` -------------------------------- ### Ondb SDK Client Initialization Source: https://docs.ondb.ai/llms-full.txt Demonstrates how to initialize the Ondb SDK client with various configuration options. ```APIDOC ## Client Initialization ### Description Initializes the Ondb SDK client with connection details and optional authentication keys. ### Method `createClient(config)` ### Parameters #### `config` (object) - **endpoint** (string) - Required - The API endpoint URL. - **appId** (string) - Required - Your application's unique identifier. - **appKey** (string) - Optional - Key for write operations (sent via X-App-Key header). - **userKey** (string) - Optional - Key for Auto-Pay operations (sent via X-User-Key header). - **agentKey** (string) - Optional - Key for agent payments (sent via X-Agent-Key header). - **timeout** (number) - Optional - Request timeout in milliseconds. Defaults to 30000. - **retryCount** (number) - Optional - Number of retry attempts. Defaults to 3. - **retryDelay** (number) - Optional - Delay between retries in milliseconds. Defaults to 1000. ### Request Example ```typescript import { createClient } from '@ondb/sdk'; const client = createClient({ endpoint: 'https://api.ondb.io', appId: 'your-app-id', appKey: 'your-app-key', // For writes (X-App-Key header) userKey: 'your-user-key', // Optional: For Auto-Pay (X-User-Key header) agentKey: 'your-agent-key', // Optional: For agent payments (X-Agent-Key header) timeout: 30000, // Request timeout (ms) retryCount: 3, // Retry attempts retryDelay: 1000, // Retry delay (ms) }); ``` ``` -------------------------------- ### Wallet API Endpoints Source: https://docs.ondb.ai/concepts/security Endpoints related to wallet functionalities. ```APIDOC ## Wallet API Endpoints ### Description API endpoints for wallet-related functionalities. ### Endpoints - (Specific endpoints for wallet are not detailed in the provided text, but the group is present.) ``` -------------------------------- ### MDX Component Rendering for Security Documentation Source: https://docs.ondb.ai/concepts/security This JavaScript snippet utilizes React and MDX to render security documentation. It dynamically imports UI components like Card, Table, and Heading to display wallet authentication workflows and session management policies. ```javascript function _createMdxContent(props) { const _components = { a: "a", code: "code", li: "li", ol: "ol", p: "p", pre: "pre", span: "span", strong: "strong", tbody: "tbody", td: "td", th: "th", thead: "thead", tr: "tr", ul: "ul", ..._provideComponents(), ...props.components }, {Card, CardGroup, CodeBlock, Heading, Mermaid, Note, Step, Steps, Table, Tip, Warning} = _components; return _jsxs(_Fragment, { children: [_jsx(_components.p, { children: "OnDB provides multiple layers of security including wallet-based authentication, spend authorization (authz), and encryption settings for your applications." }), _jsx(Heading, { level: "2", id: "wallet-authentication", children: "Wallet Authentication" })] }); } ``` -------------------------------- ### SDK Reference API Endpoints Source: https://docs.ondb.ai/concepts/security This section provides API endpoints for the SDK reference, including introduction, client, query builder, database manager, and types. ```APIDOC ## SDK Reference API Endpoints ### Description API endpoints for SDK reference documentation. ### Endpoints - `GET /api-reference/introduction` - `GET /api-reference/client` - `GET /api-reference/query-builder` - `GET /api-reference/database-manager` - `GET /api-reference/types` ``` -------------------------------- ### Configure Collection Sharding with setupSharding Source: https://docs.ondb.ai/llms-full.txt Applies sharding to an existing collection using a defined ShardingStrategy. This method requires the collection name and a strategy object containing shard keys and query enforcement rules. ```typescript await client.setupSharding('orderbook_snapshots', { keys: [ { field: 'market', type: 'discrete' }, { field: 'timestamp', type: 'time_range', granularity: 'hour' }, ], enforce_in_queries: true, }); ``` -------------------------------- ### GET /api/apps Source: https://docs.ondb.ai/llms-full.txt Lists all applications registered in OnDB storage. ```APIDOC ## GET /api/apps ### Description Returns a list of all applications registered within the OnDB storage environment. ### Method GET ### Endpoint /api/apps ### Response #### Success Response (200) - **applications** (array) - List of application objects #### Response Example { "applications": [{"id": "app_123", "name": "My App"}] } ``` -------------------------------- ### GET /x402/supported Source: https://docs.ondb.ai/llms-full.txt Lists all blockchain networks that OnDB can verify payments for. ```APIDOC ## GET /x402/supported ### Description Lists all blockchain networks that OnDB can verify payments for. ### Method GET ### Endpoint `/x402/supported` ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example ```json { "example": "No request body for GET requests" } ``` ### Response #### Success Response (200) - **supported_networks** (array) - A list of supported blockchain network identifiers. #### Response Example ```json { "supported_networks": [ "ethereum", "celestia", "polygon" ] } ``` ``` -------------------------------- ### GET /api/apps/:app_id/wallet Source: https://docs.ondb.ai/llms-full.txt Retrieves the wallet information for a specific application. ```APIDOC ## GET /api/apps/:app_id/wallet ### Description Retrieves the wallet information for a specific application. ### Method GET ### Endpoint `/api/apps/:app_id/wallet` ### Parameters #### Path Parameters - **app_id** (string) - Required - The unique identifier for the application. ### Request Example ```json { "example": "No request body for GET requests" } ``` ### Response #### Success Response (200) - **wallet_address** (string) - The wallet address of the application. - **balance** (object) - The balance of the wallet. #### Response Example ```json { "wallet_address": "0x123...", "balance": { "USDC": "1000.00" } } ``` ``` -------------------------------- ### Encryption API Source: https://docs.ondb.ai/concepts/security Endpoints for managing encryption settings for applications. ```APIDOC ## GET /api/apps/{app_id}/encryption ### Description Retrieves the encryption settings for a specific application. ### Method GET ### Endpoint /api/apps/{app_id}/encryption ### Parameters #### Path Parameters - **app_id** (string) - Required - The ID of the application. ### Response #### Success Response (200) (Schema not provided in the input) ## POST /api/apps/{app_id}/encryption ### Description Updates encryption settings for an application. This endpoint may trigger a payment flow (402 Payment Required) if costs are involved and payment proof is not provided. ### Method POST ### Endpoint /api/apps/{app_id}/encryption ### Parameters #### Path Parameters - **app_id** (string) - Required - The ID of the application. #### Headers - **X-PAYMENT** (string) - Required if cost > 0 - Base64-encoded payment proof. ### Request Body - **private_app** (boolean) - Optional - Enable/disable app-level encryption. - **action** (string) - Optional - Action for collection-level encryption ('add' or 'remove'). - **collections** (array of strings) - Optional - List of collections to add or remove encryption for. ### Response #### Success Response (200) (Schema not provided in the input) #### Error Response (402 Payment Required) (Details on payment requirements not provided in the input) ``` -------------------------------- ### GET /api/apps/:app_id/indexes Source: https://docs.ondb.ai/llms-full.txt Retrieves all indexes associated with a specific application. ```APIDOC ## GET /api/apps/:app_id/indexes ### Description Retrieves a list of all indexes associated with a given application. ### Method GET ### Endpoint /api/apps/:app_id/indexes ### Parameters #### Path Parameters - **app_id** (string) - Required - The ID of the application. ### Response #### Success Response (200) - **indexes** (array[object]) - A list of index objects. - **index_id** (string) - The ID of the index. - **collection** (string) - The collection the index belongs to. - **fields** (array[string]) - The fields included in the index. #### Response Example ```json { "indexes": [ { "index_id": "idx_abc123", "collection": "users", "fields": ["email"] }, { "index_id": "idx_def456", "collection": "products", "fields": ["sku"] } ] } ``` ``` -------------------------------- ### POST /api/pricing/quote Source: https://docs.ondb.ai/concepts/security Requests a pricing quote for services. ```APIDOC ## POST /api/pricing/quote ### Description Generates a pricing quote based on provided service parameters. ### Method POST ### Endpoint /api/pricing/quote ### Response #### Success Response (200) - **quote_id** (string) - Unique identifier for the generated quote. - **price** (number) - The quoted price. ``` -------------------------------- ### GET /health Source: https://docs.ondb.ai/llms-full.txt Performs a health check on the system with comprehensive verification. ```APIDOC ## GET /health ### Description This endpoint performs a health check on the system, verifying the status of various components and services. ### Method GET ### Endpoint /health ### Response #### Success Response (200) - **status** (string) - The overall health status of the system (e.g., "ok", "degraded"). - **details** (object) - Detailed status of individual components. #### Response Example ```json { "status": "ok", "details": { "database": "connected", "cache": "active" } } ``` ``` -------------------------------- ### GET /api/apps/:app_id/encryption Source: https://docs.ondb.ai/llms-full.txt Retrieves the encryption settings for a specific application. ```APIDOC ## GET /api/apps/:app_id/encryption ### Description Retrieves the encryption settings for a specific application. ### Method GET ### Endpoint /api/apps/:app_id/encryption ### Parameters #### Path Parameters - **app_id** (string) - Required - The ID of the application. ### Response #### Success Response (200) - **encryption_enabled** (boolean) - Indicates if encryption is enabled for the app. - **collections** (array[string]) - List of collections with encryption enabled. #### Response Example ```json { "encryption_enabled": true, "collections": ["users", "products"] } ``` ``` -------------------------------- ### POST /api/apps/:app_id/payout/info Source: https://docs.ondb.ai/concepts/security Retrieves payout settings and the current available balance for an application. ```APIDOC ## POST /api/apps/:app_id/payout/info ### Description Fetches the current payout configuration and available balance for the specified app. ### Method POST ### Endpoint /api/apps/:app_id/payout/info ### Parameters #### Path Parameters - **app_id** (string) - Required - The unique identifier of the application. ### Response #### Success Response (200) - **balance** (number) - The current available balance. - **settings** (object) - Current payout configuration details. ``` -------------------------------- ### GET /apps/:app_id/api_collections Source: https://docs.ondb.ai/llms-full.txt Lists all collections associated with a specific application. ```APIDOC ## GET /apps/:app_id/api_collections ### Description Retrieves a list of all collections for a given application. ### Method GET ### Endpoint /apps/:app_id/api_collections ### Parameters #### Path Parameters - **app_id** (string) - Required - The unique identifier of the application. ### Response #### Success Response (200) - **collections** (array) - List of collection objects #### Response Example { "collections": [{"name": "users"}, {"name": "orders"}] } ``` -------------------------------- ### GET /api/apps/:app_id/wallet Source: https://docs.ondb.ai/payments/price-index Retrieves the wallet information associated with a specific application. ```APIDOC ## GET /api/apps/:app_id/wallet ### Description Fetches the current balance and wallet details for the given application. ### Method GET ### Endpoint /api/apps/:app_id/wallet ### Parameters #### Path Parameters - **app_id** (string) - Required - The unique identifier of the application. ### Response #### Success Response (200) - **balance** (number) - Current wallet balance. - **currency** (string) - The currency code of the wallet. #### Response Example { "balance": 150.50, "currency": "USD" } ``` -------------------------------- ### POST /v1/store Source: https://docs.ondb.ai/concepts/security Stores data into a specified collection using an authenticated App Key. ```APIDOC ## POST /v1/store ### Description Stores a list of data objects into a specified collection. Requires a valid App Key in the header. ### Method POST ### Endpoint https://api.ondb.io/v1/store ### Parameters #### Request Headers - **X-App-Key** (string) - Required - 64-character alphanumeric token. - **X-User-Key** (string) - Optional - User key for auto-pay functionality. - **Content-Type** (string) - Required - Must be application/json. #### Request Body - **collection** (string) - Required - The target collection name. - **data** (array) - Required - An array of objects to store. ### Request Example { "collection": "posts", "data": [{"title": "Hello"}] } ### Response #### Success Response (200) - **status** (string) - Confirmation of storage success. #### Response Example { "status": "success" } ``` -------------------------------- ### POST /x402/settle Source: https://docs.ondb.ai/concepts/security Executes and confirms a payment using the X402 protocol. ```APIDOC ## POST /x402/settle ### Description Finalizes a payment transaction within the X402 payment protocol framework. ### Method POST ### Endpoint /x402/settle ### Request Body - **payment_id** (string) - Required - The ID of the payment to settle. ### Response #### Success Response (200) - **transaction_hash** (string) - The blockchain transaction hash of the settlement. ``` -------------------------------- ### Get all Indexes for an App Source: https://docs.ondb.ai/payments/price-index Retrieves a list of all indexes associated with a specified application. ```APIDOC ## GET /api/apps/{app_id}/indexes ### Description Retrieves a list of all indexes associated with a specified application. ### Method GET ### Endpoint /api/apps/{app_id}/indexes ### Parameters #### Path Parameters - **app_id** (string) - Required - The ID of the application. ### Request Body (Not applicable for GET request) ### Response #### Success Response (200) (Schema not provided in the source text) #### Response Example (Not provided in the source text) ``` -------------------------------- ### Initialize Ondb Client with Configuration Source: https://docs.ondb.ai/payments/price-index This JavaScript snippet demonstrates how to initialize the Ondb client using provided configuration details such as endpoint, appId, and appKey. It utilizes environment variables for sensitive information like the appKey. ```javascript const client = createClient({ endpoint: 'https://api.ondb.io', appId: 'my-store', appKey: process.env.ONDB_APP_KEY }); ``` -------------------------------- ### Get Encryption Settings for an App Source: https://docs.ondb.ai/payments/price-index Retrieves the encryption settings for a specified application. ```APIDOC ## GET /api/apps/{app_id}/encryption ### Description Retrieves the encryption settings for a specified application. ### Method GET ### Endpoint /api/apps/{app_id}/encryption ### Parameters #### Path Parameters - **app_id** (string) - Required - The ID of the application. ### Request Body (Not applicable for GET request) ### Response #### Success Response (200) (Schema not provided in the source text) #### Response Example (Not provided in the source text) ``` -------------------------------- ### GET /api/apps/:app_id/collections Source: https://docs.ondb.ai/payments/price-index Retrieves a list of all collections associated with a specific application. ```APIDOC ## GET /api/apps/:app_id/collections ### Description Lists all collections currently registered under the specified application ID. ### Method GET ### Endpoint /api/apps/:app_id/collections ### Parameters #### Path Parameters - **app_id** (string) - Required - The unique identifier of the application. ### Response #### Success Response (200) - **collections** (array) - A list of collection objects. #### Response Example { "collections": ["users", "posts", "logs"] } ``` -------------------------------- ### Initialize Database and Create PriceIndex Source: https://docs.ondb.ai/payments/price-index Demonstrates how to instantiate the database client with an application ID and configure a PriceIndex on a specific collection field. This index type is used to optimize queries involving price-based data, such as total order values. ```javascript client.database('your-app-id'); // Create PriceIndex on totalPrice field await db.createIndex({ name: 'idx_orders_totalPrice', collection: 'orders', field_name: 'totalPrice', index_type: 'Price' }); // Revenue split is configurable via createPriceIndex() // Default: 80% to app owner, 20% to platform ``` -------------------------------- ### Pricing API Source: https://docs.ondb.ai/llms-full.txt Endpoints for retrieving current pricing information and getting quotes. ```APIDOC ## GET /api/pricing ### Description Retrieves the current pricing information. ### Method GET ### Endpoint /api/pricing ### Response #### Success Response (200) - **pricing_info** (object) - An object containing pricing details. #### Response Example ```json { "pricing_info": { "plan_name": "standard", "price_per_unit": 0.01 } } ``` ## POST /api/pricing/quote ### Description Provides a quote based on specified parameters. ### Method POST ### Endpoint /api/pricing/quote ### Parameters #### Request Body - **parameters** (object) - Required - The parameters for calculating the quote. ### Request Example ```json { "parameters": { "usage_estimate": 10000 } } ``` ### Response #### Success Response (200) - **quote** (object) - An object containing the quote details. #### Response Example ```json { "quote": { "estimated_cost": 100.00 } } ``` ``` -------------------------------- ### Setting Up Event Listeners with TypeScript SDK Source: https://docs.ondb.ai/llms-full.txt Demonstrates how to set up event listeners for various transaction-related events using the Ondb TypeScript SDK. It includes listeners for task queuing, pending transactions, confirmations, failures, and general errors. Requires importing the client and initializing it with endpoint and appKey. ```typescript import { createClient } from '@ondb/sdk'; const client = createClient({ endpoint: 'https://api.ondb.io', appKey: 'your-app-key' }); // Listen for transaction events client.on('transaction:queued', (ticket) => { console.log(`Task ${ticket.ticket_id} queued: ${ticket.message}`); }); client.on('transaction:pending', (tx) => { console.log(`Transaction ${tx.id} is pending...`); }); client.on('transaction:confirmed', (tx) => { console.log(`Transaction ${tx.id} confirmed at block ${tx.block_height}`); }); client.on('transaction:failed', (tx) => { console.error(`Transaction ${tx.id} failed: ${tx.error}`); }); client.on('error', (error) => { console.error('Error occurred:', error); }); // Store data - events will be emitted automatically await client.store( { collection: 'messages', data: [{ message: 'Hello' }] }, paymentCallback ); ``` -------------------------------- ### AI Tools API Endpoints Source: https://docs.ondb.ai/concepts/security This section provides information on the API endpoints for AI tools, including setup instructions. ```APIDOC ## AI Tools API Endpoints ### Description Endpoints related to AI tools setup and usage. ### Endpoints - `GET /ai-tools/setup` ``` -------------------------------- ### POST /api/apps/:app_id/encryption/quote Source: https://docs.ondb.ai/llms-full.txt Gets a quote for encryption feature changes for an application. ```APIDOC ## POST /api/apps/:app_id/encryption/quote ### Description Gets a quote for encryption feature changes for an application. This is typically used before making changes that might incur costs. ### Method POST ### Endpoint /api/apps/:app_id/encryption/quote ### Parameters #### Path Parameters - **app_id** (string) - Required - The ID of the application. ### Request Body - **private_app** (boolean) - Optional - Whether to enable/disable app-level encryption. - **action** (string) - Optional - The action to perform on collections ('add' or 'remove'). - **collections** (array[string]) - Required - The list of collections to apply the action to. ### Request Example ```json { "action": "add", "collections": ["orders", "inventory"] } ``` ### Response #### Success Response (200) - **cost** (number) - The estimated cost for the encryption feature changes. - **currency** (string) - The currency of the cost. #### Response Example ```json { "cost": 10.50, "currency": "USD" } ``` ```