> For the complete documentation index, see [llms.txt](https://tetrics.gitbook.io/x/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://tetrics.gitbook.io/x/developer/api-reference.md).

# API Reference

> **Note:** The APIs are currently in closed alpha testing and not yet live. This reference is for partners to review and understand our development progress.

## Health check

> Returns service readiness information and adapter health status.

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Health","description":"Service health and readiness checks"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"paths":{"/health":{"get":{"tags":["Health"],"summary":"Health check","description":"Returns service readiness information and adapter health status.","operationId":"getHealth","responses":{"200":{"description":"Service is healthy","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HealthResponse"}}}}}}}},"components":{"schemas":{"HealthResponse":{"type":"object","properties":{"status":{"type":"string"},"service":{"type":"string"},"version":{"type":"string"},"chains_supported":{"type":"array","items":{"type":"string"}},"protocols_discovered":{"type":"integer"},"discovery_service_status":{"type":"string"},"adapter_health":{"type":"object","additionalProperties":{"type":"boolean"}}}}}}}
```

## Create login nonce for wallet authentication

> Generates a unique nonce and signing message for wallet-based authentication.\
> \
> \*\*Flow:\*\*\
> 1\. Call this endpoint with your wallet address\
> 2\. Receive a nonce and message to sign\
> 3\. Sign the message with your wallet\
> 4\. Submit signature to \`/auth/login\`\
> \
> \*\*Data Source:\*\* PostgreSQL\
> \*\*Expires:\*\* 5 minutes<br>

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Authentication","description":"Wallet-based authentication and API key management.\n\n**Flow:** Create nonce → Sign with wallet → Login → Receive API key\n\n**Data Source:** PostgreSQL (`api_keys` table)\n"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"paths":{"/auth/nonce":{"post":{"tags":["Authentication"],"summary":"Create login nonce for wallet authentication","description":"Generates a unique nonce and signing message for wallet-based authentication.\n\n**Flow:**\n1. Call this endpoint with your wallet address\n2. Receive a nonce and message to sign\n3. Sign the message with your wallet\n4. Submit signature to `/auth/login`\n\n**Data Source:** PostgreSQL\n**Expires:** 5 minutes\n","operationId":"createNonce","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateNonceRequest"}}}},"responses":{"200":{"description":"Nonce created successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateNonceResponse"}}}},"400":{"description":"Invalid wallet address format"}}}}},"components":{"schemas":{"CreateNonceRequest":{"type":"object","required":["wallet_address"],"properties":{"wallet_address":{"type":"string","pattern":"^0x[a-fA-F0-9]{40}$"}}},"CreateNonceResponse":{"type":"object","properties":{"nonce":{"type":"string","description":"Unique nonce for this authentication attempt"},"message":{"type":"string","description":"Message to sign with wallet"},"expires_in":{"type":"integer","format":"int64","description":"Nonce expiration in seconds"}}}}}}
```

## Login with wallet signature

> Authenticates a user by verifying their wallet signature against the nonce.\
> Returns a JWT token and API key for subsequent requests.\
> \
> \*\*Security:\*\* ECDSA signature verification ensures only the wallet owner can authenticate.\
> \
> \*\*Returns:\*\*\
> \- JWT bearer token (for session-based auth)\
> \- API key credentials (for programmatic access)<br>

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Authentication","description":"Wallet-based authentication and API key management.\n\n**Flow:** Create nonce → Sign with wallet → Login → Receive API key\n\n**Data Source:** PostgreSQL (`api_keys` table)\n"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"paths":{"/auth/login":{"post":{"tags":["Authentication"],"summary":"Login with wallet signature","description":"Authenticates a user by verifying their wallet signature against the nonce.\nReturns a JWT token and API key for subsequent requests.\n\n**Security:** ECDSA signature verification ensures only the wallet owner can authenticate.\n\n**Returns:**\n- JWT bearer token (for session-based auth)\n- API key credentials (for programmatic access)\n","operationId":"login","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/LoginRequest"}}}},"responses":{"200":{"description":"Login successful","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LoginResponse"}}}},"400":{"description":"Invalid request payload"},"401":{"description":"Signature verification failed or nonce expired"}}}}},"components":{"schemas":{"LoginRequest":{"type":"object","required":["wallet_address","nonce","signature"],"properties":{"wallet_address":{"type":"string"},"nonce":{"type":"string"},"signature":{"type":"string","description":"Hex-encoded ECDSA signature"}}},"LoginResponse":{"type":"object","properties":{"jwt":{"type":"string","description":"JWT bearer token for session auth"},"api_key":{"$ref":"#/components/schemas/ApiKeyMaterial"}}},"ApiKeyMaterial":{"type":"object","properties":{"key_id":{"type":"string","format":"uuid"},"secret":{"type":"string","description":"API key secret (only returned on creation)"},"role":{"type":"string"},"rate_limit":{"type":"integer"},"created_at":{"type":"string","format":"date-time"}}}}}}
```

## List user's API keys

> Returns all API keys associated with the authenticated user.\
> \
> \*\*Note:\*\* Secrets are not returned. Only key metadata is shown.<br>

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Authentication","description":"Wallet-based authentication and API key management.\n\n**Flow:** Create nonce → Sign with wallet → Login → Receive API key\n\n**Data Source:** PostgreSQL (`api_keys` table)\n"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"security":[{"ApiKeyAuth":[]}],"components":{"securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"Authorization","description":"API key authentication. Contact the Tetrics team to obtain your API key.\n\n**Format:** `Authorization: ApiKey <key_id>:<secret>`\n\n**Example:** `Authorization: ApiKey 550e8400-e29b-41d4-a716-446655440000:your-secret-key`\n"}},"schemas":{"ApiKeyListResponse":{"type":"object","properties":{"keys":{"type":"array","items":{"$ref":"#/components/schemas/ApiKeyListEntry"}}}},"ApiKeyListEntry":{"type":"object","properties":{"key_id":{"type":"string","format":"uuid"},"label":{"type":"string","nullable":true},"role":{"type":"string"},"rate_limit":{"type":"integer"},"created_at":{"type":"string","format":"date-time"},"last_used_at":{"type":"string","format":"date-time","nullable":true}}}}},"paths":{"/auth/api-keys":{"get":{"tags":["Authentication"],"summary":"List user's API keys","description":"Returns all API keys associated with the authenticated user.\n\n**Note:** Secrets are not returned. Only key metadata is shown.\n","operationId":"listApiKeys","responses":{"200":{"description":"API keys retrieved","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiKeyListResponse"}}}},"401":{"description":"Unauthorized"}}}}}}
```

## Create new API key

> Creates a new API key with custom permissions and rate limits.\
> \
> \*\*Use Cases:\*\*\
> \- Separate keys for different applications\
> \- Custom rate limits per use case\
> \- Role-based access control\
> \
> \*\*Important:\*\* The secret is only returned once. Store it securely.<br>

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Authentication","description":"Wallet-based authentication and API key management.\n\n**Flow:** Create nonce → Sign with wallet → Login → Receive API key\n\n**Data Source:** PostgreSQL (`api_keys` table)\n"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"security":[{"ApiKeyAuth":[]}],"components":{"securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"Authorization","description":"API key authentication. Contact the Tetrics team to obtain your API key.\n\n**Format:** `Authorization: ApiKey <key_id>:<secret>`\n\n**Example:** `Authorization: ApiKey 550e8400-e29b-41d4-a716-446655440000:your-secret-key`\n"}},"schemas":{"CreateApiKeyRequest":{"type":"object","properties":{"label":{"type":"string","nullable":true},"role":{"type":"string","nullable":true},"permissions":{"type":"array","items":{"type":"string"},"nullable":true},"rate_limit":{"type":"integer","nullable":true}}},"CreateApiKeyResponse":{"type":"object","properties":{"key_id":{"type":"string","format":"uuid"},"secret":{"type":"string","description":"Store this securely - it won't be shown again"},"role":{"type":"string"},"rate_limit":{"type":"integer"},"permissions":{"type":"array","items":{"type":"string"}},"created_at":{"type":"string","format":"date-time"}}}}},"paths":{"/auth/api-keys":{"post":{"tags":["Authentication"],"summary":"Create new API key","description":"Creates a new API key with custom permissions and rate limits.\n\n**Use Cases:**\n- Separate keys for different applications\n- Custom rate limits per use case\n- Role-based access control\n\n**Important:** The secret is only returned once. Store it securely.\n","operationId":"createApiKey","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateApiKeyRequest"}}}},"responses":{"201":{"description":"API key created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateApiKeyResponse"}}}},"400":{"description":"Invalid request"},"401":{"description":"Unauthorized"}}}}}}
```

## Revoke an API key

> Permanently revokes an API key. This action cannot be undone.\
> \
> \*\*Use Cases:\*\*\
> \- Rotating compromised keys\
> \- Deactivating unused keys\
> \- Security best practices<br>

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Authentication","description":"Wallet-based authentication and API key management.\n\n**Flow:** Create nonce → Sign with wallet → Login → Receive API key\n\n**Data Source:** PostgreSQL (`api_keys` table)\n"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"security":[{"ApiKeyAuth":[]}],"components":{"securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"Authorization","description":"API key authentication. Contact the Tetrics team to obtain your API key.\n\n**Format:** `Authorization: ApiKey <key_id>:<secret>`\n\n**Example:** `Authorization: ApiKey 550e8400-e29b-41d4-a716-446655440000:your-secret-key`\n"}}},"paths":{"/auth/api-keys/{key_id}":{"delete":{"tags":["Authentication"],"summary":"Revoke an API key","description":"Permanently revokes an API key. This action cannot be undone.\n\n**Use Cases:**\n- Rotating compromised keys\n- Deactivating unused keys\n- Security best practices\n","operationId":"revokeApiKey","parameters":[{"name":"key_id","in":"path","required":true,"description":"API key ID to revoke","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"API key revoked successfully","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string"}}}}}},"401":{"description":"Unauthorized"},"404":{"description":"API key not found"}}}}}}
```

