### Initialize Project and Install Dependencies Source: https://github.com/mydcc/cachy-app/blob/develop/DEPLOYMENT.md Commands to clone the repository, install required Node.js packages, and generate the production build artifacts. ```bash cd /www/wwwroot/cachy.app git clone https://github.com/mydcc/cachy-app.git . npm install npm run build ``` -------------------------------- ### Project Setup and Development Commands Source: https://github.com/mydcc/cachy-app/blob/develop/README.md Standard shell commands for cloning the repository, installing dependencies, and launching the development server for the Cachy-App. ```bash git clone https://github.com/mydcc/cachy-app.git cd cachy-app npm install npm run dev ``` -------------------------------- ### Start Local SpaceTimeDB Server Source: https://github.com/mydcc/cachy-app/blob/develop/server/CLAUDE.md Command to initiate a local SpaceTimeDB development server for testing and debugging. ```bash spacetime start ``` -------------------------------- ### Automated Deployment Scripts Source: https://github.com/mydcc/cachy-app/blob/develop/DEPLOYMENT.md Shell scripts used to automate the deployment process, including backups, dependency installation, build validation, and service restarts. ```bash # Deploy to staging ./deploy.sh # Deploy to production ./deploy_prod.sh ``` -------------------------------- ### Define Tables and Schema Source: https://github.com/mydcc/cachy-app/blob/develop/server/CLAUDE.md Demonstrates the correct structure for defining tables with indexes in the options object and exporting the schema. Includes examples of available column types and modifiers. ```typescript import { schema, table, t } from 'spacetimedb/server'; export const Task = table({ name: 'task', public: true, indexes: [{ name: 'by_owner', algorithm: 'btree', columns: ['ownerId'] }] }, { id: t.u64().primaryKey().autoInc(), ownerId: t.identity(), title: t.string(), createdAt: t.timestamp(), }); export const spacetimedb = schema(Task); ``` -------------------------------- ### SpacetimeDB CLI Commands Source: https://github.com/mydcc/cachy-app/blob/develop/server/CLAUDE.md Essential CLI commands for managing the SpacetimeDB lifecycle, including starting the local server, publishing modules, generating client bindings, and viewing logs. ```bash # Start local SpacetimeDB spacetime start # Publish module spacetime publish --project-path # Clear and republish spacetime publish --clear-database -y --project-path # Generate client bindings spacetime generate --lang --out-dir --project-path # View logs spacetime logs ``` -------------------------------- ### Perform Manual Application Update Source: https://github.com/mydcc/cachy-app/blob/develop/DEPLOYMENT.md Steps to manually update the application by pulling the latest code from Git, installing dependencies, and rebuilding the project. This is an alternative to using automated deployment scripts. ```bash cd /www/wwwroot/cachy.app git pull npm ci --legacy-peer-deps npm run build ``` -------------------------------- ### Production Build and Deployment Commands Source: https://github.com/mydcc/cachy-app/blob/develop/README.md Commands to generate a production build of the SvelteKit application and start the server, including an optional command for PM2 process management. ```bash npm run build npm start pm2 start build/index.js --name "cachy-app" ``` -------------------------------- ### Manual Rollback Procedure Source: https://github.com/mydcc/cachy-app/blob/develop/DEPLOYMENT.md Commands to list available backups for manual restoration in case of deployment failure. ```bash ls -la /backups/cachy/dev/ ls -la /backups/cachy/prod/ ``` -------------------------------- ### Common Workflows Source: https://github.com/mydcc/cachy-app/blob/develop/docs/bitunix-api/README.md Example workflows demonstrating common trading actions using the API. ```APIDOC ## Common Workflows ### Workflow 1: Place Limit Order ```javascript // 1. Check balance GET /api/v1/futures/account/balance // 2. Get current price GET /api/v1/futures/market/ticker?symbol=BTCUSDT // 3. Place order POST /api/v1/futures/trade/place_order { "symbol": "BTCUSDT", "side": "BUY", "orderType": "LIMIT", "qty": 0.01, "price": 49500, "effect": "GTC" } // 4. Check order status GET /api/v1/futures/trade/get_order_detail?orderId=... ``` ``` -------------------------------- ### Subscribe to Views in SpaceTimeDB Client Source: https://github.com/mydcc/cachy-app/blob/develop/server/CLAUDE.md Shows how to explicitly subscribe to views using SQL queries in the client-side connection setup, as views require explicit subscription. ```typescript conn.subscriptionBuilder().subscribe([ 'SELECT * FROM public_table', 'SELECT * FROM my_data', // Views need explicit SQL! ]); ``` -------------------------------- ### Troubleshoot Deployment and Service Issues Source: https://github.com/mydcc/cachy-app/blob/develop/DEPLOYMENT.md Common commands for debugging deployment failures, including log inspection, removing stale lock files, and verifying network port availability. ```bash tail -f /var/log/cachy/deploy_YYYYMMDD.log rm /tmp/cachy_deploy_dev.lock lsof -i :3001 ``` -------------------------------- ### Publish SpaceTimeDB Module Source: https://github.com/mydcc/cachy-app/blob/develop/server/CLAUDE.md Command to deploy a SpaceTimeDB module to a network, requiring the module name and project path. ```bash spacetime publish --project-path ``` -------------------------------- ### Define and Schedule Tables in TypeScript Source: https://github.com/mydcc/cachy-app/blob/develop/server/CLAUDE.md Demonstrates how to define a scheduled table with `scheduledId` and `scheduledAt` columns and how to schedule and cancel jobs using SpaceTimeDB reducers. ```typescript export const CleanupJob = table({ name: 'cleanup_job', scheduled: 'run_cleanup' // reducer name }, { scheduledId: t.u64().primaryKey().autoInc(), scheduledAt: t.scheduleAt(), targetId: t.u64(), // Your custom data }); // Scheduled reducer receives full row as arg spacetimedb.reducer('run_cleanup', { arg: CleanupJob.rowType }, (ctx, { arg }) => { // arg.scheduledId, arg.targetId available // Row is auto-deleted after reducer completes }); // Schedule a job import { ScheduleAt } from 'spacetimedb'; const futureTime = ctx.timestamp.microsSinceUnixEpoch + 60_000_000n; // 60 seconds ctx.db.cleanupJob.insert({ scheduledId: 0n, scheduledAt: ScheduleAt.time(futureTime), targetId: someId }); // Cancel a job by deleting the row ctx.db.cleanupJob.scheduledId.delete(jobId); ``` -------------------------------- ### Memoize Connection Builder in React Source: https://github.com/mydcc/cachy-app/blob/develop/server/CLAUDE.md Demonstrates using `useMemo` to create the `DbConnection.builder` instance only once in a React component, optimizing performance by avoiding redundant creations. ```typescript const builder = useMemo(() => DbConnection.builder() .withUri(SPACETIMEDB_URI) .withModuleName(MODULE_NAME) .withToken(localStorage.getItem('auth_token') || undefined) .onConnect(onConnect) .onConnectError(onConnectError), [] // Empty deps - only create once ); ``` -------------------------------- ### Generate SpaceTimeDB Client Bindings Source: https://github.com/mydcc/cachy-app/blob/develop/server/CLAUDE.md Command to generate TypeScript bindings for the SpaceTimeDB client, specifying the output directory and project path. ```bash spacetime generate --lang typescript --out-dir /src/module_bindings --project-path ``` -------------------------------- ### View SpaceTimeDB Module Logs Source: https://github.com/mydcc/cachy-app/blob/develop/server/CLAUDE.md Command to access the logs of a running SpaceTimeDB module, useful for monitoring and troubleshooting. ```bash spacetime logs ``` -------------------------------- ### Standard API Request and Response Formats Source: https://github.com/mydcc/cachy-app/blob/develop/docs/bitunix-api/README.md Examples of HTTP request structures and the standardized TypeScript interface for all API responses. ```http GET /api/v1/futures/trade/get_pending_orders?symbol=BTCUSDT&page=1 Headers: { "api-key": "...", "nonce": "...", "timestamp": "...", "sign": "..." } ``` ```typescript { code: number; // 0 = success, other = error msg: string; // Success message or error description data?: any; // Response payload (if applicable) } ``` -------------------------------- ### Server Project Structure for SpaceTimeDB Source: https://github.com/mydcc/cachy-app/blob/develop/server/CLAUDE.md Outlines the typical file structure for the server-side of a SpaceTimeDB project, including schema definition, reducer implementation, and necessary configuration files. ```plaintext src/schema.ts → Tables, export spacetimedb src/index.ts → Reducers, lifecycle, import schema package.json → { "type": "module", "dependencies": { "spacetimedb": "^1.11.0" } } tsconfig.json → Standard config ``` -------------------------------- ### TypeScript SDK Correct Implementation Patterns Source: https://github.com/mydcc/cachy-app/blob/develop/server/CLAUDE.md Demonstrates the correct way to import generated bindings, use React hooks for data access, and invoke reducers using the required object syntax. ```typescript // ✅ CORRECT IMPORTS import { DbConnection, tables } from './module_bindings'; // Generated! import { SpacetimeDBProvider, useTable, Identity } from 'spacetimedb/react'; // ✅ CORRECT REDUCER CALLS — object syntax, not positional! conn.reducers.doSomething({ value: 'test' }); conn.reducers.updateItem({ itemId: 1n, newValue: 42 }); // ✅ CORRECT DATA ACCESS — useTable returns [rows, isLoading] const [items, isLoading] = useTable(tables.item); ``` -------------------------------- ### Implement Reducers and Lifecycle Hooks Source: https://github.com/mydcc/cachy-app/blob/develop/server/CLAUDE.md Defines how to create reducers with parameter validation and table mutations, as well as handling client connection and disconnection lifecycle events. ```typescript spacetimedb.reducer('reducer_name', { param1: t.string() }, (ctx, { param1 }) => { if (!param1) throw new SenderError('param1 required'); ctx.db.myTable.insert({ ... }); }); spacetimedb.clientConnected((ctx) => { /* Handle connection */ }); spacetimedb.clientDisconnected((ctx) => { /* Handle disconnection */ }); ``` -------------------------------- ### Client Project Structure for SpaceTimeDB Source: https://github.com/mydcc/cachy-app/blob/develop/server/CLAUDE.md Details the standard directory layout for the client-side of a SpaceTimeDB application, including generated module bindings, main entry point, UI components, and configuration. ```plaintext src/module_bindings/ → Generated (spacetime generate) src/main.tsx → Provider, connection setup src/App.tsx → UI components src/config.ts → MODULE_NAME, SPACETIMEDB_URI ``` -------------------------------- ### Svelte 5 Derived State Example Source: https://github.com/mydcc/cachy-app/blob/develop/AGENT.md Illustrates how to use Svelte 5's `$derived` rune to create reactive values based on other state variables. This is crucial for performance by avoiding re-computation. ```svelte

