TradeMarketsCreditsSearch
Medusa Logo
Medusa
  • Trade
  • Markets
  • Launchpad
  • AI Credits
  • AnalyticsDocumentationAPI Reference
/
1.00Credits
Elysium
QuickstartAPI Reference
/v1 (OpenAI Compatible)
Manage API Keys
On this page8 min · 0%
  1. 01Overview
  2. 02Authentication
  3. 03TypeScript SDK (@medusadex/sdk)
  4. 04Chat CompletionsPOST
  5. 05Agent Tools & CallingSPEC
  6. 06List ModelsGET
  7. 07Programmatic Key APIPOST
  8. 08Agent Wallet AuthPOST
  9. 09Model Context Protocol (/api/mcp)
  10. 10Credit Metering & Pricing
  11. 11Errors & Status Codes

Medusa Developer Reference

The Medusa API is an OpenAI-compatible HTTP interface for running frontier LLM inference and on-chain contract intelligence. Every DEX trade executed on the protocol credits your connected wallet with compute quota, allowing programmatic access without credit cards or third-party subscriptions.

Base URL
http://localhost:3000/api/ai/v1
All standard OpenAI endpoints append to this path.
Specification
OpenAI Spec 2024 / JSON & SSE
Compatible with OpenCode, Cursor, Aider, and Python.

Authentication

Medusa supports flexible authentication options: Developer API Keys for web applications and CLI tools, Direct Agent EOA Wallet Auth for autonomous agents launched on the launchpad, and Cryptographic Wallet Challenge Keys.

Mode A · API KeyStandard
Authorization: Bearer mdsa_live_...

Created via the Credits dashboard or programmatically via POST /api/ai/keys. Deducts from your wallet's compute credit balance.

Mode B · Agent EOALaunchpad
Authorization: Bearer 0x...

Direct EOA address authentication for agents provisioned via the launchpad. 30% of token trading volume continuously refills this balance.

Mode C · Web3 SignatureAutonomous
POST /api/ai/keys/wallet

Zero sign-in required. An agent signs a cryptographic challenge message with its private key to generate an authenticated session instantly.

AttributeSpecification
Prefixmdsa_live_ (production/testnet unified)
Storage & HashingStored as SHA-256 hash. The raw secret is returned only once upon generation.
Limits5 active keys per connected wallet address. Revocation is instantaneous.

TypeScript SDK (@medusadex/sdk)

The official @medusadex/sdk client library provides unified, type-safe access to Medusa's LLM inference gateway, autonomous agent tools with max_cost budget protection, and live bonding curve trackers.

Installation & Usage (@medusadex/sdk)
// Install: pnpm add @medusadex/sdk
import { createMedusa } from "@medusadex/sdk";

const medusa = createMedusa({
  apiKey: process.env.MEDUSA_API_KEY!, // mdsa_live_...
  baseUrl: "http://localhost:3000",
});

// 1. OpenAI-Compatible Chat Completion
const chat = await medusa.chat.completions.create({
  model: "deepseek/deepseek-r1",
  messages: [{ role: "user", content: "Optimize AMM route on Elysium" }],
});
console.log(chat.choices[0].message.content);

// 2. Autonomous Tool Calling with max_cost Budget Protection
const quote = await medusa.getQuote({
  tokenIn: "0x0269031ace34a7821e9d9980d087c35ce7c19eef", // WHYPE
  tokenOut: "0x9a9815af521149e8d982791703a31bca2f95f534", // MEDUSA
  amountIn: "10.0",
});
console.log("Estimated Output:", quote.amountOut);

// 3. DEX Token & Bonding Curve Tracking
const token = await medusa.tokens.get("0xcac5b6e74eb7383af0a6dc344d996e225bbf9a17");
console.log(`${token.symbol} Price: $${token.priceUsd} | Progress: ${token.progress}%`);
POST/api/ai/v1/chat/completions

Generates model completions for a list of chat messages. Supports Server-Sent Events (SSE) streaming for real-time token output.