## Get protocol-level staking metrics

> Returns aggregated staking metrics for a protocol (APY, TVL, total stakers).\
> \
> \*\*Scope:\*\* Protocol-wide (not user-specific)\
> \*\*Data Source:\*\* Mixed (DeFiLlama API, protocol APIs, on-chain queries)\
> \*\*Data Freshness:\*\* Cached (refreshed every 5-15 minutes)\
> \
> \*\*Supported Protocols:\*\*\
> \- \`lido\`: Ethereum staking via Lido\
> \- \`wsteth\`: Wrapped stETH\
> \- \`morpho\`: Morpho lending protocol\
> \- \`hype-staking\`: HYPE staking for beHYPE\
> \- \`hyperlend\`: HyperLend protocol\
> \- \`felix\`: Felix CDP protocol\
> \- \`hyperbeat\`: HyperBeat meta vault\
> \
> \*\*Use Cases:\*\* Protocol comparison, APY discovery, TVL monitoring<br>

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Staking Positions","description":"On-chain DeFi staking positions and yield farming analytics (real-time).\n\n**Position Type:** Yield-bearing ERC20 tokens (stETH, wstETH, beHYPE, etc.)\n**Data Source:** On-chain via Ethereum/Hyperliquid RPC\n**Data Freshness:** Real-time blockchain queries\n**Protocols:** Lido, wstETH, Morpho, HYPE Staking, HyperLend, Felix, HyperBeat\n**Use Cases:** Yield monitoring, liquidity tracking, staking rewards analysis\n"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"paths":{"/api/staking/{protocol}/metrics":{"get":{"tags":["Staking Positions"],"summary":"Get protocol-level staking metrics","description":"Returns aggregated staking metrics for a protocol (APY, TVL, total stakers).\n\n**Scope:** Protocol-wide (not user-specific)\n**Data Source:** Mixed (DeFiLlama API, protocol APIs, on-chain queries)\n**Data Freshness:** Cached (refreshed every 5-15 minutes)\n\n**Supported Protocols:**\n- `lido`: Ethereum staking via Lido\n- `wsteth`: Wrapped stETH\n- `morpho`: Morpho lending protocol\n- `hype-staking`: HYPE staking for beHYPE\n- `hyperlend`: HyperLend protocol\n- `felix`: Felix CDP protocol\n- `hyperbeat`: HyperBeat meta vault\n\n**Use Cases:** Protocol comparison, APY discovery, TVL monitoring\n","operationId":"getStakingMetrics","parameters":[{"name":"protocol","in":"path","required":true,"description":"Protocol identifier","schema":{"type":"string","enum":["lido","wsteth","morpho","hype-staking","hyperlend","felix","hyperbeat"]}}],"responses":{"200":{"description":"Protocol metrics","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StakingMetricsResponse"}}}},"404":{"description":"Protocol not found"}}}}},"components":{"schemas":{"StakingMetricsResponse":{"type":"object","properties":{"protocol":{"type":"string"},"apy":{"type":"string"},"tvl":{"type":"string"},"total_stakers":{"type":"integer"},"updated_at":{"type":"string","format":"date-time"}}}}}}
```

## Get protocol metadata and validation constraints

