For the complete documentation index, see llms.txt. This page is also available as Markdown.

Quick Start (5 minutes)

This guide gets you to a working Quote → Deposit → Order tracking loop using the public API and an EVM wallet.

You will:

  1. Request quotes

  2. Build a deposit plan (wallet actions)

  3. Execute wallet actions (approve + deposit)

  4. Submit the deposit transaction hash

  5. Track the resulting order

Prerequisites

  • An EVM wallet that supports EIP-1193 (e.g., injected window.ethereum)

  • Funds and gas on the source chain

  • A basic fetch-capable environment (browser or Node)

Code

/**
 * Khalani HyperStream Quick Start (single snippet)
 * Goal: Quote → Build deposit plan → Execute wallet actions → Submit deposit txHash → Track order
 *
 * Notes:
 * - This is written for a browser environment with an EIP-1193 wallet (e.g. window.ethereum / MetaMask).
 * - If you're running in Node, swap the EIP-1193 calls with your wallet client (viem/ethers/etc.).
 */

(async () => {
  // 0) Set your base URL
  const BASE_URL = "https://api.hyperstream.dev";

  // Small helper for consistent API error handling
  async function fetchJson<T>(url: string, init?: RequestInit): Promise<T> {
    const res = await fetch(url, init);
    if (!res.ok) {
      const text = await res.text().catch(() => "");
      throw new Error(`${res.status} ${res.statusText}: ${text || "Request failed"}`);
    }
    return (await res.json()) as T;
  }

  // 0.1) Connect wallet (EIP-1193)
  if (!window.ethereum) throw new Error("No EVM wallet found (window.ethereum missing).");

  // Request account access and use the connected address as fromAddress
  const accounts = (await window.ethereum.request({ method: "eth_requestAccounts" })) as string[];
  // Normalize to lowercase to avoid EIP-55 checksum validation issues
  const fromAddress = accounts?.[0]?.toLowerCase();
  if (!fromAddress) throw new Error("No wallet account available.");

  // 1) Request a quote
  //    (Adjust chain IDs / token addresses for your desired route; below is an example.)
  const quoteReq = {
    fromAddress,
    tradeType: "EXACT_INPUT",
    fromChainId: 1, // Ethereum
    fromToken: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // USDC (Ethereum)
    toChainId: 8453, // Base
    toToken: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // USDC (Base)
    amount: "1000000", // 1 USDC (6 decimals)
  };

  type QuoteResponse = {
    quoteId: string;
    routes: Array<{
      routeId: string;
      type: string;
      exactOutMethod?: string; // Only present for certain route types
      quote: {
        amountIn: string;
        amountOut: string;
        expectedDurationSeconds: number;
        validBefore: number;
      };
    }>;
  };

  const quotes = await fetchJson<QuoteResponse>(`${BASE_URL}/v1/quotes`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(quoteReq),
  });

  const route = quotes.routes?.[0];
  if (!quotes.quoteId) throw new Error("Missing quoteId in response.");
  if (!route?.routeId) throw new Error("No routes available for this request.");

  // Optional sanity: check quote expiry before proceeding
  if (typeof route.quote?.quoteExpiresAt === "number") {
    const nowUnix = Math.floor(Date.now() / 1000);
    if (nowUnix >= route.quote.quoteExpiresAt) throw new Error("Quote expired (quoteExpiresAt passed). Re-request a quote.");
  }

  console.log("quoteId:", quotes.quoteId);
  console.log("routeId:", route.routeId);
  console.log("amountOut:", route.quote.amountOut);
  console.log("validBefore (unix):", route.quote.validBefore);

  // 2) Build the deposit plan (wallet actions)
  //    For EVM, each approval is an EIP-1193 request with a required `request` field.
  //    (Solana uses `solana_sendTransaction` with a `transaction` field instead.)
  type DepositPlan = {
    kind: "CONTRACT_CALL";
    approvals?: Array<{
      type: "eip1193_request";
      request: { method: string; params?: unknown[] };
      deposit?: boolean;      // True for the main deposit transaction
      waitForReceipt?: boolean;
    }>;
  };

  const depositPlan = await fetchJson<DepositPlan>(`${BASE_URL}/v1/deposit/build`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      from: fromAddress,
      quoteId: quotes.quoteId,
      routeId: route.routeId,
    }),
  });

  // 3) Execute wallet actions (EVM / EIP-1193)
  //    Execute approvals[] in order. One action will be marked deposit: true.
  let depositTxHash: string | null = null;

  const actions = depositPlan.approvals ?? [];
  if (!actions.length) throw new Error("Deposit plan contained no actions (approvals[] empty).");

  for (const action of actions) {
    const req = action.request;
    if (!req?.method) throw new Error("Malformed deposit plan action: missing request.method");

    // Many wallets support calling these requests directly via EIP-1193.
    // - wallet_switchEthereumChain => returns null
    // - eth_sendTransaction       => returns txHash (string)
    const result = await window.ethereum.request(req);

    // Capture the deposit tx hash (the action flagged as deposit=true).
    if (action.deposit) {
      if (typeof result !== "string" || !result.startsWith("0x")) {
        throw new Error("Deposit action did not return a tx hash.");
      }
      depositTxHash = result;
    }
  }

  if (!depositTxHash) throw new Error("No deposit transaction hash produced (no action had deposit=true).");

  console.log("depositTxHash:", depositTxHash);

  // 4) Submit the deposit transaction hash (create an order)
  type SubmitResponse = { orderId: string };

  const submit = await fetchJson<SubmitResponse>(`${BASE_URL}/v1/deposit/submit`, {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      txHash: depositTxHash,
      quoteId: quotes.quoteId,
      routeId: route.routeId,
    }),
  });

  if (!submit.orderId) throw new Error("Missing orderId in submit response.");
  const orderId = submit.orderId;

  console.log("orderId:", orderId);

  // 5) Track the order
  type OrderStatus = "created" | "deposited" | "published" | "filled" | "refund_pending" | "refunded" | "failed";

  type Order = {
    id: string;
    status: OrderStatus;
    fromChainId: number;
    toChainId: number;
    fromToken: string;
    toToken: string;
    srcAmount: string;
    destAmount: string;
    depositTxHash: string | null;
    createdAt: string;
    updatedAt: string;
    // Additional fields available: quoteId, routeId, type, author, tradeType,
    // transactions, timestamps, providerStatus, fromTokenMeta, toTokenMeta, etc.
  };

  type OrdersResponse = {
    data: Order[];
    cursor?: number;
  };

  async function fetchOrder(): Promise<Order | undefined> {
    const res = await fetchJson<OrdersResponse>(
      `${BASE_URL}/v1/orders/${fromAddress}?orderIds=${encodeURIComponent(orderId)}`
    );
    return res.data?.[0];
  }

  // Single fetch (minimum viable "tracking")
  const firstOrder = await fetchOrder();
  console.log("status:", firstOrder?.status);
  console.log("updatedAt:", firstOrder?.updatedAt);

  // Optional: simple polling loop for a basic "tracking timeline"
  // Terminal statuses per the API spec (lowercase)
  const TERMINAL: Set<OrderStatus> = new Set(["filled", "refunded", "failed"]);
  const POLL_INTERVAL_MS = 5_000;
  const MAX_POLLS = 24; // ~2 minutes

  let lastStatus: OrderStatus | undefined = firstOrder?.status;

  for (let i = 0; i < MAX_POLLS; i++) {
    const o = await fetchOrder();
    const s = o?.status;

    if (s && s !== lastStatus) {
      console.log(`[poll] status changed: ${lastStatus ?? "(none)"} → ${s}`);
      lastStatus = s;
    }

    if (s && TERMINAL.has(s)) break;
    await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
  }

  console.log("Done. You just completed a Quote → Deposit → Order tracking loop.");
})().catch((err) => {
  console.error("Quick Start failed:", err);
});

That's it! You just published a cross-chain intent and can track its status until filled.

What to build next

  • Add route selection logic (best price vs speed vs route type)

  • Add quote expiration handling (refresh on expiry)

  • Add robust order polling / UI timeline

  • Implement exception handling

Last updated