@derivexyz/derive-ts

中文文档
3.0.36发布于 2026/10/20MITTypeScriptESM + CJS构建来源已验证近 30 天下载 5093

TypeScript SDK for the Derive v3 exchange API

原始使用文档
文档目录10 节
  1. Install
  2. Quickstart
  3. Authentication & session keys
  4. API surface
  5. Type-only usage (stubs)
  6. Subscriptions
  7. Value conventions (read this before signing)
  8. Examples
  9. Networks & signing params
  10. License

@derivexyz/derive-ts

npm version CI license

TypeScript SDK for the Derive v3 exchange API — a typed client for market data, orders, RFQs, transfers, withdrawals, deposits, vaults, session keys, and websocket subscriptions.

For more detailed docs see the Derive v3 API reference.

Install

npm install @derivexyz/derive-ts ethers ws

Quickstart

import { DeriveClient } from '@derivexyz/derive-ts';

const client = new DeriveClient({
  network: 'testnet', // 'mainnet' | 'testnet' | 'local'
  wallet: process.env.PRIVATE_KEY, // account owner key (or an ethers Wallet)
});

// Public data needs no auth:
const ticker = await client.marketData.getTicker('ETH-PERP');
console.log('ETH index price', ticker.I);

// Private calls sign automatically. Open the websocket and log in first:
await client.connect();
const subaccountIds = await client.login();

await client.orders.place({
  subaccountId: subaccountIds[0],
  instrumentName: 'ETH-PERP',
  direction: 'buy',
  amount: '0.1',
  limitPrice: '1000', // rests below market
});

await client.close();

Authentication & session keys

Login and per-request auth use an EIP-191 signature over a millisecond timestamp. Trading/transfer/withdrawal actions are separately EIP-712 signed. Both are handled for you — you only provide a signing key.

For bots and frontends, do not ship the account owner key. Register a scoped session key once (signed by the owner), then run with only that key:

import { DeriveClient, ProtocolScopeCode } from '@derivexyz/derive-ts';
import { Wallet } from 'ethers';

const sessionKey = Wallet.createRandom();
const owner = new DeriveClient({ network: 'testnet', wallet: process.env.PRIVATE_KEY });
await owner.connect();
await owner.login();
await owner.sessionKeys.set({
  publicSessionKey: sessionKey,
  expirySec: Math.floor(Date.now() / 1000) + 7 * 24 * 3600,
  protocolScopes: [ProtocolScopeCode.Trade], // least privilege — never Admin for a bot
  ipWhitelist: ['203.0.113.7'],
});

// Later, in the bot, with only the session key:
const bot = new DeriveClient({
  network: 'testnet',
  sessionKey: sessionKey.privateKey,
  ownerAddress: await (new Wallet(process.env.PRIVATE_KEY!)).getAddress(),
});

Session keys expire at their signed expirySec and cannot be revoked via the API — set a sensible expiry. sessionKeys.edit changes only off-chain attributes (label, IP allowlist).

API surface

DeriveClient exposes namespaced sub-APIs:

NamespaceWhat it does
client.marketDatainstruments, tickers, currencies (public, no auth)
client.subaccountsportfolio, positions, margin, trade history
client.ordersplace / cancel / query orders
client.rfqRFQ taker (request → quote → execute) and maker (quote) flows
client.spotTransferstransferInternal (own subaccounts), transferExternal (other wallets), updateWhitelistedRecipients
client.positionTransfersRFQ-backed transferPositions between subaccounts owned by the same wallet
client.withdrawalssigned L1 withdrawals
client.depositscontractCall.* (self-custody on-chain) and depositAddress.* (CEX-style)
client.vaultspublic reads + vaults.shareholder.* and vaults.curator.*
client.sessionKeyscreate / list / edit session keys
client.subscriptionswebsocket channels (callback or async-iterator)

Anything not wrapped is reachable, fully typed, via client.send(method, params).

Type-only usage (stubs)

If you only want the endpoint type stubs — the request/response shape of every public RPC method, with no runtime client — import them from the types/endpoints subpath. They're generated from the exchange's canonical API spec, so they stay in lockstep with the live surface; nothing here pulls in ethers, ws, or any runtime.