> Returns protocol configuration including supported methods, parameter constraints, and gas estimates.\
> \
> \*\*Data Source:\*\* JSON protocol configuration files\
> \*\*Use Cases:\*\* Dynamic form generation, parameter validation, gas estimation<br>

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Staking Positions","description":"On-chain DeFi staking positions and yield farming analytics (real-time).\n\n**Position Type:** Yield-bearing ERC20 tokens (stETH, wstETH, beHYPE, etc.)\n**Data Source:** On-chain via Ethereum/Hyperliquid RPC\n**Data Freshness:** Real-time blockchain queries\n**Protocols:** Lido, wstETH, Morpho, HYPE Staking, HyperLend, Felix, HyperBeat\n**Use Cases:** Yield monitoring, liquidity tracking, staking rewards analysis\n"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"paths":{"/api/staking/{protocol}/metadata":{"get":{"tags":["Staking Positions"],"summary":"Get protocol metadata and validation constraints","description":"Returns protocol configuration including supported methods, parameter constraints, and gas estimates.\n\n**Data Source:** JSON protocol configuration files\n**Use Cases:** Dynamic form generation, parameter validation, gas estimation\n","operationId":"getStakingMetadata","parameters":[{"name":"protocol","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Protocol metadata","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StakingMetadataResponse"}}}}}}}},"components":{"schemas":{"StakingMetadataResponse":{"type":"object","properties":{"protocol":{"type":"string"},"supported_methods":{"type":"array","items":{"type":"string"}},"validation_constraints":{"type":"object"},"gas_estimates":{"type":"object"}}}}}}
```

## Get user staking positions (real-time on-chain)

> Returns current staking balances across all supported protocols by querying blockchain in real-time.\
> \
> \*\*Position Type:\*\* Yield-bearing ERC20 tokens (stETH, wstETH, beHYPE, etc.)\
> \*\*Data Source:\*\* On-chain (Ethereum/Hyperliquid RPC via \`PositionTracker\`)\
> \*\*Data Freshness:\*\* Real-time blockchain query\
> \*\*Chain Scope:\*\* Multi-chain (Ethereum + Hyperliquid)\
> \
> \*\*Returns:\*\*\
> \- All non-zero token balances for staking protocols\
> \- Current USD values\
> \- Protocol metadata\
> \
> \*\*Use Cases:\*\* Real-time portfolio tracking, yield monitoring, liquidity management<br>

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Staking Positions","description":"On-chain DeFi staking positions and yield farming analytics (real-time).\n\n**Position Type:** Yield-bearing ERC20 tokens (stETH, wstETH, beHYPE, etc.)\n**Data Source:** On-chain via Ethereum/Hyperliquid RPC\n**Data Freshness:** Real-time blockchain queries\n**Protocols:** Lido, wstETH, Morpho, HYPE Staking, HyperLend, Felix, HyperBeat\n**Use Cases:** Yield monitoring, liquidity tracking, staking rewards analysis\n"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"security":[{"ApiKeyAuth":[]}],"components":{"securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"Authorization","description":"API key authentication. Contact the Tetrics team to obtain your API key.\n\n**Format:** `Authorization: ApiKey <key_id>:<secret>`\n\n**Example:** `Authorization: ApiKey 550e8400-e29b-41d4-a716-446655440000:your-secret-key`\n"}},"schemas":{"StakingPositionsResponse":{"type":"object","properties":{"wallet":{"type":"string"},"positions":{"type":"array","items":{"type":"object","properties":{"protocol":{"type":"string"},"chain":{"type":"string"},"token":{"type":"string"},"balance":{"type":"string"},"value_usd":{"type":"string"}}}}}}}},"paths":{"/api/staking/positions/{wallet}":{"get":{"tags":["Staking Positions"],"summary":"Get user staking positions (real-time on-chain)","description":"Returns current staking balances across all supported protocols by querying blockchain in real-time.\n\n**Position Type:** Yield-bearing ERC20 tokens (stETH, wstETH, beHYPE, etc.)\n**Data Source:** On-chain (Ethereum/Hyperliquid RPC via `PositionTracker`)\n**Data Freshness:** Real-time blockchain query\n**Chain Scope:** Multi-chain (Ethereum + Hyperliquid)\n\n**Returns:**\n- All non-zero token balances for staking protocols\n- Current USD values\n- Protocol metadata\n\n**Use Cases:** Real-time portfolio tracking, yield monitoring, liquidity management\n","operationId":"getStakingPositions","parameters":[{"name":"wallet","in":"path","required":true,"description":"Wallet address","schema":{"type":"string","pattern":"^0x[a-fA-F0-9]{40}$"}}],"responses":{"200":{"description":"Current staking positions","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StakingPositionsResponse"}}}},"401":{"description":"Unauthorized"}}}}}}
```

## Get staking transaction history

> Returns historical staking transactions (stakes, withdrawals) for the user.\
> \
> \*\*Data Source:\*\* PostgreSQL (\`staking\_position\_history\` table)\
> \*\*Data Freshness:\*\* Updated after each staking transaction\
> \
> \*\*Use Cases:\*\* Transaction history, audit trails, rewards tracking<br>

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Staking Positions","description":"On-chain DeFi staking positions and yield farming analytics (real-time).\n\n**Position Type:** Yield-bearing ERC20 tokens (stETH, wstETH, beHYPE, etc.)\n**Data Source:** On-chain via Ethereum/Hyperliquid RPC\n**Data Freshness:** Real-time blockchain queries\n**Protocols:** Lido, wstETH, Morpho, HYPE Staking, HyperLend, Felix, HyperBeat\n**Use Cases:** Yield monitoring, liquidity tracking, staking rewards analysis\n"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"security":[{"ApiKeyAuth":[]}],"components":{"securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"Authorization","description":"API key authentication. Contact the Tetrics team to obtain your API key.\n\n**Format:** `Authorization: ApiKey <key_id>:<secret>`\n\n**Example:** `Authorization: ApiKey 550e8400-e29b-41d4-a716-446655440000:your-secret-key`\n"}},"schemas":{"StakingHistoryResponse":{"type":"object","properties":{"wallet":{"type":"string"},"transactions":{"type":"array","items":{"type":"object"}}}}}},"paths":{"/api/staking/positions/{wallet}/history":{"get":{"tags":["Staking Positions"],"summary":"Get staking transaction history","description":"Returns historical staking transactions (stakes, withdrawals) for the user.\n\n**Data Source:** PostgreSQL (`staking_position_history` table)\n**Data Freshness:** Updated after each staking transaction\n\n**Use Cases:** Transaction history, audit trails, rewards tracking\n","operationId":"getStakingHistory","parameters":[{"name":"wallet","in":"path","required":true,"schema":{"type":"string"}},{"name":"protocol","in":"query","description":"Filter by protocol","schema":{"type":"string"}},{"name":"limit","in":"query","schema":{"type":"integer","default":50}}],"responses":{"200":{"description":"Staking history","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StakingHistoryResponse"}}}}}}}}}
```

## Get aggregated staking summary

> Returns aggregated staking statistics across all protocols for the user.\
> \
> \*\*Data Source:\*\* Computed from on-chain positions\
> \*\*Aggregations:\*\* Total staked value (USD), positions by protocol, positions by chain\
> \
> \*\*Use Cases:\*\* Portfolio overview, total value calculation, protocol diversification analysis<br>

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Staking Positions","description":"On-chain DeFi staking positions and yield farming analytics (real-time).\n\n**Position Type:** Yield-bearing ERC20 tokens (stETH, wstETH, beHYPE, etc.)\n**Data Source:** On-chain via Ethereum/Hyperliquid RPC\n**Data Freshness:** Real-time blockchain queries\n**Protocols:** Lido, wstETH, Morpho, HYPE Staking, HyperLend, Felix, HyperBeat\n**Use Cases:** Yield monitoring, liquidity tracking, staking rewards analysis\n"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"security":[{"ApiKeyAuth":[]}],"components":{"securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"Authorization","description":"API key authentication. Contact the Tetrics team to obtain your API key.\n\n**Format:** `Authorization: ApiKey <key_id>:<secret>`\n\n**Example:** `Authorization: ApiKey 550e8400-e29b-41d4-a716-446655440000:your-secret-key`\n"}},"schemas":{"StakingSummaryResponse":{"type":"object","properties":{"wallet":{"type":"string"},"total_staked_usd":{"type":"string"},"positions_by_protocol":{"type":"object"},"positions_by_chain":{"type":"object"}}}}},"paths":{"/api/staking/positions/{wallet}/summary":{"get":{"tags":["Staking Positions"],"summary":"Get aggregated staking summary","description":"Returns aggregated staking statistics across all protocols for the user.\n\n**Data Source:** Computed from on-chain positions\n**Aggregations:** Total staked value (USD), positions by protocol, positions by chain\n\n**Use Cases:** Portfolio overview, total value calculation, protocol diversification analysis\n","operationId":"getStakingSummary","parameters":[{"name":"wallet","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Staking summary","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StakingSummaryResponse"}}}}}}}}}
```

## Execute staking transaction

> Executes a staking transaction (stake, unstake, withdraw, etc.) for the specified protocol.\
> \
> \*\*Execution Modes:\*\*\
> \- \`direct\`: API executes transaction with its own wallet (testing/development)\
> \- \`broadcast\`: User provides signed transaction for broadcasting (production)\
> \
> \*\*Supported Methods (vary by protocol):\*\*\
> \- \`deposit\`, \`stake\`: Stake tokens\
> \- \`withdraw\`, \`unstake\`: Withdraw staked tokens\
> \- \`wrap\`, \`unwrap\`: Convert between token forms (e.g., stETH ↔ wstETH)\
> \- \`supply\`, \`borrow\`, \`repay\`, \`redeem\`: Lending operations (Morpho, HyperLend)\
> \
> \*\*Data Source:\*\* On-chain execution via protocol adapters\
> \*\*Returns:\*\* Transaction receipt with gas used, output amounts<br>

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Staking Positions","description":"On-chain DeFi staking positions and yield farming analytics (real-time).\n\n**Position Type:** Yield-bearing ERC20 tokens (stETH, wstETH, beHYPE, etc.)\n**Data Source:** On-chain via Ethereum/Hyperliquid RPC\n**Data Freshness:** Real-time blockchain queries\n**Protocols:** Lido, wstETH, Morpho, HYPE Staking, HyperLend, Felix, HyperBeat\n**Use Cases:** Yield monitoring, liquidity tracking, staking rewards analysis\n"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"security":[{"ApiKeyAuth":[]}],"components":{"securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"Authorization","description":"API key authentication. Contact the Tetrics team to obtain your API key.\n\n**Format:** `Authorization: ApiKey <key_id>:<secret>`\n\n**Example:** `Authorization: ApiKey 550e8400-e29b-41d4-a716-446655440000:your-secret-key`\n"}},"schemas":{"StakingActionRequest":{"type":"object","required":["amount"],"properties":{"amount":{"type":"string","description":"Amount in token units (wei for ETH)"},"asset":{"type":"string","nullable":true},"method":{"type":"string","nullable":true},"recipient":{"type":"string","nullable":true},"user_address":{"type":"string","nullable":true},"mode":{"type":"string","enum":["direct","broadcast"],"nullable":true},"decimals":{"type":"integer","nullable":true},"extra_params":{"type":"object","additionalProperties":{},"nullable":true},"signed_transaction":{"type":"string","nullable":true,"description":"For broadcast mode"}}},"StakingExecutionResponse":{"type":"object","properties":{"success":{"type":"boolean"},"tx_hash":{"type":"string","nullable":true},"gas_used":{"type":"string","nullable":true},"output_amount":{"type":"string","nullable":true},"error":{"type":"string","nullable":true}}}}},"paths":{"/staking/{protocol}/stake":{"post":{"tags":["Staking Positions"],"summary":"Execute staking transaction","description":"Executes a staking transaction (stake, unstake, withdraw, etc.) for the specified protocol.\n\n**Execution Modes:**\n- `direct`: API executes transaction with its own wallet (testing/development)\n- `broadcast`: User provides signed transaction for broadcasting (production)\n\n**Supported Methods (vary by protocol):**\n- `deposit`, `stake`: Stake tokens\n- `withdraw`, `unstake`: Withdraw staked tokens\n- `wrap`, `unwrap`: Convert between token forms (e.g., stETH ↔ wstETH)\n- `supply`, `borrow`, `repay`, `redeem`: Lending operations (Morpho, HyperLend)\n\n**Data Source:** On-chain execution via protocol adapters\n**Returns:** Transaction receipt with gas used, output amounts\n","operationId":"executeStaking","parameters":[{"name":"protocol","in":"path","required":true,"schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StakingActionRequest"}}}},"responses":{"200":{"description":"Transaction executed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StakingExecutionResponse"}}}},"400":{"description":"Invalid parameters"},"422":{"description":"Transaction failed"}}}}}}
```

