本页由机器翻译。英文原文为权威版本。 阅读英文版
跳转到主要内容

TypeScript SDK

Use the official @hypercallxyz/sdk package to call the Hypercall REST API from TypeScript or modern JavaScript.

The SDK provides:

  • Typed clients for public, account, and signed exchange methods.
  • Runtime request validation before a request is sent.
  • EIP-712 helpers for constructing the exact message signed by a wallet.
  • Production defaults for https://api.hypercall.xyz and a 10-second request timeout.

The source is public at github.com/hypercall-public/hypercall-typescript-sdk.

Current scope

The TypeScript SDK covers REST reads, pre-signed REST writes, and signing helpers. Use the WebSocket API directly for streaming order, fill, portfolio, and market updates.

Install

npm install @hypercallxyz/sdk

The package is ESM and exports TypeScript declarations with every public entry point. Pin an exact version for production integrations that need controlled upgrades.

Read Market Data

InfoClient provides typed access to market data and account state. HttpTransport uses the production API by default.

import { HttpTransport, InfoClient } from "@hypercallxyz/sdk";

const info = new InfoClient({
transport: new HttpTransport(),
});

const markets = await info.markets({ include_instruments: false });
const currency = markets.data[0]?.underlying;

if (!currency) {
throw new Error("Hypercall returned no active markets");
}

const summaries = await info.optionSummaries({ currency });

console.log(summaries.result?.[0]?.instrument_name);
console.log(summaries.result?.[0]?.mark_price);

Common InfoClient methods include:

SurfaceMethods
Exchange metadataexchangeInfo, markets, instruments, optionSummaries, orderbook
Account stateportfolio, orders, orderStatus, fills, settlementPayouts, authorizedAgents
Activitytrade, trades, transfers, historicalPnl, historicalTheos
Risk and identityriskGrid, profile, profileTrades, referralBinding, referralCodeByOwner
RFQ and liquidationrfqStatus, liquidations, liquidationStatus, liquidationHistory

Request parameters come first. Pass an optional AbortSignal as the final argument.

const controller = new AbortController();

const portfolio = await info.portfolio(
{ wallet: "0xYourWalletAddress" },
controller.signal,
);

console.log(portfolio.data?.available_balance);

Configure Transport

Pass an explicit API URL when your application selects its environment through configuration.

const transport = new HttpTransport({
apiUrl: "https://api.hypercall.xyz",
timeout: 15_000,
fetchOptions: {
cache: "no-store",
},
});
  • apiUrl defaults to https://api.hypercall.xyz.
  • timeout defaults to 10,000 milliseconds. Set it to null only when the caller provides its own cancellation policy.
  • fetchOptions applies default fetch options to every request. The SDK owns the request method and body.

Sign and Submit a Write

ExchangeClient accepts pre-signed request payloads. The caller remains responsible for wallet connection, nonce selection, and signature creation.

The signing helper produces the EIP-712 domain, types, primary type, and message. Pass that typed data to the signing method provided by your wallet library.

import { ExchangeClient, HttpTransport, InfoClient } from "@hypercallxyz/sdk";
import {
buildPlaceOrderValue,
buildTypedData,
PLACE_ORDER_TYPES,
} from "@hypercallxyz/sdk/signing";

declare const nonceStore: {
next(signer: string, nowMs: number): Promise<number>;
};

declare const yourWallet: {
signTypedData(typedData: unknown): Promise<`0x${string}`>;
};

const wallet = "0xYourWalletAddress";
const transport = new HttpTransport();
const info = new InfoClient({ transport });
const exchange = new ExchangeClient({ transport });

const instruments = await info.instruments({ currency: "BTC" });
const instrument = instruments.result?.find(
({ is_active, orderbook }) => is_active && orderbook,
);

if (!instrument) {
throw new Error("Hypercall returned no active BTC orderbook instrument");
}

// Back this allocator with durable, per-signer state. It should atomically
// persist and return max(nowMs, previousNonce + 1).
const nonce = await nonceStore.next(wallet, Date.now());

const order = {
wallet,
symbol: instrument.instrument_name,
side: "Buy" as const,
size: "0.1",
price: "100",
tif: "gtc" as const,
route: "book_only" as const,
clientId: "quote-123",
nonce,
};

const typedData = buildTypedData({
chainId: 999,
primaryType: "PlaceOrder",
types: PLACE_ORDER_TYPES,
message: buildPlaceOrderValue(order),
});

// Replace this with the typed-data signing call from your wallet library.
const signature = await yourWallet.signTypedData(typedData);

const result = await exchange.placeOrder({
wallet: order.wallet,
symbol: order.symbol,
side: order.side,
size: order.size,
price: order.price,
tif: order.tif,
route: order.route,
client_id: order.clientId,
nonce: order.nonce,
signature,
});

console.log(result.status);
Signed values must match

The price, size, route, client ID, and nonce submitted to the API must exactly match the values in the signed message. Keep price and size as strings. A different string representation produces a different signature.

Nonce allocation: Hypercall accepts nonces within two days before and one day after the server timestamp. Use millisecond epoch time as the seed, atomically persist the last nonce per signer, and increment monotonically to prevent collisions across concurrent workers and process restarts.

Instrument selection: Resolve an active instrument from InfoClient immediately before constructing an order. Do not hard-code a dated option symbol into a long-lived integration.

Use the matching reduce-only type and builder for reduce-only requests:

  • Place: PLACE_ORDER_REDUCE_ONLY_TYPES with buildPlaceOrderReduceOnlyValue.
  • Replace: REPLACE_ORDER_REDUCE_ONLY_TYPES with buildReplaceOrderReduceOnlyValue.

See Authentication & Signing for the production signing domain, nonce rules, agent authorization, and all supported write messages.

Handle Errors

The root package exports the SDK error classes.

import {
HttpRequestError,
ValidationError,
} from "@hypercallxyz/sdk";

try {
await info.portfolio({ wallet: "invalid-wallet" });
} catch (error) {
if (error instanceof ValidationError) {
console.error("Invalid request:", error.message);
} else if (error instanceof HttpRequestError) {
console.error("HTTP request failed:", error.response?.status, error.message);
} else {
throw error;
}
}
  • ValidationError means the SDK rejected an invalid request before sending it.
  • HttpRequestError means the request failed, timed out, was aborted, returned a non-success status, or returned invalid JSON.
  • Trading results can still report a rejected status in a successful HTTP response. Inspect the method response instead of relying only on exceptions.

See API Errors for stable error handling guidance.

Import Surfaces

ImportUse
@hypercallxyz/sdkHttpTransport, InfoClient, ExchangeClient, error classes, and public types
@hypercallxyz/sdk/api/infoLow-level typed info methods and request schemas
@hypercallxyz/sdk/api/exchangeLow-level typed exchange methods and request schemas
@hypercallxyz/sdk/signingEIP-712 type maps, value builders, and typed-data helpers

For endpoint-level request and response details, use the REST API Reference. For release history and runnable examples, use the SDK changelog and examples/ directory.