# Integrating with Grvt: notes for coding agents

Read this before writing code against the Grvt API. It lists the rules that, when missed, produce code that
looks right and fails.

## Where the truth is

- Look calls up in [llms.txt](llms.txt) (one line per RPC and stream) or
  [reference/index.md](reference/index.md). Each reference page has the exact request/response fields and one
  working example. Fetch single pages as you need them.
- For a whole area, load one file. They are large, so pick the one you need:
  [llms-full-trading.txt](llms-full-trading.txt) (~420 KB),
  [llms-full-account.txt](llms-full-account.txt) (~260 KB),
  [llms-full-market-data.txt](llms-full-market-data.txt) (~250 KB) or
  [llms-full-signing.txt](llms-full-signing.txt) (~65 KB).
- Machine-readable, for tools rather than reading: [contract.json](downloads/contract.json) (~900 KB, everything),
  [signing.json](downloads/signing.json) (~130 KB, signing test cases),
  [openapi.yaml](downloads/openapi.yaml), [asyncapi.yaml](downloads/asyncapi.yaml).
- Do not trust field names from memory or from older Grvt SDKs. Use the names on the reference page, exactly.

## Use an SDK when you can

There are SDKs for Python, TypeScript, Go and Rust with the same calls; the example is Python.

```python
from grvt import Grvt, PrivateKeySigner
from grvt import models as m

client = Grvt(
    env="testnet",
    api_key=...,
    signer=PrivateKeySigner(...),
)
# client.<method>(**fields)
resp = client.create_order(
    order=m.OrderInput(...),
)
```

- Every call is a method directly on the client, `client.<method_name>` (`client.create_order`); calls are not
  grouped by namespace. Every stream method ends in `_stream` (`client.trade_stream`).
- Request fields are keyword arguments; nested objects are `grvt.models` classes. Responses are models with the
  wire field names (most results are under `.result`). Async code uses `AsyncGrvt` the same way.
- Start on **testnet** (`env="testnet"`). Keys and accounts differ per environment. Mint test funds at
  [testnet.grvt.io/exchange/deposit](https://testnet.grvt.io/exchange/deposit) ("Mint testnet tokens", then
  "Move" them to the trading sub-account); without them orders fail with `2080 InsufficientMargin`.

## Rules

1. **Credentials from the environment**, never in code: `GRVT_API_KEY`, `GRVT_PRIVATE_KEY`,
   `GRVT_SUB_ACCOUNT_ID`.
2. **Use exact SDK types.** Python uses `decimal.Decimal`, Rust uses `rust_decimal`, and Go and TypeScript
   use the SDK decimal wrapper. Nanosecond timestamps use `time.Time` in Go and the SDK timestamp type elsewhere.
   JSON still carries decimals and 64-bit IDs as strings. Never pass floats for prices or sizes.
3. **Do not fill server fields.** Fields described as "Set by the server." (`order_id`, `create_time`,
   `state`) are left out of requests.
4. **Let the SDK sign.** Do not build `signature` by hand when using the SDK. If you must sign yourself, follow
   [guides/signing.md](guides/signing.md) and make your code reproduce a signing case from
   [signing.json](downloads/signing.json) before sending anything.
5. **Precision is exact.** Reject values that cannot be represented exactly at the required scale. Never round.
   Trailing zeros do not add precision: at nine decimal places, `1.0000000000` is exact but `1.0000000001` is not.
6. **Know what the SDK retries.** It tries a read up to 3 times in all (backoff with jitter, within the
   30 s call timeout). It sends a write (orders, cancels, transfers, withdrawals, settings) exactly once. A
   write that may have reached the exchange (a timeout or dropped connection after sending, a 5xx, `1002`,
   `1005`) raises `OrderStateUnknown`; a `TransportError` on a write means it was never sent.