Request Parameters
FieldTypeRequired
modelstringYes
Identifier of the model to use (e.g. deepseek/deepseek-r1, anthropic/claude-3.5-sonnet).
messagesMessage[]Yes
Array of message objects with role (user, assistant, system, tool) and content.
streambooleanOptional
If true, returns Server-Sent Events stream as tokens generate. Default: false.
toolsTool[]Optional
Array of function tools that the model may call to inspect on-chain state or execute swaps.
zero_retentionbooleanUnavailable (503)
Not currently available. A request with this field set to true (or header x-zero-retention: true) returns 503. Do not assume enclave execution or zero retention; upstream provider policies apply.
curl -X POST http://localhost:3000/api/ai/v1/chat/completions \
  -H "Authorization: Bearer mdsa_live_YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek/deepseek-r1",
    "messages": [
      {"role": "user", "content": "Compute AMM output"}
    ],
    "stream": true
  }'
Response (200 OK)
{
  "id": "chatcmpl-f53903e0a1894ba1aed138c4",
  "object": "chat.completion",
  "model": "deepseek/deepseek-r1",
  "choices": [{
    "index": 0,
    "message": { "role": "assistant", "content": "export function calculateSwap..." },
    "finish_reason": "stop"
  }],
  "usage": { "prompt_tokens": 12, "completion_tokens": 120, "total_tokens": 132 },
  "medusaCompute": { "creditsCost": 0.02, "creditsRemaining": 1.76 }
}
SPECAgent Tools & Function Calling

Medusa supports standard OpenAI function calling. Autonomous agents can invoke native on-chain tools—such as contract security verification and multi-launchpad swap quotes—without writing custom blockchain parsing logic.

Native Protocol Tools
Function NameParametersDescription
get_swap_quotetokenIn, tokenOut, amountInQueries dynamic order router across BOXA, Kleos, ElysPump, and Ascend liquidity pools.
get_bonding_curvetokenAddressReturns launchpad bonding curve graduation percentage, real reserves, and target liquidity.
Tool Calling Payload Example
curl -X POST http://localhost:3000/api/ai/v1/chat/completions \
  -H "Authorization: Bearer mdsa_live_YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek/deepseek-r1",
    "messages": [
      {"role": "user", "content": "What is the quote for 10 HYPE to MEDUSA?"}
    ],
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_swap_quote",
        "description": "Fetch real-time swap quote from Elysium DEX pools",
        "parameters": {
          "type": "object",
          "properties": {
            "tokenIn": { "type": "string" },
            "tokenOut": { "type": "string" },
            "amountIn": { "type": "string" }
          },
          "required": ["tokenIn", "tokenOut", "amountIn"]
        }
      }
    }]
  }'
GET/api/ai/v1/models

Returns a list of currently active model identifiers that can be passed to the completions endpoint. Supports live server-side filtering via query parameters.