## Preview staking action without executing

> Simulates a staking transaction to preview gas costs and output amounts without executing on-chain.\
> \
> \*\*Use Cases:\*\* Gas estimation, parameter validation, dry-run testing\
> \
> \*\*Returns:\*\*\
> \- Estimated gas cost\
> \- Expected output amount\
> \- Validation errors (if any)<br>

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Staking Positions","description":"On-chain DeFi staking positions and yield farming analytics (real-time).\n\n**Position Type:** Yield-bearing ERC20 tokens (stETH, wstETH, beHYPE, etc.)\n**Data Source:** On-chain via Ethereum/Hyperliquid RPC\n**Data Freshness:** Real-time blockchain queries\n**Protocols:** Lido, wstETH, Morpho, HYPE Staking, HyperLend, Felix, HyperBeat\n**Use Cases:** Yield monitoring, liquidity tracking, staking rewards analysis\n"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"security":[{"ApiKeyAuth":[]}],"components":{"securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"Authorization","description":"API key authentication. Contact the Tetrics team to obtain your API key.\n\n**Format:** `Authorization: ApiKey <key_id>:<secret>`\n\n**Example:** `Authorization: ApiKey 550e8400-e29b-41d4-a716-446655440000:your-secret-key`\n"}},"schemas":{"StakingActionRequest":{"type":"object","required":["amount"],"properties":{"amount":{"type":"string","description":"Amount in token units (wei for ETH)"},"asset":{"type":"string","nullable":true},"method":{"type":"string","nullable":true},"recipient":{"type":"string","nullable":true},"user_address":{"type":"string","nullable":true},"mode":{"type":"string","enum":["direct","broadcast"],"nullable":true},"decimals":{"type":"integer","nullable":true},"extra_params":{"type":"object","additionalProperties":{},"nullable":true},"signed_transaction":{"type":"string","nullable":true,"description":"For broadcast mode"}}},"StakingPreviewResponse":{"type":"object","properties":{"estimated_gas":{"type":"string"},"expected_output":{"type":"string"},"validation_errors":{"type":"array","items":{"type":"string"}}}}}},"paths":{"/staking/{protocol}/preview":{"post":{"tags":["Staking Positions"],"summary":"Preview staking action without executing","description":"Simulates a staking transaction to preview gas costs and output amounts without executing on-chain.\n\n**Use Cases:** Gas estimation, parameter validation, dry-run testing\n\n**Returns:**\n- Estimated gas cost\n- Expected output amount\n- Validation errors (if any)\n","operationId":"previewStaking","parameters":[{"name":"protocol","in":"path","required":true,"schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StakingActionRequest"}}}},"responses":{"200":{"description":"Preview result","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StakingPreviewResponse"}}}},"400":{"description":"Invalid parameters"}}}}}}
```

## Get all margin positions (cross-chain)

> Returns unified view of all collateral and debt positions across lending protocols and chains.\
> \
> \*\*Position Type:\*\* Collateral deposits and borrowed amounts\
> \*\*Data Source:\*\* PostgreSQL (\`cross\_chain\_positions\` table)\
> \*\*Data Freshness:\*\* Last sync timestamp (call \`/sync\` to update)\
> \*\*Chain Scope:\*\* Cross-chain (Ethereum + Hyperliquid)\
> \*\*Protocols:\*\* Morpho, HyperLend, Aave-like protocols\
> \
> \*\*Returns:\*\*\
> \- All collateral positions\
> \- All debt positions\
> \- Grouped by chain and protocol\
> \- USD values and weighted amounts\
> \- Market overview and top exposures\
> \
> \*\*Use Cases:\*\*\
> \- Unified portfolio view\
> \- Cross-protocol position tracking\
> \- Collateral diversification analysis\
> \
> \*\*Important:\*\* Data is synced from blockchain. Call \`/api/margin/sync/:address\` to refresh.<br>

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Margin & Lending","description":"Cross-chain borrowing position tracking and health monitoring (database-synced).\n\n**Position Type:** Collateral deposits and debt obligations\n**Data Source:** PostgreSQL (synced from on-chain via `/sync` endpoint)\n**Data Freshness:** Last sync timestamp (manual or scheduled)\n**Protocols:** Morpho, HyperLend, Aave-like lending protocols\n**Use Cases:** Leveraged position management, liquidation prevention, risk monitoring\n\n**Important:** Call `/api/margin/sync/:address` to refresh data from blockchain.\n"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"security":[{"ApiKeyAuth":[]}],"components":{"securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"Authorization","description":"API key authentication. Contact the Tetrics team to obtain your API key.\n\n**Format:** `Authorization: ApiKey <key_id>:<secret>`\n\n**Example:** `Authorization: ApiKey 550e8400-e29b-41d4-a716-446655440000:your-secret-key`\n"}},"schemas":{"MarginPositionsResponse":{"type":"object","properties":{"margin_account":{"type":"object","properties":{"address":{"type":"string"},"total_collateral_usd":{"type":"string"},"total_borrowed_usd":{"type":"string"},"health_factor":{"type":"string","nullable":true}}},"positions":{"type":"array","items":{"$ref":"#/components/schemas/PositionDetail"}},"positions_by_chain":{"type":"object","additionalProperties":{"type":"array","items":{"$ref":"#/components/schemas/PositionDetail"}}},"collateral_positions":{"type":"array","items":{"$ref":"#/components/schemas/PositionDetail"}},"debt_positions":{"type":"array","items":{"$ref":"#/components/schemas/PositionDetail"}}}},"PositionDetail":{"type":"object","properties":{"protocol":{"type":"string"},"chain":{"type":"string"},"asset":{"type":"string"},"position_type":{"type":"string","enum":["collateral","debt"]},"amount":{"type":"string"},"value_usd":{"type":"string"},"weighted_value_usd":{"type":"string","nullable":true}}}}},"paths":{"/api/margin/positions/{address}":{"get":{"tags":["Margin & Lending"],"summary":"Get all margin positions (cross-chain)","description":"Returns unified view of all collateral and debt positions across lending protocols and chains.\n\n**Position Type:** Collateral deposits and borrowed amounts\n**Data Source:** PostgreSQL (`cross_chain_positions` table)\n**Data Freshness:** Last sync timestamp (call `/sync` to update)\n**Chain Scope:** Cross-chain (Ethereum + Hyperliquid)\n**Protocols:** Morpho, HyperLend, Aave-like protocols\n\n**Returns:**\n- All collateral positions\n- All debt positions\n- Grouped by chain and protocol\n- USD values and weighted amounts\n- Market overview and top exposures\n\n**Use Cases:**\n- Unified portfolio view\n- Cross-protocol position tracking\n- Collateral diversification analysis\n\n**Important:** Data is synced from blockchain. Call `/api/margin/sync/:address` to refresh.\n","operationId":"getMarginPositions","parameters":[{"name":"address","in":"path","required":true,"description":"Margin account address","schema":{"type":"string","pattern":"^0x[a-fA-F0-9]{40}$"}}],"responses":{"200":{"description":"Margin positions","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MarginPositionsResponse"}}}},"401":{"description":"Unauthorized"},"404":{"description":"Margin account not found"}}}}}}
```