7. **Never resend an uncertain write.** On `OrderStateUnknown`, find out what happened first:
   - Orders: `resolve_order` or `client.get_order` by the error's `client_order_id`. Found means it
     happened, in the state shown; do not resend. Not found stays unknown, because reads can lag behind
     an accepted write.
   - Transfers and withdrawals: `client.transfer_history` / `withdrawal_history`, matching the signature
     (`signer`, `nonce`, `expiration`) and the currency and amount. An absent record does not prove
     failure. An exact repeat of a signed transfer fails with `4007`.
   - Bound the lookup attempts. If the outcome stays unknown, save the identifiers for investigation.
8. **Client order IDs:** any non-zero uint64 that none of the sub-account's open orders uses (`2012`
   otherwise; repeating the last one gives `2013`). An ID is accepted again once its order closes, so use a
   new one for every order. An exact resend of a signed order can rest on the book, but all copies together
   never fill more than the signed size; an order signed again (new nonce) is a new order and can fill again.
   The Grvt web app uses IDs below 2^63, and the SDKs generate IDs from 2^63 up; pick yours from 2^63 up
   too if you set them yourself and the web app trades the same sub-account.
   The create reply has no `order_id` yet: follow the order by `client_order_id`.
9. **Signature expiration is the order's lifetime.** An order still open when `signature.expiration`
   passes is cancelled (`EXPIRED`). The SDKs sign with now + 24 hours; set it yourself (at most 30 days;
   take-profit and stop-loss orders may be accepted up to 180 days) for orders that should rest longer.
10. **Use streams, not polling**, for prices and order updates. Open the order stream before placing orders.
11. **Check sequence numbers.** Subscribe with `use_global_sequence_number: true` and compare numbers as
    integers. On `.s` and `.d` streams the first frame is a snapshot with `sequence_number` `"0"`; event
    streams (fills, orders, positions, transfers) have no snapshot. The first update's
    `prev_sequence_number` is at or below the subscribe reply's `latest_sequence_number`; after that each
    one equals the last `sequence_number`. On a gap: `.s` streams need nothing; `.d` streams re-subscribe
    and replace state with the new snapshot; event streams re-subscribe and refetch what they missed over
    HTTP (`open_orders`, `positions`, `fill_history`). Same after a reconnect.
12. **Sessions:** the SDK logs in with the API key and logs in again before the session cookie expires.
    Open sockets keep the old session (there is no re-login inside a socket), so the SDK sends a
    `session_rotated` event, then reconnects and re-subscribes every socket. Handle it like any other gap.
13. **Rate limits:** on `RateLimitError` (code 1006) back off. Numbers are not published; read the
    `X-RateLimit-Limit` and `X-RateLimit-Remaining` headers.
14. **Stable-perp funding (`_SFP`):** longs and shorts have separate annual rates. For both, positive means
    that side receives and negative means it pays.

## Without the SDK

- HTTP: `POST https://{market-data|trades}.<domain>/full/v1/<route>`, JSON body, full field names. Use the
  exact path on each reference page: a few calls are `v2` (`bulk_orders`).
- Auth: `POST https://edge.<domain>/auth/api_key/login` → send `Cookie: gravity=...` and
  `X-Grvt-Account-Id` on every trading call and on the WebSocket upgrade.
- WebSocket: JSON-RPC 2.0 on `/ws/full`; `subscribe` with `{stream, selectors, use_global_sequence_number: true}`.
- Signing: EIP-712, domain `{name: "GRVT Exchange", version: "0", chainId}`; testnet 326, production 325.
- Retries: retry reads only on no answer, `1006`, other retryable codes or HTTP 502/503/504. Treat a write
  that timed out after sending, or got a non-4xx status or a 5xx code (`1002`, `1005`), as outcome unknown:
  look it up, never resend it automatically.

## C++ integrations

C++ provides a signing core and tested reference examples, not a client runtime.
Read [the C++ guide](sdks/cpp.md) before choosing dependencies.
The application owns HTTP, WebSocket, login, sessions, event loops, stream state and recovery.
Supply chain ID, metadata, nonce and expiration explicitly. Use the digest API for external keys.
