Jupiter defi

From elophanto/EloPhanto · View interactive version

Jupiter defi is an AI agent skill from the GitHub repository elophanto/EloPhanto. Comprehensive guidance for integrating Jupiter APIs (Ultra Swap, Lend, Perps, Trigger, Recurring, Tokens, Price, Portfolio, Prediction Markets, Send, Studio, Lock, Routing). Use for endpoint selection, integration flows, error handling, and production hardening.

How to use this skill

Skill file

Jupiter API Integration

Single skill for all Jupiter APIs, optimized for fast routing and deterministic execution.

Base URL: https://api.jup.ag

Auth: x-api-key from portal.jup.ag (required for Jupiter REST endpoints)

Use/Do Not Use

Use when:

Do not use when:

Triggers: swap, quote, gasless, best route, lend, borrow, earn, liquidation, perps, leverage, long, short, position, limit order, trigger, price condition, dca, recurring, scheduled swaps, token metadata, token search, verification, shield, price, valuation, price feed, portfolio, positions, holdings, prediction markets, market odds, event market, invite transfer, send, clawback, create token, studio, claim fee, vesting, distribution lock, unlock schedule, dex integration, rfq integration, routing engine

Developer Quickstart

import { Connection, Keypair, VersionedTransaction } from '@solana/web3.js';

const API_KEY = process.env.JUPITER_API_KEY!;  // from portal.jup.ag
if (!API_KEY) throw new Error('Missing JUPITER_API_KEY');
const BASE = 'https://api.jup.ag';
const headers = { 'x-api-key': API_KEY };

async function jupiterFetch<T>(path: string, init?: RequestInit): Promise<T> {
  const res = await fetch(`${BASE}${path}`, {
    ...init,
    headers: { ...headers, ...init?.headers },
  });
  if (res.status === 429) throw { code: 'RATE_LIMITED', retryAfter: 10 };
  if (!res.ok) {
    const raw = await res.text();
    let body: any = { message: raw || `HTTP_${res.status}` };
    try {
      body = raw ? JSON.parse(raw) : body;
    } catch {
      // keep text fallback body
    }
    throw { status: res.status, ...body };
  }
  return res.json();
}

// Sign and send any Jupiter transaction
async function signAndSend(
  txBase64: string,
  wallet: Keypair,
  connection: Connection,
  additionalSigners: Keypair[] = []
): Promise<string> {
  const tx = VersionedTransaction.deserialize(Buffer.from(txBase64, 'base64'));
  tx.sign([wallet, ...additionalSigners]);
  const sig = await connection.sendRawTransaction(tx.serialize(), {
    maxRetries: 0,
    skipPreflight: true,
  });
  return sig;
}

Intent Router (first step)

| User intent | API family | First action |

|---|---|---|

| Swap/quote | Ultra Swap | GET /ultra/v1/order -> sign -> POST /ultra/v1/execute |

| Lend/borrow/yield | Lend | POST /lend/v1/earn/deposit or /withdraw |

| Leverage/perps | Perps | On-chain via Anchor IDL (no REST API yet) |

| Limit orders | Trigger | POST /trigger/v1/createOrder -> sign -> POST /trigger/v1/execute |

| DCA/recurring buys | Recurring | POST /recurring/v1/createOrder -> sign -> POST /recurring/v1/execute |

| Token search/verification | Tokens | GET /tokens/v2/search?query={mint} |

| Price lookup | Price | GET /price/v3?ids={mints} |

| Portfolio/positions | Portfolio | GET /portfolio/v1/positions/{address} |

| Prediction market integration | Prediction Markets | GET /prediction/v1/events -> POST /prediction/v1/orders |

| Invite send/clawback | Send | POST /send/v1/craft-send -> sign -> send to RPC |

| Token creation/fees | Studio | POST /studio/v1/dbc-pool/create-tx -> upload -> submit |

| Vesting/distribution | Lock | On-chain program LocpQgucEQHbqNABEYvBvwoxCPsSbG91A1QaQhQQqjn |

| DEX/RFQ integration | Routing | Choose DEX (AMM trait) vs RFQ (webhook) path |

API Playbooks

Use each block as a minimal execution contract. Fetch the linked refs for full request/response shapes, TypeScript interfaces, and parameter details.