## Get comprehensive health metrics for liquidation risk

> Returns detailed health factor analysis and liquidation risk metrics.\
> \
> \*\*Data Source:\*\* PostgreSQL (\`health\_snapshots\` table)\
> \*\*Calculation:\*\* Weighted collateral / weighted debt with protocol-specific LTV ratios\
> \*\*Data Freshness:\*\* Last sync timestamp\
> \
> \*\*Metrics:\*\*\
> \- Health factor (>1.0 = safe, <1.0 = liquidatable)\
> \- Total collateral (USD)\
> \- Weighted collateral with LTV ratios\
> \- Total debt (USD)\
> \- Distance to liquidation (%)\
> \- Max borrowable amount\
> \- Risk level (healthy/warning/critical)\
> \
> \*\*Use Cases:\*\*\
> \- Liquidation prevention\
> \- Risk monitoring alerts\
> \- Borrowing capacity calculation\
> \
> \*\*Important:\*\* Call \`/api/margin/sync/:address\` first for up-to-date health metrics.<br>

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Margin & Lending","description":"Cross-chain borrowing position tracking and health monitoring (database-synced).\n\n**Position Type:** Collateral deposits and debt obligations\n**Data Source:** PostgreSQL (synced from on-chain via `/sync` endpoint)\n**Data Freshness:** Last sync timestamp (manual or scheduled)\n**Protocols:** Morpho, HyperLend, Aave-like lending protocols\n**Use Cases:** Leveraged position management, liquidation prevention, risk monitoring\n\n**Important:** Call `/api/margin/sync/:address` to refresh data from blockchain.\n"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"security":[{"ApiKeyAuth":[]}],"components":{"securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"Authorization","description":"API key authentication. Contact the Tetrics team to obtain your API key.\n\n**Format:** `Authorization: ApiKey <key_id>:<secret>`\n\n**Example:** `Authorization: ApiKey 550e8400-e29b-41d4-a716-446655440000:your-secret-key`\n"}},"schemas":{"MarginHealthResponse":{"type":"object","properties":{"address":{"type":"string"},"health_factor":{"type":"string","nullable":true,"description":"Greater than 1.0 = safe, less than 1.0 = liquidatable"},"risk_level":{"type":"string","enum":["healthy","warning","critical"]},"total_collateral_usd":{"type":"string"},"weighted_collateral_usd":{"type":"string"},"total_debt_usd":{"type":"string"},"weighted_debt_usd":{"type":"string"},"liquidation_threshold_usd":{"type":"string"},"distance_to_liquidation_pct":{"type":"string"},"max_borrowable_usd":{"type":"string"}}}}},"paths":{"/api/margin/health/{address}":{"get":{"tags":["Margin & Lending"],"summary":"Get comprehensive health metrics for liquidation risk","description":"Returns detailed health factor analysis and liquidation risk metrics.\n\n**Data Source:** PostgreSQL (`health_snapshots` table)\n**Calculation:** Weighted collateral / weighted debt with protocol-specific LTV ratios\n**Data Freshness:** Last sync timestamp\n\n**Metrics:**\n- Health factor (>1.0 = safe, <1.0 = liquidatable)\n- Total collateral (USD)\n- Weighted collateral with LTV ratios\n- Total debt (USD)\n- Distance to liquidation (%)\n- Max borrowable amount\n- Risk level (healthy/warning/critical)\n\n**Use Cases:**\n- Liquidation prevention\n- Risk monitoring alerts\n- Borrowing capacity calculation\n\n**Important:** Call `/api/margin/sync/:address` first for up-to-date health metrics.\n","operationId":"getMarginHealth","parameters":[{"name":"address","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Health metrics","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MarginHealthResponse"}}}},"401":{"description":"Unauthorized"}}}}}}
```

## Sync positions from blockchain

> Triggers synchronization of margin positions from on-chain state to database.\
> \
> \*\*Process:\*\*\
> 1\. Queries all lending protocols on-chain\
> 2\. Fetches oracle prices\
> 3\. Calculates health metrics\
> 4\. Updates database with latest positions\
> \
> \*\*Data Source:\*\* On-chain → PostgreSQL via \`PositionSyncService\`\
> \*\*Duration:\*\* \~2-5 seconds\
> \*\*Protocols Synced:\*\* All enabled lending protocols (optional filter)\
> \
> \*\*Use Cases:\*\*\
> \- Before checking health factor\
> \- After executing positions on-chain\
> \- Scheduled background jobs\
> \
> \*\*Returns:\*\* Sync job status with updated position counts<br>

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Margin & Lending","description":"Cross-chain borrowing position tracking and health monitoring (database-synced).\n\n**Position Type:** Collateral deposits and debt obligations\n**Data Source:** PostgreSQL (synced from on-chain via `/sync` endpoint)\n**Data Freshness:** Last sync timestamp (manual or scheduled)\n**Protocols:** Morpho, HyperLend, Aave-like lending protocols\n**Use Cases:** Leveraged position management, liquidation prevention, risk monitoring\n\n**Important:** Call `/api/margin/sync/:address` to refresh data from blockchain.\n"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"security":[{"ApiKeyAuth":[]}],"components":{"securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"Authorization","description":"API key authentication. Contact the Tetrics team to obtain your API key.\n\n**Format:** `Authorization: ApiKey <key_id>:<secret>`\n\n**Example:** `Authorization: ApiKey 550e8400-e29b-41d4-a716-446655440000:your-secret-key`\n"}},"schemas":{"MarginSyncRequest":{"type":"object","properties":{"protocols":{"type":"array","items":{"type":"string"},"nullable":true,"description":"Optional filter for specific protocols"}}},"MarginSyncResponse":{"type":"object","properties":{"address":{"type":"string"},"synced_positions":{"type":"integer"},"total_collateral_usd":{"type":"string"},"total_borrowed_usd":{"type":"string"},"job_id":{"type":"string"},"duration_ms":{"type":"integer","format":"int64"},"message":{"type":"string"}}}}},"paths":{"/api/margin/sync/{address}":{"post":{"tags":["Margin & Lending"],"summary":"Sync positions from blockchain","description":"Triggers synchronization of margin positions from on-chain state to database.\n\n**Process:**\n1. Queries all lending protocols on-chain\n2. Fetches oracle prices\n3. Calculates health metrics\n4. Updates database with latest positions\n\n**Data Source:** On-chain → PostgreSQL via `PositionSyncService`\n**Duration:** ~2-5 seconds\n**Protocols Synced:** All enabled lending protocols (optional filter)\n\n**Use Cases:**\n- Before checking health factor\n- After executing positions on-chain\n- Scheduled background jobs\n\n**Returns:** Sync job status with updated position counts\n","operationId":"syncMarginPositions","parameters":[{"name":"address","in":"path","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MarginSyncRequest"}}}},"responses":{"200":{"description":"Sync completed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MarginSyncResponse"}}}},"401":{"description":"Unauthorized"},"422":{"description":"Sync failed"}}}}}}
```

## List lending markets with metrics and filtering

> Returns lending market metrics across all supported protocols with advanced filtering.\
> \
> \*\*Scope:\*\* Protocol-wide market data (not user-specific)\
> \*\*Data Source:\*\* PostgreSQL (\`market\_metrics\`, \`market\_protocol\_metrics\` tables)\
> \*\*Data Freshness:\*\* Background scheduler updates every 5-15 minutes\
> \
> \*\*Metrics:\*\*\
> \- Total supply and borrow (USD)\
> \- Utilization rate\
> \- Supply APY and borrow APY\
> \- Oracle health status\
> \- Risk score\
> \- Market volatility\
> \
> \*\*Filters:\*\*\
> \- \`protocol\`: Filter by protocol name\
> \- \`chain\`: Filter by chain\
> \- \`asset\`: Filter by asset symbol\
> \- \`market\_type\`: lending/borrowing/vault\
> \- \`risk\_min\`/\`risk\_max\`: Filter by risk score\
> \
> \*\*Use Cases:\*\*\
> \- Market opportunity discovery\
> \- Yield comparison across protocols\
> \- Risk-based market filtering\
> \
> \*\*Note:\*\* This endpoint should ideally be at \`/api/markets\` (not \`/api/margin/markets\`).<br>

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Market Intelligence","description":"Protocol-wide lending market metrics and risk analysis (background-scheduled).\n\n**Scope:** Aggregated market data (not user-specific)\n**Data Source:** PostgreSQL (updated by `MarketAnalyticsScheduler`)\n**Data Freshness:** Scheduled background updates (every 5-15 minutes)\n**Metrics:** TVL, utilization rates, APY, borrow/supply rates, oracle health\n**Use Cases:** Market opportunity discovery, protocol risk assessment, yield optimization\n\n**Note:** These endpoints provide protocol-level analytics, not individual user positions.\n"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"security":[{"ApiKeyAuth":[]}],"components":{"securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"Authorization","description":"API key authentication. Contact the Tetrics team to obtain your API key.\n\n**Format:** `Authorization: ApiKey <key_id>:<secret>`\n\n**Example:** `Authorization: ApiKey 550e8400-e29b-41d4-a716-446655440000:your-secret-key`\n"}},"schemas":{"MarketMetricsResponse":{"type":"object","properties":{"protocol_metrics":{"type":"array","items":{"type":"object","properties":{"protocol":{"type":"string"},"total_supply_usd":{"type":"string"},"total_borrow_usd":{"type":"string"},"average_utilization":{"type":"string"}}}},"market_metrics":{"type":"array","items":{"$ref":"#/components/schemas/MarketMetric"}}}},"MarketMetric":{"type":"object","properties":{"market_id":{"type":"string"},"protocol":{"type":"string"},"chain":{"type":"string"},"asset":{"type":"string"},"total_supply":{"type":"string"},"total_borrow":{"type":"string"},"utilization_rate":{"type":"string"},"supply_apy":{"type":"string"},"borrow_apy":{"type":"string"},"risk_score":{"type":"string"},"updated_at":{"type":"string","format":"date-time"}}}}},"paths":{"/api/margin/markets":{"get":{"tags":["Market Intelligence"],"summary":"List lending markets with metrics and filtering","description":"Returns lending market metrics across all supported protocols with advanced filtering.\n\n**Scope:** Protocol-wide market data (not user-specific)\n**Data Source:** PostgreSQL (`market_metrics`, `market_protocol_metrics` tables)\n**Data Freshness:** Background scheduler updates every 5-15 minutes\n\n**Metrics:**\n- Total supply and borrow (USD)\n- Utilization rate\n- Supply APY and borrow APY\n- Oracle health status\n- Risk score\n- Market volatility\n\n**Filters:**\n- `protocol`: Filter by protocol name\n- `chain`: Filter by chain\n- `asset`: Filter by asset symbol\n- `market_type`: lending/borrowing/vault\n- `risk_min`/`risk_max`: Filter by risk score\n\n**Use Cases:**\n- Market opportunity discovery\n- Yield comparison across protocols\n- Risk-based market filtering\n\n**Note:** This endpoint should ideally be at `/api/markets` (not `/api/margin/markets`).\n","operationId":"listMarketMetrics","parameters":[{"name":"protocol","in":"query","schema":{"type":"string"}},{"name":"chain","in":"query","schema":{"type":"string"}},{"name":"asset","in":"query","schema":{"type":"string"}},{"name":"market_type","in":"query","schema":{"type":"string","enum":["lending","borrowing","vault"]}},{"name":"risk_min","in":"query","schema":{"type":"string"}},{"name":"risk_max","in":"query","schema":{"type":"string"}}],"responses":{"200":{"description":"Market metrics","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MarketMetricsResponse"}}}},"401":{"description":"Unauthorized"}}}}}}
```

## Get markets for specific protocol

> Returns all lending markets and aggregated protocol metrics for a single protocol.\
> \
> \*\*Data Source:\*\* PostgreSQL\
> \*\*Returns:\*\*\
> \- Individual market metrics\
> \- Protocol-level aggregates (total TVL, average utilization, etc.)\
> \
> \*\*Use Cases:\*\* Protocol-specific analysis, deep-dive into single protocol<br>

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Market Intelligence","description":"Protocol-wide lending market metrics and risk analysis (background-scheduled).\n\n**Scope:** Aggregated market data (not user-specific)\n**Data Source:** PostgreSQL (updated by `MarketAnalyticsScheduler`)\n**Data Freshness:** Scheduled background updates (every 5-15 minutes)\n**Metrics:** TVL, utilization rates, APY, borrow/supply rates, oracle health\n**Use Cases:** Market opportunity discovery, protocol risk assessment, yield optimization\n\n**Note:** These endpoints provide protocol-level analytics, not individual user positions.\n"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"security":[{"ApiKeyAuth":[]}],"components":{"securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"Authorization","description":"API key authentication. Contact the Tetrics team to obtain your API key.\n\n**Format:** `Authorization: ApiKey <key_id>:<secret>`\n\n**Example:** `Authorization: ApiKey 550e8400-e29b-41d4-a716-446655440000:your-secret-key`\n"}},"schemas":{"ProtocolMarketsResponse":{"type":"object","properties":{"protocol":{"type":"string"},"markets":{"type":"array","items":{"$ref":"#/components/schemas/MarketMetric"}},"aggregates":{"type":"object","properties":{"total_tvl":{"type":"string"},"average_utilization":{"type":"string"}}}}},"MarketMetric":{"type":"object","properties":{"market_id":{"type":"string"},"protocol":{"type":"string"},"chain":{"type":"string"},"asset":{"type":"string"},"total_supply":{"type":"string"},"total_borrow":{"type":"string"},"utilization_rate":{"type":"string"},"supply_apy":{"type":"string"},"borrow_apy":{"type":"string"},"risk_score":{"type":"string"},"updated_at":{"type":"string","format":"date-time"}}}}},"paths":{"/api/margin/markets/{protocol}":{"get":{"tags":["Market Intelligence"],"summary":"Get markets for specific protocol","description":"Returns all lending markets and aggregated protocol metrics for a single protocol.\n\n**Data Source:** PostgreSQL\n**Returns:**\n- Individual market metrics\n- Protocol-level aggregates (total TVL, average utilization, etc.)\n\n**Use Cases:** Protocol-specific analysis, deep-dive into single protocol\n","operationId":"getProtocolMarkets","parameters":[{"name":"protocol","in":"path","required":true,"description":"Protocol identifier (e.g., \"morpho\", \"hyperlend\")","schema":{"type":"string"}}],"responses":{"200":{"description":"Protocol markets","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProtocolMarketsResponse"}}}},"401":{"description":"Unauthorized"},"404":{"description":"Protocol not found"}}}}}}
```

## Get market history for time-series analysis

> Returns historical snapshots of market metrics for trend analysis.\
> \
> \*\*Data Source:\*\* PostgreSQL (\`market\_metrics\_history\` table)\
> \*\*Granularity:\*\* Hourly or daily snapshots\
> \*\*Time Range:\*\* Configurable via query parameters\
> \
> \*\*Use Cases:\*\*\
> \- Utilization trend charts\
> \- APY history tracking\
> \- Market volatility analysis\
> \
> \*\*Query Parameters:\*\*\
> \- \`market\_id\`: Specific market identifier (required)\
> \- \`start\_date\`: Start of time range\
> \- \`end\_date\`: End of time range\
> \- \`limit\`: Max number of snapshots<br>

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Market Intelligence","description":"Protocol-wide lending market metrics and risk analysis (background-scheduled).\n\n**Scope:** Aggregated market data (not user-specific)\n**Data Source:** PostgreSQL (updated by `MarketAnalyticsScheduler`)\n**Data Freshness:** Scheduled background updates (every 5-15 minutes)\n**Metrics:** TVL, utilization rates, APY, borrow/supply rates, oracle health\n**Use Cases:** Market opportunity discovery, protocol risk assessment, yield optimization\n\n**Note:** These endpoints provide protocol-level analytics, not individual user positions.\n"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"security":[{"ApiKeyAuth":[]}],"components":{"securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"Authorization","description":"API key authentication. Contact the Tetrics team to obtain your API key.\n\n**Format:** `Authorization: ApiKey <key_id>:<secret>`\n\n**Example:** `Authorization: ApiKey 550e8400-e29b-41d4-a716-446655440000:your-secret-key`\n"}},"schemas":{"MarketHistoryResponse":{"type":"object","properties":{"market_id":{"type":"string"},"history":{"type":"array","items":{"type":"object","properties":{"timestamp":{"type":"string","format":"date-time"},"utilization_rate":{"type":"string"},"supply_apy":{"type":"string"},"borrow_apy":{"type":"string"}}}}}}}},"paths":{"/api/margin/markets/{protocol}/history":{"get":{"tags":["Market Intelligence"],"summary":"Get market history for time-series analysis","description":"Returns historical snapshots of market metrics for trend analysis.\n\n**Data Source:** PostgreSQL (`market_metrics_history` table)\n**Granularity:** Hourly or daily snapshots\n**Time Range:** Configurable via query parameters\n\n**Use Cases:**\n- Utilization trend charts\n- APY history tracking\n- Market volatility analysis\n\n**Query Parameters:**\n- `market_id`: Specific market identifier (required)\n- `start_date`: Start of time range\n- `end_date`: End of time range\n- `limit`: Max number of snapshots\n","operationId":"getMarketHistory","parameters":[{"name":"protocol","in":"path","required":true,"schema":{"type":"string"}},{"name":"market_id","in":"query","required":true,"schema":{"type":"string"}},{"name":"start_date","in":"query","schema":{"type":"string","format":"date-time"}},{"name":"end_date","in":"query","schema":{"type":"string","format":"date-time"}},{"name":"limit","in":"query","schema":{"type":"integer","default":100}}],"responses":{"200":{"description":"Market history","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MarketHistoryResponse"}}}},"401":{"description":"Unauthorized"}}}}}}
```

