이 페이지는 자동 번역되었습니다. 영어 원문이 정본입니다. 영어로 읽기 →
메인 콘텐츠로 건너뛰기

TypeScript SDK

공식 @hypercallxyz/sdk 패키지를 사용하면 TypeScript 또는 최신 JavaScript에서 Hypercall REST API를 호출할 수 있습니다.

SDK는 다음을 제공합니다.

  • 퍼블릭, 계정, 서명된 거래소 메서드를 위한 타입 지정 클라이언트.
  • 요청 전송 전에 수행되는 런타임 요청 검증.
  • 지갑이 서명하는 메시지를 정확히 구성하기 위한 EIP-712 헬퍼.
  • https://api.hypercall.xyz 및 10초 요청 타임아웃을 사용하는 프로덕션 기본값.

소스 코드는 github.com/hypercall-public/hypercall-typescript-sdk에 공개되어 있습니다.

현재 지원 범위

TypeScript SDK는 REST 조회, 사전 서명된 REST 쓰기 요청, 서명 헬퍼를 지원합니다. 주문, 체결, 포트폴리오, 마켓 업데이트 스트리밍에는 WebSocket API를 직접 사용하십시오.

ExchangeClient는 POST /bulk_order, PUT /bulk_order, MMP 설정, 퍼프 주문을 래핑하지 않습니다. 이러한 요청은 문서화된 구조체로 서명한 뒤 엔드포인트를 직접 호출하십시오.

설치​

npm install @hypercallxyz/sdk

이 패키지는 ESM이며 모든 퍼블릭 엔트리 포인트에 TypeScript 선언을 함께 내보냅니다. 업그레이드를 통제해야 하는 프로덕션 연동에서는 정확한 버전을 고정하십시오.

마켓 데이터 조회​

InfoClient는 마켓 데이터와 계정 상태에 대한 타입 지정 접근을 제공합니다. HttpTransport는 기본적으로 프로덕션 API를 사용합니다.

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);

주요 InfoClient 메서드는 다음과 같습니다.

영역메서드
거래소 메타데이터exchangeInfo, markets, instruments, optionSummaries, orderbook
계정 상태portfolio, orders, orderStatus, fills, settlementPayouts, authorizedAgents
활동 내역trade, trades, transfers, historicalPnl, historicalTheos
리스크 및 신원riskGrid, profile, profileTrades, referralBinding, referralCodeByOwner
RFQ 및 청산rfqStatus, liquidations, liquidationStatus, liquidationHistory

요청 파라미터가 첫 번째 인자입니다. 선택적인 AbortSignal은 마지막 인자로 전달합니다.

const controller = new AbortController();

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

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

Transport 설정​

애플리케이션이 설정을 통해 환경을 선택하는 경우 API URL을 명시적으로 전달하십시오.

const transport = new HttpTransport({
apiUrl: "https://api.hypercall.xyz",
timeout: 15_000,
fetchOptions: {
cache: "no-store",
},
});
  • **apiUrl**의 기본값은 https://api.hypercall.xyz입니다.
  • **timeout**의 기본값은 10,000밀리초입니다. 호출자가 자체 취소 정책을 제공하는 경우에만 null로 설정하십시오.
  • **fetchOptions**는 모든 요청에 기본 fetch 옵션을 적용합니다. 요청 메서드와 본문은 SDK가 관리합니다.

쓰기 요청 서명 및 제출​

ExchangeClient는 사전 서명된 요청 페이로드를 받습니다. 지갑 연결, 논스 선택, 서명 생성은 호출자가 책임집니다.

서명 헬퍼는 EIP-712 도메인, 타입, 기본 타입(primary type), 메시지를 생성합니다. 이 typed data를 사용 중인 지갑 라이브러리의 서명 메서드에 전달하십시오.

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);
서명된 값이 일치해야 합니다

API에 제출하는 wallet, symbol, side, size, price, tif, route, client_id, nonce는 서명된 PlaceOrder의 대응 필드와 정확히 일치해야 합니다. price와 size는 문자열로 유지하십시오. 문자열 표현이 다르면 서명도 달라집니다.

논스 할당: Hypercall은 서버 타임스탬프 기준 2일 전부터 1일 후까지의 논스를 허용합니다. 밀리초 단위 에포크 시간을 시드로 사용하고, 서명자별 마지막 논스를 원자적으로 저장하며, 단조 증가시켜 동시 실행 워커 간 및 프로세스 재시작 시의 충돌을 방지하십시오.

라우트: SDK의 route 타입에는 rfq_only가 포함되어 있지만, 현재 API는 모든 주문 엔드포인트에서 이를 거부합니다. book_only 또는 best_execution을 사용하십시오.

상품 선택: 주문을 구성하기 직전에 InfoClient에서 활성 상품을 조회하십시오. 장기간 운영되는 연동에 만기일이 포함된 옵션 심볼을 하드코딩하지 마십시오.

reduce-only 요청에는 그에 맞는 reduce-only 타입과 빌더를 사용하십시오.

  • 주문 제출: PLACE_ORDER_REDUCE_ONLY_TYPES와 buildPlaceOrderReduceOnlyValue.
  • 주문 정정: REPLACE_ORDER_REDUCE_ONLY_TYPES와 buildReplaceOrderReduceOnlyValue.

프로덕션 서명 도메인, 논스 규칙, 에이전트 승인, 지원되는 모든 쓰기 메시지는 인증 및 서명을 참고하십시오.

오류 처리​

루트 패키지는 SDK 오류 클래스를 내보냅니다.

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**는 SDK가 잘못된 요청을 전송 전에 거부했음을 의미합니다.
  • **HttpRequestError**는 요청이 실패했거나, 타임아웃되었거나, 중단되었거나, 성공이 아닌 상태 코드를 반환했거나, 잘못된 JSON을 반환했음을 의미합니다.
  • 거래 결과는 HTTP 응답이 성공이더라도 거부 상태를 보고할 수 있습니다. 예외에만 의존하지 말고 메서드 응답을 확인하십시오.

안정적인 오류 처리 가이드는 API 오류를 참고하십시오.

Import 경로​

Import용도
@hypercallxyz/sdkHttpTransport, InfoClient, ExchangeClient, 오류 클래스, 퍼블릭 타입
@hypercallxyz/sdk/api/info저수준 타입 지정 info 메서드 및 요청 스키마
@hypercallxyz/sdk/api/exchange저수준 타입 지정 exchange 메서드 및 요청 스키마
@hypercallxyz/sdk/signingEIP-712 타입 맵, 값 빌더, typed-data 헬퍼

엔드포인트별 요청 및 응답 세부 사항은 REST API 레퍼런스를 참고하십시오. 릴리스 이력과 실행 가능한 예제는 SDK 변경 로그와 examples/ 디렉터리를 참고하십시오.