Full Name: {fullName}

``` -------------------------------- ### Perform Database Operations Source: https://github.com/mydcc/cachy-app/blob/develop/server/CLAUDE.md Covers proper insertion patterns using auto-increment placeholders and handling return values. Also demonstrates filtering versus finding rows using indexes. ```typescript // Insert with auto-inc placeholder ctx.db.task.insert({ id: 0n, ownerId: ctx.sender, title: 'New', createdAt: ctx.timestamp }); // Insert returns the row, not the ID const row = ctx.db.task.insert({ ... }); const newId = row.id; // Filter vs Find const rows = [...ctx.db.task.by_owner.filter(ownerId)]; const row = ctx.db.player.identity.find(ctx.sender); ``` -------------------------------- ### TypeScript SDK Anti-Patterns Source: https://github.com/mydcc/cachy-app/blob/develop/server/CLAUDE.md Examples of common incorrect API usage and hallucinated methods that should be avoided when developing with the SpacetimeDB TypeScript SDK. ```typescript // ❌ WRONG PACKAGE — does not exist import { SpacetimeDBClient } from "@clockworklabs/spacetimedb-sdk"; // ❌ WRONG — these methods don't exist SpacetimeDBClient.connect(...); SpacetimeDBClient.call("reducer_name", [...]); connection.call("reducer_name", [arg1, arg2]); // ❌ WRONG — positional reducer arguments conn.reducers.doSomething("value"); ``` -------------------------------- ### Run Unit and Performance Tests with Vitest Source: https://github.com/mydcc/cachy-app/blob/develop/docs/calculation-engine-dev.md Demonstrates various `vitest` commands for running different types of tests, including unit tests for edge cases, performance benchmarks, memory profiling, and load testing. It also shows how to run all calculation-related tests and perform type checking. ```bash # Unit tests (edge cases) npx vitest run src/tests/unit/edge_cases.test.ts # Performance benchmarks npx vitest run src/tests/performance/engine_benchmark.test.ts # Memory profiling npx vitest run src/tests/performance/memory_profiling.test.ts # Load testing (1k-50k candles) npx vitest run src/tests/performance/load_testing.test.ts # All calculation tests npx vitest run src/tests/unit/edge_cases.test.ts src/tests/performance/ # Type checking npx tsc --noEmit ``` -------------------------------- ### WebGPU Engine Shader for Indicator Calculation Source: https://github.com/mydcc/cachy-app/blob/develop/docs/calculation-engine-dev.md Provides an example of a WGSL shader used for GPU-accelerated indicator calculations. This shader defines input buffers, uniform parameters, and the output buffer, along with the compute kernel logic for processing data on the GPU. ```wgsl @group(0) @binding(0) var input: array; @group(0) @binding(1) var params: Params; @group(0) @binding(2) var output: array; struct Params { window_size: u32, data_len: u32, } @compute @workgroup_size(256) fn main(@builtin(global_invocation_id) gid: vec3) { let i = gid.x; if (i >= params.data_len) { return; } // ... calculation logic ... output[i] = result; } ``` -------------------------------- ### GET /api/v1/futures/trade/get_order_detail Source: https://github.com/mydcc/cachy-app/blob/develop/docs/bitunix-api/README.md Retrieve detailed information for a specific futures order. ```APIDOC ## GET /api/v1/futures/trade/get_order_detail ### Description Get details of a specific order. ### Method GET ### Endpoint `/api/v1/futures/trade/get_order_detail` ### Parameters #### Query Parameters - **orderId** (string) - Required - The ID of the order to retrieve. - **symbol** (string) - Required - The trading symbol (e.g., "BTCUSDT"). ### Response (No specific response format provided in the documentation, but it's expected to return detailed information about the specified order, similar to the 'data' field in the 'Get Pending Orders' response.) ``` -------------------------------- ### GET /api/tickers Source: https://context7.com/mydcc/cachy-app/llms.txt Retrieves a market snapshot of tickers from a specified exchange provider. ```APIDOC ## GET /api/tickers ### Description Fetches current market ticker data from a specific exchange provider. ### Method GET ### Endpoint /api/tickers ### Parameters #### Query Parameters - **provider** (string) - Required - The exchange provider (e.g., bitget). ### Request Example curl "http://localhost:5173/api/tickers?provider=bitget" ### Response #### Success Response (200) - **data** (array) - List of ticker objects. ``` -------------------------------- ### GET /api/v1/futures/trade/get_pending_orders Source: https://github.com/mydcc/cachy-app/blob/develop/docs/bitunix-api/README.md Retrieve a list of all pending futures orders, with optional filtering by symbol and pagination. ```APIDOC ## GET /api/v1/futures/trade/get_pending_orders ### Description Get all pending orders. ### Method GET ### Endpoint `/api/v1/futures/trade/get_pending_orders` ### Parameters #### Query Parameters - **symbol** (string) - Optional - Filter by symbol - **page** (number) - Optional - Default: 1 - **pageSize** (number) - Optional - Default: 20, Max: 100 ### Response #### Success Response (200) - **code** (number) - 0 for success - **data** (object) - **orders** (array) - **orderId** (string) - **symbol** (string) - **side** (string) - **orderType** (string) - **price** (string) - **qty** (string) - **filledQty** (string) - **status** (string) - **createTime** (number) - **total** (number) - Total number of pending orders - **page** (number) - Current page number - **pageSize** (number) - Number of orders per page #### Response Example ```json { "code": 0, "data": { "orders": [ { "orderId": "123456789", "symbol": "BTCUSDT", "side": "BUY", "orderType": "LIMIT", "price": "50000.00", "qty": "0.001", "filledQty": "0.000", "status": "NEW", "createTime": 1705900800000 } ], "total": 1, "page": 1, "pageSize": 20 } } ``` ``` -------------------------------- ### CSS Theming with Paired Utility Classes Source: https://github.com/mydcc/cachy-app/blob/develop/AGENT.md Demonstrates the use of paired CSS utility classes for theming, ensuring accessibility and consistent contrast across different themes. Avoids hardcoded colors and relies on CSS variables and predefined paired classes. ```html
This div uses paired utility classes for background and text contrast.
This is a success message.
This is an error message.
``` -------------------------------- ### Testing and Quality Assurance Commands Source: https://github.com/mydcc/cachy-app/blob/develop/README.md Commands to execute unit tests using Vitest and run linting tools to ensure code quality and adherence to project standards. ```bash npm test npm run lint ``` -------------------------------- ### Handle Timestamps Server-Side in TypeScript Source: https://github.com/mydcc/cachy-app/blob/develop/server/CLAUDE.md Illustrates how to use `ctx.timestamp` for current and future timestamps when inserting data into tables on the server-side. ```typescript import { Timestamp, ScheduleAt } from 'spacetimedb'; // Current time ctx.db.item.insert({ id: 0n, createdAt: ctx.timestamp }); // Future time (add microseconds) const future = ctx.timestamp.microsSinceUnixEpoch + 300_000_000n; // 5 minutes ``` -------------------------------- ### Clear Database and Republish SpaceTimeDB Module Source: https://github.com/mydcc/cachy-app/blob/develop/server/CLAUDE.md Command to publish a SpaceTimeDB module while ensuring the database is cleared first, using the `-y` flag for confirmation. ```bash spacetime publish --clear-database -y --project-path ``` -------------------------------- ### Define Application Environment Variables Source: https://github.com/mydcc/cachy-app/blob/develop/DEPLOYMENT.md Configuration file format for setting application-specific variables like port and origin. The ORIGIN variable is critical for SvelteKit Form Actions to prevent CSRF errors. ```env PORT=3001 ORIGIN=https://cachy.app NODE_ENV=production ``` -------------------------------- ### Implement Settings UI Component Structure in Svelte Source: https://github.com/mydcc/cachy-app/blob/develop/plans/settings-ui-optimization-20260228.md Demonstrates the usage of the new reusable SettingsGroup and SettingsRow components. This structure enforces consistent visual hierarchy and layout for settings controls. ```svelte ``` -------------------------------- ### Synchronize Trade History Source: https://context7.com/mydcc/cachy-app/llms.txt Imports historical trade data for journal integration. Supports pagination and time-range filtering using start and end timestamps. ```bash curl -X POST "http://localhost:5173/api/sync" \ -H "Content-Type: application/json" \ -H "X-App-Auth: your-app-auth-token" \ -d '{ "apiKey": "your-api-key", "apiSecret": "your-api-secret", "startTime": 1704067200000, "endTime": 1704672000000, "limit": 50 }' ```