## Simulate market scenario (what-if analysis)

> Simulates the impact of a supply or borrow action on market metrics.\
> \
> \*\*Simulation Logic:\*\*\
> \- Adds hypothetical supply/borrow to current market state\
> \- Recalculates utilization rate\
> \- Projects new APY based on utilization curve\
> \- Estimates new risk score\
> \
> \*\*Use Cases:\*\*\
> \- What-if analysis before large positions\
> \- Optimal amount calculation\
> \- Market impact estimation\
> \
> \*\*Inputs:\*\*\
> \- \`market\_id\`: Target market\
> \- \`action\`: "supply" or "borrow"\
> \- \`amount\`: Amount to simulate (in token units)\
> \- \`stress\_pct\`: Optional stress test % (default: 0)\
> \
> \*\*Returns:\*\*\
> \- Projected supply and borrow amounts\
> \- Projected utilization rate\
> \- Projected risk score\
> \- Warnings if thresholds exceeded<br>

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Market Intelligence","description":"Protocol-wide lending market metrics and risk analysis (background-scheduled).\n\n**Scope:** Aggregated market data (not user-specific)\n**Data Source:** PostgreSQL (updated by `MarketAnalyticsScheduler`)\n**Data Freshness:** Scheduled background updates (every 5-15 minutes)\n**Metrics:** TVL, utilization rates, APY, borrow/supply rates, oracle health\n**Use Cases:** Market opportunity discovery, protocol risk assessment, yield optimization\n\n**Note:** These endpoints provide protocol-level analytics, not individual user positions.\n"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"security":[{"ApiKeyAuth":[]}],"components":{"securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"Authorization","description":"API key authentication. Contact the Tetrics team to obtain your API key.\n\n**Format:** `Authorization: ApiKey <key_id>:<secret>`\n\n**Example:** `Authorization: ApiKey 550e8400-e29b-41d4-a716-446655440000:your-secret-key`\n"}},"schemas":{"MarketSimulationRequest":{"type":"object","required":["market_id","action","amount"],"properties":{"market_id":{"type":"string"},"action":{"type":"string","enum":["supply","borrow"]},"amount":{"type":"string","description":"Amount in token units"},"stress_pct":{"type":"number","nullable":true,"description":"Stress test percentage (default 0)"}}},"MarketSimulationResponse":{"type":"object","properties":{"protocol":{"type":"string"},"market_id":{"type":"string"},"action":{"type":"string"},"amount":{"type":"string"},"projected_supply":{"type":"string"},"projected_borrow":{"type":"string"},"projected_utilization_pct":{"type":"string"},"projected_risk":{"type":"string"},"notes":{"type":"array","items":{"type":"string"}}}}}},"paths":{"/api/margin/markets/{protocol}/simulate":{"post":{"tags":["Market Intelligence"],"summary":"Simulate market scenario (what-if analysis)","description":"Simulates the impact of a supply or borrow action on market metrics.\n\n**Simulation Logic:**\n- Adds hypothetical supply/borrow to current market state\n- Recalculates utilization rate\n- Projects new APY based on utilization curve\n- Estimates new risk score\n\n**Use Cases:**\n- What-if analysis before large positions\n- Optimal amount calculation\n- Market impact estimation\n\n**Inputs:**\n- `market_id`: Target market\n- `action`: \"supply\" or \"borrow\"\n- `amount`: Amount to simulate (in token units)\n- `stress_pct`: Optional stress test % (default: 0)\n\n**Returns:**\n- Projected supply and borrow amounts\n- Projected utilization rate\n- Projected risk score\n- Warnings if thresholds exceeded\n","operationId":"simulateMarket","parameters":[{"name":"protocol","in":"path","required":true,"schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MarketSimulationRequest"}}}},"responses":{"200":{"description":"Simulation result","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MarketSimulationResponse"}}}},"400":{"description":"Invalid simulation parameters"},"401":{"description":"Unauthorized"}}}}}}
```