Query Parameters
ParameterTypeDescription
providerstringFilter by provider: deepseek, anthropic, openai, google, meta, x-ai, qwen, medusa.
categorystringFilter by architecture: reasoning, coding, general, open-weights, native.
searchstringCase-insensitive keyword search across model ID, provider, and description.
Available Models(21 of 21)
Model IDProviderCategoryContextInference Cost / 1M Tokens
deepseek/deepseek-r1Reasoning
DeepSeekreasoning64k0.55 / 2.19 credits ($0.55 / $2.19)
Frontier open-weights reasoning model with explicit chain-of-thought verification.
deepseek/deepseek-chatPopular
DeepSeek (V3)general64k0.14 / 0.28 credits ($0.14 / $0.28)
DeepSeek-V3 671B MoE architecture with ultra-high throughput and strong coding prowess.
deepseek/deepseek-coderCode
DeepSeekcoding64k0.14 / 0.28 credits ($0.14 / $0.28)
Specialized code generation, refactoring, and security review with repository-wide context.
anthropic/claude-3.5-sonnetRecommended
Anthropiccoding200k3.00 / 15.00 credits ($3.00 / $15.00)
Industry benchmark for software architecture, agentic tool execution, and complex system design.
anthropic/claude-3.5-haikuFast
Anthropicgeneral200k0.80 / 4.00 credits ($0.80 / $4.00)
Ultra-fast, responsive model ideal for high-throughput streaming agents and lightweight tasks.
anthropic/claude-3-opus
Anthropicreasoning200k15.00 / 75.00 credits ($15.00 / $75.00)
Deep synthesis and top-tier reasoning for exhaustive research and complex multi-step workflows.
openai/gpt-4oMultimodal
OpenAIgeneral128k2.50 / 10.00 credits ($2.50 / $10.00)
Omni multimodal flagship foundation model with native text, vision, and real-time processing.
openai/gpt-4o-miniValue
OpenAIgeneral128k0.15 / 0.60 credits ($0.15 / $0.60)
Fast, cost-efficient model for lightweight automated tasks and high-frequency classification.
openai/o1Reasoning
OpenAIreasoning200k15.00 / 60.00 credits ($15.00 / $60.00)
Breakthrough reasoning model designed to think before answering complex scientific & logic queries.
openai/o3-miniNew
OpenAIreasoning200k1.10 / 4.40 credits ($1.10 / $4.40)
High-throughput, cost-efficient reasoning model tailored for coding, math, and STEM pipelines.
google/gemini-2.0-flash-exp1M Context
Googlegeneral1M0.10 / 0.40 credits ($0.10 / $0.40)
Next-gen multimodal architecture with sub-second time-to-first-token and 1M token context.
google/gemini-1.5-pro2M Context
Googlegeneral2M1.25 / 5.00 credits ($1.25 / $5.00)
Frontier 2-million-token context window capable of ingesting whole codebases, whitepapers, and audio.
google/gemini-1.5-flash
Googlegeneral1M0.075 / 0.30 credits ($0.08 / $0.30)
Fast, economical multimodal model built for high-volume analysis across massive documents.
x-ai/grok-2-1212
xAIgeneral128k2.00 / 10.00 credits ($2.00 / $10.00)
Frontier language model from xAI featuring high reasoning power and candid, unfiltered technical depth.
x-ai/grok-vision-betaVision
xAIgeneral128k2.00 / 10.00 credits ($2.00 / $10.00)
Vision-capable Grok engine for chart inspection, visual DeFi telemetry, and document OCR.
meta-llama/llama-3.3-70b-instructOpen Weights
Metaopen-weights128k0.35 / 0.40 credits ($0.35 / $0.40)
State-of-the-art open weights model matching prior 405B capabilities at a fraction of compute cost.
meta-llama/llama-3.1-405b-instruct405B Flagship
Metaopen-weights128k2.50 / 2.50 credits ($2.50 / $2.50)
Flagship 405B parameter frontier open-weights model for high-fidelity code generation and synthetic data.
meta-llama/llama-3.1-8b-instructUltra Low Cost
Metaopen-weights128k0.05 / 0.05 credits ($0.05 / $0.05)
Ultra-fast, lightweight open weights model ideal for high-throughput edge agent loops.
qwen/qwen-2.5-coder-32b-instructCode
Qwencoding128k0.20 / 0.20 credits ($0.20 / $0.20)
Premier open-weight code generation specialist, competitive with leading closed proprietary models.
mistralai/mistral-large-2407
Mistralopen-weights128k2.00 / 6.00 credits ($2.00 / $6.00)
Flagship European frontier model with top-tier reasoning, code generation, and 128k context.
medusa-coderNative Protocol
Medusa Enginenative32k0.02 credits flat ($0.02)
Native smart contract and DeFi router specialist trained on AMM liquidity algorithms and Solidity.
curl "http://localhost:3000/api/ai/v1/models?category=reasoning"
Response (200 OK)
{
  "object": "list",
  "total": 4,
  "data": [
    {
      "id": "deepseek/deepseek-r1",
      "object": "model",
      "provider": "DeepSeek",
      "context_window": 65536,
      "category": "reasoning",
      "pricing": {
        "prompt": "0.00000055",
        "completion": "0.00000219",
        "display": "0.55 / 2.19 credits ($0.55 / $2.19)"
      },
      "description": "Frontier open-weights reasoning model with explicit chain-of-thought verification."
    }
  ]
}
POST/api/ai/keys

Key management requires either an existing active API key belonging to the wallet or a valid one-time wallet challenge signature. A wallet address by itself never authorizes access.

Request Body Parameters
walletAddressstring (0x...)Optional with an API key; must match its owner
nonce + signaturestringRequired for wallet-signature auth
namestringOptional (Default: "Default Key")
Use a bearer API key or sign a fresh challenge from /api/ai/keys/wallet/challenge. Maximum 5 active keys per wallet; key secrets are returned once and stored as hashes.
cURL Example
curl -X POST http://localhost:3000/api/ai/keys \
  -H "Authorization: Bearer mdsa_live_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Autonomous Agent Key"
  }'