import type { EndpointMap, ParamsOf, ResultFor } from '@derivexyz/derive-ts/types/endpoints';

type PlaceParams = ParamsOf<'private/order'>;
type Ticker = ResultFor<'public/get_ticker'>;
// or reach into the map structurally:
type PlaceParamsStructural = EndpointMap['private/order']['request']['params'];

Useful for codegen, tooling, or typing a hand-rolled client. EndpointMap is keyed by method string; each entry is { request, response }, where response is the { result } | { error } JSON-RPC union — use ResultFor<M> to pull out the success payload.

Subscriptions

import { channel } from '@derivexyz/derive-ts';

await client.connect();
const book = channel('orderbook.{instrument_name}.{group}.{depth}', {
  instrument_name: 'ETH-PERP',
  group: '1',
  depth: '10',
});

const sub = await client.subscriptions.subscribe(book, (data) => console.log(data));
// ...later
await sub.unsubscribe();

// Or as an async iterator:
for await (const update of client.subscriptions.stream(channel('trades.{instrument_name}', { instrument_name: 'ETH-PERP' }))) {
  console.log(update);
}

Value conventions (read this before signing)

  • Prices, amounts, and fees are passed as decimal strings/numbers (e.g. '1500.5'). On the wire the SDK sends decimal strings; inside signed action data it scales them to 1e18. The protocol runs at 1e12 precision and rejects (does not truncate) values with more than 12 decimal places.
  • Withdrawal amounts are the one exception — they are in the ERC-20's native decimals (e.g. USDC has 6), because they are the L1 payout value.
  • Withdrawals always pay out to the signer. If a session key signs a withdrawal, funds go to the session key's address, not the owner's.
  • Deposits are two distinct flows, chosen explicitly:
    • deposits.depositAddress.register(...) returns a deterministic address; send funds to it from anywhere and the exchange sweeps and credits them.
    • deposits.contractCall.* builds the on-chain approve + ActionManager transaction from an ethers Signer you provide.

Examples

Runnable, heavily commented walkthroughs live in examples/:

DERIVE_NETWORK=testnet PRIVATE_KEY=0x... npx tsx examples/01-deposit.ts

Ordered by the v3 onboarding flow — your first deposit creates your account, then session keys, then the rest: 01-deposit, 02-session-keys, 03-market-data, 04-subscribe, 05-place-order, 06-rfq-taker, 07-rfq-maker, 08-transfers, 09-withdraw, 10-vaults, 11-position-transfers.

Networks & signing params

The EIP-712 domain separator is computed from the network's chain id and the protocol's constant Matching verifying contract; the action typehash is a protocol constant. You normally just pass network: 'mainnet' | 'testnet' | 'local'. To point at a custom deployment, pass a full NetworkConfig.

Security note: auth headers are named X-Derive* on the wire. Keep your private keys in a secret manager; the SDK never logs key material.

License

MIT — see LICENSE.

版本与发布记录

@derivexyz/derive-ts 共发布 20 个版本,首次发布于 2026/07/13;过去 12 个月发布了 20 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
3.0.36latest2026/10/2022 天前
3.0.352026/10/1825 天前
3.0.322026/10/111 个月前
3.0.312026/10/111 个月前
3.0.292026/10/021 个月前
3.0.252026/09/241 个月前

关于 @derivexyz/derive-ts 的常见问题

@derivexyz/derive-ts 是什么?

TypeScript SDK for the Derive v3 exchange API

如何安装 @derivexyz/derive-ts?

在项目目录运行 npm install @derivexyz/derive-ts,或使用 pnpm add / yarn add / bun add。

@derivexyz/derive-ts 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@derivexyz/derive-ts 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@derivexyz/derive-ts 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@derivexyz/derive-ts 可以商用吗?

@derivexyz/derive-ts 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@derivexyz/derive-ts 的下载量有多少?

根据 npm 官方下载统计,@derivexyz/derive-ts 在 2026/10/12 – 2026/11/10 这 30 天内被下载 5,093 次,日均约 170 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@derivexyz/derive-ts 还在维护吗?

最新版本 3.0.36 发布于 2026/10/20(22 天前);至今共发布 20 个版本,其中过去 12 个月发布了 20 个;首次发布于 2026/07/13。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。