## List supported protocol adapters

> Returns metadata for all registered protocol adapters grouped by chain.

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Protocols","description":"Discover supported DeFi protocols and their capabilities"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"paths":{"/protocols":{"get":{"tags":["Protocols"],"summary":"List supported protocol adapters","description":"Returns metadata for all registered protocol adapters grouped by chain.","operationId":"listProtocols","responses":{"200":{"description":"Protocol metadata","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProtocolsResponse"}}}}}}}},"components":{"schemas":{"ProtocolsResponse":{"type":"object","properties":{"protocols":{"type":"array","items":{"$ref":"#/components/schemas/ProtocolInfo"}},"protocols_by_chain":{"type":"object","additionalProperties":{"type":"array","items":{"type":"string"}}},"total_protocols":{"type":"integer"}}},"ProtocolInfo":{"type":"object","properties":{"name":{"type":"string"},"chain":{"type":"string","description":"Supported chain identifier (e.g. `Ethereum`, `Hyperliquid`)"},"version":{"type":"string"},"description":{"type":"string"},"supported_methods":{"type":"array","items":{"type":"string"}},"contract_address":{"type":"string","description":"Adapter contract address"},"requires_approval":{"type":"boolean"}}}}}}
```

## Discovery service status

> Returns adapter discovery statistics and configuration health.

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Protocols","description":"Discover supported DeFi protocols and their capabilities"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"paths":{"/protocols/discovery":{"get":{"tags":["Protocols"],"summary":"Discovery service status","description":"Returns adapter discovery statistics and configuration health.","operationId":"getProtocolDiscoveryInfo","responses":{"200":{"description":"Discovery status","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProtocolDiscoveryInfo"}}}}}}}},"components":{"schemas":{"ProtocolDiscoveryInfo":{"type":"object","properties":{"total_protocols_discovered":{"type":"integer"},"total_protocols_enabled":{"type":"integer"},"protocols_by_chain":{"type":"object","additionalProperties":{"type":"array","items":{"type":"string"}}},"health_status":{"type":"object","additionalProperties":{"type":"boolean"}},"discovery_stats":{"type":"object","additionalProperties":{}},"last_config_reload":{"type":"integer","format":"int64","nullable":true}}}}}}
```

