TypeScript SDK
Install the grvt package, create a client, call any RPC, stream data, place signed orders and handle errors, in Node and the browser.
On this page
Help me with: TypeScript SDK. Install the grvt package, create a client, call any RPC, stream data, place signed orders and handle errors, in Node and the browser.
Target environment: {environment} (chain ID {chainId}). Recorded signing cases keep their original environment.
{executionGuidance}
Read this first: {origin}/bundle/sdks/typescript.md (~29 KB, plain Markdown: this page plus the AGENTS.md rules, Environments).
Fetch other pages from the index at {origin}/llms.txt only as you need them. {origin}/downloads/contract.json is a machine-readable contract for tools, not for reading.
Rules: follow AGENTS.md; do not send requests without the user asking you to; read credentials from environment variables; never retry writes automatically; show me the code and how to run it. Preview. Any 0.x release can change the API. Install says what to pin.
The TypeScript SDK has a method for every call and stream in the API reference. It signs every call that needs a signature (filling in the nonce, expiration and client order ID) and re-syncs streams after a gap (when frames were missed, it subscribes again to get current data). It runs on Node.js 24+ and in modern browsers.
New here? Install the SDK and run the Quickstart, then read this page down to Track and cancel an order. Later sections are for when you need them.
Install
Not on the npm registry yet. Install it from its public GitHub repository; npm builds it during the install. It needs Node.js 24 or newer.
npm install github:gravity-technologies/grvt-sdk-typescript
Then import it as grvt. The repository has no version tags yet and its main branch moves, so pin the commit
you tested: npm install github:gravity-technologies/grvt-sdk-typescript#<commit> (your package-lock.json
also records the exact commit).
With other package managers, pin the commit too:
-
yarn 1 installs and builds it.
-
pnpm (tested with pnpm 12) stops with
ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED, because the package builds itself on install. Allow that build in your project'spnpm-workspace.yaml, keyed by the package's exact Git address and commit; a wildcard such asgrvt@*is not accepted:allowBuilds: "grvt@<git URL>#<commit>": true -
bun hasn't been tested.
Create a client
import { Grvt, PrivateKeySigner } from "grvt";
// The API key logs in; the signer signs orders with your signing key. Leave both out for public data only.
const client = new Grvt({
env: "testnet",
apiKey: process.env.GRVT_API_KEY,
signer: new PrivateKeySigner(process.env.GRVT_PRIVATE_KEY!),
});
const t = await client.ticker({ instrument: "BTC_USDT_Perp" });
console.log(t.result.mark_price); // the exchange's fair price, used for margin
await client.close();
envis"testnet", or"prod"for production (Environments).- The client sends short (lite) field names on the wire by default; your code still uses the full names.
encoding: "full"switches to full names (Encoding). - The client logs in on the first private call and renews the session before it expires (Authentication). Renewal reconnects the client's WebSockets, so every stream gets a gap (Session renewal).
- To stop, follow Shut down cleanly.
Watch out: in the browser, only public calls and streams work. Anything that needs a session (private calls and streams, orders) is Node-only for now: browsers don't let code read the login cookie or send it on a WebSocket.
Call an RPC
Every call is a method on the client, client.<method>(request). Method names are the reference page's
name in camelCase, with no exceptions: create_order is client.createOrder, trade_stream is
client.tradeStream. Request and response fields stay snake_case, exactly as on the reference pages (for
example mark_price), because they are the JSON sent and received.
const inst = await client.getInstrument({ instrument: "BTC_USDT_Perp" });
console.log(inst.result.tick_size, inst.result.min_size);
- Reads are tried up to 3 times; writes are sent once (What the SDK retries).
- Timeouts, as client options in milliseconds:
callTimeoutMs(30000),httpAttemptTimeoutMs(10000),wsRequestTimeoutMs(5000),resyncTimeoutMs(5000),idleTimeoutMs(30000).callTimeoutMscovers the whole call: login, instrument lookup, signing, retries and the reply.httpAttemptTimeoutMscaps each HTTP attempt within what is left of it. For one call, pass{ timeoutMs }as the second argument; an earlier abortsignalthere still wins.
Pagination
History calls return one page and a next cursor. pages follows the cursors, fetching the next page only
when your loop asks for it. Put the filters and call options in the callback.
import { pages } from "grvt";
for await (const page of pages((cursor) => client.tradeHistory({ instrument: "BTC_USDT_Perp", cursor }))) {
for (const trade of page.result ?? []) console.log(trade);
}
- An empty page can still have a next cursor. Breaking out of the loop stops further calls.
- A repeated cursor throws
PaginationCycle. Fetch errors pass through, with no extra retries. - Cursors are not a stable snapshot: records can change while you page.
Default sub-account
Pass subAccountId: "123" to new Grvt to fill in sub_account_id wherever a request or stream leaves it out.
- An ID you pass explicitly wins.
- An order in
bulkOrderstakes the request's account first, then the client default. - Transfer source and destination IDs are never filled in.
- The default is applied to a copy, before signing.
- Without a default, calls that need an account still require one.
Stream data
Every stream method ends in Stream, for example client.tradeStream.
- Call the stream method to get a subscription.
- Read frames with
for await. - Break out of the loop or call
close()to unsubscribe.
// rate: update interval in ms
for await (const frame of client.orderbookDeltaStream({ instrument: "BTC_USDT_Perp", rate: 500 })) {
console.log(frame.sequence_number, frame.feed);
}
frame.sequence_number is a string, as on the wire, and so are a gap event's bounds. Compare them as
BigInt(...), not as strings.
Watch out:
- After a gap, older frames can still come first and missed private events aren't replayed (What happens after a gap).
- Each subscription queues up to 4096 frames (client option
queueSize, at least 1). If your code falls behind,.sstreams (every frame complete) drop their oldest frame and others throwStreamOverflowout of yourfor await: catch it and loop again (stream errors).
Place an order
- Build a
models.OrderInputwithDecimalprice and size.is_buying_assetis true to buy, false to sell.GOOD_TILL_TIME(GTT) rests until filled, cancelled or expired;post_onlyrejects the order rather than let it trade at once (TimeInForce). - Call
createOrder. The SDK fills in the signature and aclient_order_id, and looks up the instrument details it needs to sign. It works on a copy, so yourorderobject is not changed. - Save the
client_order_id: you follow the order by it, because the reply'sorder_idis always zero. The SDK fills it in, so read it from the reply. If the reply is lost, the outcome-unknown error carries it. To know it before sending, set your own (below).
import { Decimal, Grvt, PrivateKeySigner, type models } from "grvt";
const client = new Grvt({
env: "testnet",
apiKey: process.env.GRVT_API_KEY,
signer: new PrivateKeySigner(process.env.GRVT_PRIVATE_KEY!),
});
const order: models.OrderInput = {
sub_account_id: process.env.GRVT_SUB_ACCOUNT_ID!,
time_in_force: "GOOD_TILL_TIME",
post_only: true,
legs: [{ instrument: "BTC_USDT_Perp", size: new Decimal("0.01"), limit_price: new Decimal("60000"), is_buying_asset: true }],
};
const resp = await client.createOrder({ order });
console.log(resp.result.metadata.client_order_id);
await client.close();
To choose the client_order_id yourself, set it before you send the order, following the
client order ID rules:
order.metadata = { client_order_id: (2n ** 63n | crypto.getRandomValues(new BigUint64Array(1))[0]!).toString() };
Orders go over HTTP by default. Pass orderTransport: "ws" to the client to send them over the trading
WebSocket instead.
Watch out:
- A reply means the exchange received the order, not that it rests on the book (What a create reply means).
- An order still open 24 hours after signing expires (Expiration).
- Sending the same
orderagain places a second order, with a newclient_order_idunless you set one. - An order that breaks its instrument's limits throws
OrderOutOfBoundsand is not sent (Orders checked before sending). If the exchange still rejects an order for these limits, the SDK drops its cached instrument details and fetches them again for the next order.checkOrders: falseon the client turns the check off.
Sign with a wallet or KMS
PrivateKeySigner keeps the key in your process. To sign elsewhere (a wallet, or a key management service
(KMS) such as AWS KMS), pass your own Signer: an object with address (lowercase 0x address) and
signTyped(domain, type, message). Inside it, type.toTypedData(domain, message) gives the JSON to hand to
eth_signTypedData_v4. Return { signer, r, s, v }.
The SDK checks every signature it gets back and throws SigningError unless:
randsare 32 bytes of0xhex andvis 27 or 28;sis low-s (Signing). Some KMS backends return a high s: replace it with n - s and flipv;- it recovers to
signer.address, and itssignerfield is empty or equal to it.
Track and cancel an order
Private streams need a client with an API key. orderStream sends every change to your orders, rejections
included; fillStream sends each fill, with its trade ID and client order ID.
- Open
orderStreamandawaititssubscribe()before you place the order. - Match updates by
metadata.client_order_id. The updates also carry theorder_id. - Stop at a final status:
"FILLED","REJECTED"or"CANCELLED"(order states). - To cancel, call
cancelOrderwithsub_account_idandclient_order_id(ororder_id), after the create has replied.
const sub = process.env.GRVT_SUB_ACCOUNT_ID!;
const orders = await client.orderStream({ sub_account_id: sub }).subscribe();
const resp = await client.createOrder({ order });
const id = resp.result.metadata.client_order_id;
await client.cancelOrder({ sub_account_id: sub, client_order_id: id });
for await (const { feed } of orders) {
const status = feed.state?.status;
if (feed.metadata.client_order_id !== id) continue;
if (status === "FILLED" || status === "REJECTED" || status === "CANCELLED") {
console.log(feed.order_id, status, feed.state?.reject_reason);
break; // leaving the loop unsubscribes
}
}
Recover a lost order response
When: a write times out or the socket drops before the response arrives. The call throws
OrderStateUnknown. Look the order up with resolveOrder; don't resend it. Steps and code:
When a write's outcome is unknown.
Recovery helpers
These are imports from grvt, not client methods.
import { OrderBook, backfillPages, refreshCancelCountdown, resolveOrder } from "grvt";
| Helper | What it does |
|---|---|
resolveOrder( | Looks up an order whose write outcome is unknown. It never resends. |
new OrderBook( | Keeps a local book from order-book stream frames. |
backfillPages( | Pages through REST history after a gap. Your callback picks the call and time window. |
refreshCancelCountdown( | Arms or refreshes the cancel-on-disconnect countdown once (1 to 300 seconds). The SDK never does this for you. |
Your onEvent hook gets the gap and session_rotated events they use. How to use them:
SDK helpers.
Errors
| Class | When |
|---|---|
ApiError | the server answered with an error code; has code, serverMessage (message is the full text), status, rpc, retryable |
RateLimitError | code 1006 (HTTP 429); a subclass of ApiError; reads were already retried |
TransportError | no usable answer (connection failed, read timed out, socket closed); has rpc, and sent (whether the request may have left). A write that may have left throws OrderStateUnknown instead |
OrderStateUnknown | a write may or may not have happened; look it up by clientOrderId (clientOrderIds for a bulk call). The original failure is its cause |
OrderOutOfBounds | an order breaks its instrument's limits; nothing was sent; has nearest and serverCode |
StreamOverflow | your code fell behind a stream that may not drop frames; the frames in between are lost and the stream re-synced |
SigningError, DecodeError, ConfigError, FrameTooLarge, ClosedError | local problems: bad key or value, unexpected response or frame, bad setup, oversized frame, client closed |
All of them extend GrvtError. Error code constants are in ErrorCode. The full list is on
Error codes.
Hooks and logging
GRVT_LOG=debuglogs every request and frame to stderr, with keys and signatures redacted.setLogLevel()changes the level at runtime.beforeSendruns before each RPC is signed and may changecall.params(or return new params). It sees the wire names: bulk order fieldsorder_idsandclient_order_idsappear asorder_i_dsandclient_order_i_ds. It must not add, remove or reorder orders, or change their client order IDs, since those are how you look up an unknown outcome: that fails with a config error before anything is sent.onEventgets typed events:connect,disconnect,reconnect,subscribe,gap,retry,frame,session_rotatedanderror. Keep it fast.
const client = new Grvt({
env: "testnet",
onEvent: (e) => { if (e.type === "gap") console.warn("re-syncing", e.stream, e.selector); },
});
Data types
- Decimals use the SDK's
Decimalwrapper. It checks for exact text and needs no arithmetic library. A value with more decimal places than the field allows throwsSigningError; nothing is rounded. - Nanosecond timestamps use
Timestampoverbigint.toDate()drops sub-millisecond precision. - IDs are strings.
- Optional fields can be missing (
undefined). Some list fields can benullinstead of empty: check before you iterate. - Signed requests use
Inputmodels, so the SDK can fill in signatures and metadata. - Ticker and mini-ticker delta streams yield
Partialmodels: every feed field is optional. - Enum types accept any string. A value added by a newer server arrives as its plain string, so give your
switchadefaultbranch. - Millisecond schedule fields stay plain integers.
Not supported yet
- Resuming a private stream from a sequence number. After a gap, fill missed events from history with
backfillPages(Fill missed events from history). - Private calls, private streams and orders in the browser. Meanwhile, make them from a Node server and use the browser for public data (Create a client).
- Logging in with a wallet. The client logs in with an API key only.
- A client heartbeat. The global
WebSockethas no ping API. On Node 24 and later the SDK still sees the server's pings, so a connection silent foridleTimeoutMsis dropped and reconnected. In browsers it can't tell a quiet connection from a dead one, so a dead one is noticed only when TCP gives up. A customwebSocketfactory that sees ping frames can call the socket'sonheartbeatto turn the check on. - Telling a rejected WebSocket handshake from a network error. The global
WebSockethides the HTTP status, so a 401 or 403 is retried with backoff. A customwebSocketfactory that knows the status can setstatuson the close event to stop for good.