Ultra Swap


Lend


Perps


Trigger (Limit Orders)


Recurring (DCA)


Tokens


Price


Portfolio


Prediction Markets


Send


Studio


Lock


Routing


Rate Limits

Ultra Swap (dynamic, volume-based):

| 24h Execute Volume | Requests per 10s window |

|--------------------|-------------------------|

| $0 | 50 |

| $10,000 | 51 |

| $100,000 | 61 |

| $1,000,000 | 165 |

Quotas recalculate every 10 minutes. Pro plan does NOT increase Ultra limits.

Other APIs: Managed at portal level. Check portal rate limits.

On HTTP 429: Exponential backoff with jitter: delay = min(baseDelay * 2^attempt + random(0, jitter), maxDelay). Wait for 10s sliding window refresh. Do NOT burst aggressively.

Production Hardening

  1. Auth: Fail fast if x-api-key is missing or invalid.
  2. Timeouts: 5s for quotes, 30s for executions, plus total operation timeout.
  3. Retries: Only transient/network/rate-limit failures with exponential backoff + jitter.
  4. Idempotency: Ultra /execute accepts same signedTransaction + requestId for up to 2 min without duplicate execution.
  5. Validation: Validate mint addresses, amount precision, and wallet ownership before calls.
  6. Safety: Enforce slippage and max-amount guardrails from app config.
  7. Observability: Log requestId, API family, endpoint, latency, status, and error code.
  8. UX resilience: Return actionable states (retry, adjust params, insufficient balance, rate limited).
  9. Consistency: Reconcile async states (submitted vs confirmed vs failed) before final user success.
  10. Freshness: Re-fetch referenced docs when behavior differs from expected flow.

Integration Best Practices

  1. Start from the API-specific overview before coding endpoint calls.
  2. Enforce auth as a hard precondition for every request. Ref: Portal setup
  3. Design retry logic around documented rate-limit behavior, not fixed assumptions. Ref: Rate limits
  4. Map all non-success responses to typed app errors using documented response semantics. Ref: API responses
  5. For order-based products (Ultra/Trigger/Recurring), separate create/execute/retrieve phases in code and logs.
  6. Treat network/service health as part of runtime behavior (degrade gracefully). Ref: Status page

Cross-Cutting Error Pattern

interface JupiterResult<T> {
  ok: boolean;
  result?: T;
  error?: { code: string | number; message: string; retryable: boolean };
}

async function jupiterAction<T>(action: () => Promise<T>): Promise<JupiterResult<T>> {
  try {
    const result = await action();
    return { ok: true, result };
  } catch (error: any) {
    const code = error?.code ?? error?.status ?? 'UNKNOWN';

    // Rate limit — retry with backoff
    if (code === 429 || code === 'RATE_LIMITED') {
      return { ok: false, error: { code: 'RATE_LIMITED', message: 'Rate limited', retryable: true } };
    }

    // Ultra execute errors (negative codes)
    if (typeof code === 'number' && code < 0) {
      const retryable = [-1, -1000, -1001, -1005, -1006, -2000, -2003, -2005].includes(code);
      return { ok: false, error: { code, message: error?.error ?? 'Execute failed', retryable } };
    }

    // Program errors (positive codes like 6001 = slippage)
    if (typeof code === 'number' && code > 0) {
      return { ok: false, error: { code, message: error?.error ?? 'Program error', retryable: false } };
    }

    return { ok: false, error: { code, message: error?.message ?? 'UNKNOWN_ERROR', retryable: false } };
  }
}

Fresh Context Policy

Always fetch the freshest context from referenced docs/specs before executing a playbook.

  1. Resolve intent with Intent Router.
  2. Before coding, fetch the playbook's linked refs (overview + API-specific docs).
  3. If needed for validation or ambiguity, fetch the OpenAPI spec.
  4. Treat fetched docs as source of truth over cached memory.
  5. If fetched docs conflict with this file, follow fetched docs and note the mismatch.
  6. If docs cannot be fetched, state that context is stale/unverified and continue with best-known guidance.
  7. Keep auth invariant: x-api-key is required for Jupiter REST endpoints (not on-chain-only flows like Perps/Lock).

Verify

Operational References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.