## Get balances for default account

> Returns a balance snapshot for the default account used in automated tests.

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Balances","description":"Query wallet balances across supported chains"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"paths":{"/balances":{"get":{"tags":["Balances"],"summary":"Get balances for default account","description":"Returns a balance snapshot for the default account used in automated tests.","operationId":"getBalancesDefault","responses":{"200":{"description":"Balance snapshot","content":{"application/json":{"schema":{"$ref":"#/components/schemas/BalanceResponse"}}}}}}}},"components":{"schemas":{"BalanceResponse":{"type":"object","properties":{"account":{"type":"string"},"balances_by_chain":{"type":"object","additionalProperties":{"$ref":"#/components/schemas/ChainBalance"}}}},"ChainBalance":{"type":"object","properties":{"native_token":{"type":"string","description":"Native token balance as decimal string"},"tokens":{"type":"object","additionalProperties":{"type":"string","description":"Token balance as decimal string"}}}}}}}
```

## Get balances for a wallet

> Returns ETH and token balances for the provided wallet across all supported chains.

```json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"Balances","description":"Query wallet balances across supported chains"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"paths":{"/balances/{account}":{"get":{"tags":["Balances"],"summary":"Get balances for a wallet","description":"Returns ETH and token balances for the provided wallet across all supported chains.","operationId":"getBalancesForAccount","parameters":[{"name":"account","in":"path","required":true,"description":"Wallet address (0x-prefixed)","schema":{"type":"string","pattern":"^0x[a-fA-F0-9]{40}$"}}],"responses":{"200":{"description":"Balance snapshot","content":{"application/json":{"schema":{"$ref":"#/components/schemas/BalanceResponse"}}}},"400":{"description":"Invalid account address supplied"}}}}},"components":{"schemas":{"BalanceResponse":{"type":"object","properties":{"account":{"type":"string"},"balances_by_chain":{"type":"object","additionalProperties":{"$ref":"#/components/schemas/ChainBalance"}}}},"ChainBalance":{"type":"object","properties":{"native_token":{"type":"string","description":"Native token balance as decimal string"},"tokens":{"type":"object","additionalProperties":{"type":"string","description":"Token balance as decimal string"}}}}}}}
```

## WebSocket connection for real-time updates

> Establishes a WebSocket connection for streaming real-time strategy execution updates, transaction receipts,\
> and balance changes.\
> \
> \*\*Message Types:\*\*\
> \- \`strategy\_progress\` - Step-by-step execution updates\
> \- \`transaction\_update\` - Transaction confirmation events\
> \- \`balance\_update\` - Wallet balance changes\
> \- \`error\` - Execution errors and warnings\
> \
> \*\*Example Message:\*\*\
> \`\`\`json\
> {\
> &#x20; "type": "strategy\_progress",\
> &#x20; "data": {\
> &#x20;   "execution\_id": "abc-123",\
> &#x20;   "step": 2,\
> &#x20;   "total\_steps": 5,\
> &#x20;   "protocol": "lido",\
> &#x20;   "status": "completed"\
> &#x20; }\
> }\
> \`\`\`<br>

````json
{"openapi":"3.0.3","info":{"title":"Tetrics Reactor API","version":"0.2.0"},"tags":[{"name":"WebSocket","description":"Real-time execution updates and notifications"}],"servers":[{"url":"https://api.tetrics.io","description":"Production API"},{"url":"http://localhost:4001","description":"Local development server"}],"paths":{"/ws":{"get":{"tags":["WebSocket"],"summary":"WebSocket connection for real-time updates","description":"Establishes a WebSocket connection for streaming real-time strategy execution updates, transaction receipts,\nand balance changes.\n\n**Message Types:**\n- `strategy_progress` - Step-by-step execution updates\n- `transaction_update` - Transaction confirmation events\n- `balance_update` - Wallet balance changes\n- `error` - Execution errors and warnings\n\n**Example Message:**\n```json\n{\n  \"type\": \"strategy_progress\",\n  \"data\": {\n    \"execution_id\": \"abc-123\",\n    \"step\": 2,\n    \"total_steps\": 5,\n    \"protocol\": \"lido\",\n    \"status\": \"completed\"\n  }\n}\n```\n","operationId":"websocketStream","responses":{"101":{"description":"WebSocket connection established"},"400":{"description":"Invalid WebSocket upgrade request"}}}}}}
````