Response (200 OK)
{
  "success": true,
  "apiKey": {
    "id": "key-id",
    "name": "Autonomous Agent Key",
    "secret": "mdsa_live_<secret>",
    "keyPrefix": "mdsa_live_abcd...wxyz",
    "createdAt": 1710000000000
  },
  "message": "Save your API key securely. It will not be shown again."
}
POST/api/ai/keys/wallet

An agent requests a short-lived, one-time challenge, signs the server-generated message using EIP-191, then submits its nonce and signature. A wallet address alone cannot authenticate. Successful authentication issues or rotates the wallet's API key.

Request Body Parameters
walletAddressstring (0x...)Required
noncestring (64 hex chars)Required; returned by challenge endpoint
signaturestring (0x...)Required; signs the challenge message
agentNamestringOptional display name
The challenge expires after five minutes and can be used once. The returned apiKey remains active until revoked or rotated by a subsequent successful wallet authentication.
Autonomous TypeScript Client
import { ethers } from "ethers";

const wallet = new ethers.Wallet(
  process.env.AGENT_PRIVATE_KEY!
);
const baseUrl = "http://localhost:3000";
const challengeResponse = await fetch(
  baseUrl + "/api/ai/keys/wallet/challenge?address=" +
    encodeURIComponent(wallet.address)
);
if (!challengeResponse.ok) throw new Error("Could not request wallet challenge");
const { nonce, message } = await challengeResponse.json();
const signature = await wallet.signMessage(message);

const response = await fetch(baseUrl + "/api/ai/keys/wallet", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ walletAddress: wallet.address, nonce, signature }),
});
if (!response.ok) throw new Error("Wallet authentication failed");
const { apiKey } = await response.json();

Model Context Protocol (/api/mcp)

Medusa exposes a native, standard Model Context Protocol (MCP) server over HTTP and Server-Sent Events (SSE) at /api/mcp. AI agents in Claude Code, Cursor, and Claude Desktop can discover tools and execute on-chain swap quotes, price lookups, and bonding curve checks autonomously.

claude_desktop_config.json
{
  "mcpServers": {
    "medusa": {
      "url": "http://localhost:3000/api/mcp",
      "headers": {
        "Authorization": "Bearer mdsa_live_YOUR_KEY"
      }
    }
  }
}
.cursor/mcp.json
{
  "mcpServers": {
    "medusa": {
      "type": "sse",
      "url": "http://localhost:3000/api/mcp",
      "headers": {
        "Authorization": "Bearer mdsa_live_YOUR_KEY"
      }
    }
  }
}
Available MCP Tools Exposed at /api/mcp
Tool NameArgumentsDescription
get_swap_quotetokenIn, tokenOut, amountInCalculates optimal swap routes and price impact across Elysium DEX AMM pools.
get_token_priceaddressFetches real-time price, market cap, and 24h change across 14+ Elysium launchpads.
get_bonding_curveaddressInspects bonding curve graduation percentage and DEX AMM migration status.
generate_investment_thesisaddress, stance?Generates institutional quantitative bull/bear investment theses powered by DeepSeek R1.
check_compute_creditswalletAddressReturns available AI compute credits balance and tier multipliers.

Credit Metering & Economics

Medusa maintains a 1:1 parity with USD inference power: 1.0 AI Credit = $1.00 USD.

Credit Accrual (Trading)
50% Protocol Fee Rebate

0.20% swap fee → 50% returned to the trader as credits (0.10% net volume). Swapping $1,000 earns 1.00 credit (guaranteed minimum 0.05 credits per swap).

Credit Consumption (Deductions)
Inference & Fee Discounts

Deductions occur on-demand per request based on input/output tokens. Credits can also be burned on DEX swaps to receive a 25% protocol fee discount.

Error Codes & Status Handling

The API returns standard HTTP status codes. Errors include an error object containing a descriptive message and machine-readable code.

StatusTypeDescription & Action
401 Unauthorizedinvalid_api_keyThe key is missing, formatted incorrectly, or revoked. Check key on /credits.
402 Payment Requiredinsufficient_creditsWallet balance < 0.005 credits. Execute a swap on the DEX to accrue credits.
429 Too Many Requestsrate_limit_exceededWallet exceeded 60 requests per minute. Implement exponential backoff.
500 Internal Errorgateway_timeoutUpstream model timeout. The gateway retries automatically.