> For the complete documentation index, see [llms.txt](https://docs.aftermath.finance/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.aftermath.finance/for-developers/api/rest-api/gotchas.md).

# Integration Notes

Integration details and migration notes for the current API.

> Common pitfalls when integrating with the public API at `https://aftermath.finance/docs`.

***

## 1) Account ID vs Account Object ID

* CCXT write endpoints use `accountId` as an account capability object ID (`0x...`).
* CCXT read/stream endpoints use `accountNumber` (number).
* Native Perpetuals account endpoints use a numeric account ID, commonly transported as a mandatory `"123n"` string.

Mixing these is one of the most common integration failures.

***

## 2) Build -> Sign -> Submit Is Mandatory

For CCXT writes:

```
POST /api/ccxt/build/* -> sign signingDigest -> POST /api/ccxt/submit/*
```

Sign the `signingDigest`, not `transactionBytes`.

***

## 3) CCXT `OrderRequest` Is Minimal

Current schema supports:

* `type`: `market | limit`
* `side`: `buy | sell`
* optional `amount`, `price`, `reduceOnly`, `expirationTimestampMs`, `clientOrderId`

Fields such as `timeInForce` and `postOnly` are unsupported by `/api/ccxt/build/createOrders` and may be ignored if sent.

***

## 4) Native History Endpoints Are Cursor-Based

* `/api/perpetuals/account/order-history` paginates with `beforeTimestampCursor`.
* Response includes `nextBeforeTimestampCursor`.

Keep the cursor from each response if you need full history backfill.

***

## 5) Stop-Order Data Requires Signed Auth

`/api/perpetuals/account/stop-order-datas` and `/api/perpetuals/vault/stop-order-datas` require `walletAddress`, `bytes`, `signature`, and one target: `accountId: "...n"` or `vaultId`. Optional `marketIds` narrows the response.

***

## 6) Preview Endpoints Can Return 200 With Error Payload

Some `/api/perpetuals/account/previews/*` and vault preview routes can return:

* HTTP `200`
* body `{ error: string }`
* header `X-Error-Message: true`

Treat preview responses as tagged unions, not always-success payloads.

***

## 7) Ticker Does Not Guarantee Funding-Rate Fields

CCXT ticker includes fields such as `markPrice` and `indexPrice`. Do not rely on explicit funding-rate fields being present in ticker responses.

***

## 8) Coin and Gas Object Concurrency Is Real

Concurrent signed transactions can race on shared Sui objects (USDC coin objects, gas coins) and fail with version/equivocation-style errors.

Serialize critical funding operations and manage gas coins intentionally for parallel submission.

***

## 9) Account State Is Quickly Stale

After any fill/cancel/withdraw/deposit/leverage update, refresh account and position state before computing new risk or order decisions.

***

## 10) Follow Endpoint Wire Formats

Use the public OpenAPI for discovery:

* `https://aftermath.finance/api/openapi/spec.json`

Use the endpoint-specific request and response formats in these guides when serializing BigInt values, preview unions, and pool paths.

***

## 11) Native BigInt Fields Use Exact Strings

Native BigInt fields require `"...n"` request strings and return `"...n"` response strings. Plain numbers and strings without the suffix fail for those inputs. Other timestamps and counters remain JSON numbers, so follow endpoint-specific types.

***

## 12) Deferred Create Flows Change Response Shape

`/api/perpetuals/transactions/create-account` can return deferred PTB argument references when `deferShare = true`.

Do not hardcode the response as `{ txKind }` only if you compose transactions client-side.

***

## 13) No Built-In Dead Man's Switch

The public API does not provide a scheduled cancel or dead-man-switch endpoint.

Implement a heartbeat-driven kill switch that cancels all open orders when the strategy loop stalls or process health checks fail.

***

## 14) CCXT Submit May Require Multiple Signatures

`/api/ccxt/submit/*` accepts `signatures[]`, not a single signature.

When sender and gas owner are different, collect both signatures over the same `signingDigest` before submit.

***

## 15) Migrating From the Pre-v3 API

If your integration predates the v3.0.0 service surface, these renames and removals will break requests that still use the old shapes:

* Candle intervals: `intervalMs` / `interval_ms` (milliseconds) are gone. Native `candle-history` takes `resolution` and CCXT OHLCV takes `timeframe`. See `native.md` for the full enum.
* Candles WebSocket: `GET /api/perpetuals/ws/market-candles/{market_id}/{interval_ms}` no longer exists. Subscribe with `marketCandles` on `/api/perpetuals/ws/updates`.
* Builder codes: `integratorAddress` is replaced by numeric `integratorId`; order-level `builderCode.takerFee` is now `builderCode.integratorFee`; config `maxTakerFee` is now `maxIntegratorFee`. The integrator-vault routes (`integrator-vaults`, `create-integrator-vault`, `claim-integrator-vault-fees`) are removed in favor of one-time integrator registration.
* SL/TP: `stopLossIndexPrice` / `takeProfitIndexPrice` are now `stopLossPrice` / `takeProfitPrice`. Transaction inputs can also include `triggerPriceType`; basic order-history `slTp` does not.
* Rewards: `/api/rewards/points` returns `{ totalPoints }` (float, was `{ points }`); `/api/rewards/history` now requires `bytes` + `signature`.
* Removed response fields: position `makerFee`/`takerFee`; vault `totalCollateral`/`totalCollateralUsd`; market params `gasPriceTwapPeriodMs`, `forceCancelFee`, `gasPriceTakerFee`, `zScoreThreshold`; liquidation `forceCancelFeesUsd`. Price-feed IDs are numeric.
* Ordering: markets sort by symbol; positions sort by market ID; pending bids and asks each sort by order ID; stop-order market groups sort by market ID. Inner stop-order ordering is unspecified.

***

## 16) TypeScript SDK May Lag Native Renames

`sdk-reference.md` describes selected SDK flows, but installed SDK versions can expose different names from raw native HTTP. Verify your package's generated types instead of assuming both surfaces match.

***

## 17) CCXT Streams Use WebSockets

Connect to CCXT stream routes with WebSockets and pass `chId` or `accountNumber` as query parameters. Do not use `EventSource` or GET request bodies for these streams.

## 18) Reusable Auth Is Not Action-Specific JSON

Current service-authenticated routes require base64 bytes that decode exactly to `Aftermath Terms and Conditions`. Sign that message once and reuse the signature. DCA/limit cancellation IDs, referral codes, and history filters are plain request fields. Old SDK helpers that generate `CANCEL_*`, referral action/date, or `SPONSOR_GAS` JSON are stale for this service. See `authentication.md`.

## 19) Gas Budget Units Are MIST

Gas-pool sponsorship and embedded perpetuals sponsor configs accept optional `gasBudget` in SUI MIST. Supplying it asks the service to sign at exactly that budget; omitting it lets the service derive one. Do not send a human-readable SUI amount.

## 20) Address-Balance Gas Is a Separate CCXT Funding Mode

`metadata.gasFromAddressBalance` cannot be combined with `gasCoins`. `fromAddressBalance` and `toAddressBalance` on CCXT deposit/withdraw are also exclusive choices, not additive fallbacks. This mode adds a single-epoch expiration and changes which SUI balance pays embedded oracle fees.

## 21) Summary Routes Return Composite Objects

`POST /api/pools/summary` returns `{ pool, stats }[]`, not `PoolStats[]`. `POST /api/farms/summary` returns `{ farmId, tvl, rewardsTvl }[]`. Both routes cache computed data for about 30 seconds and accept optional ID filters.

## 22) Kebab-Case Normalization Is Enforced

Use `/api/rewards/expected-rewards` and the other hyphenated paths in `endpoint-inventory.md`. A camelCase spelling such as `/api/rewards/expectedRewards` is not a compatibility alias.

## 23) zkLogin Takes a Public Key

`POST /api/zklogin/create` accepts base64 `ephemeralPublicKey`, not an ephemeral private keypair. Keep the private key client-side and preserve the route's downstream 400/401/502/504 status semantics.

## 24) SDK Route Names Are Not Proof of Service Support

The v3.3.1 SDK still contains removed integrator-vault builders and legacy router/DCA/auth methods. Compare the SDK method's literal `fetchApi` path with the current service inventory before shipping an integration; use the raw API when a typed helper is behind the service.

## 25) Gas-Pool Errors Are Actionable

Gas-pool failures are mapped to `2030` (insufficient funds), `2031` (temporarily unavailable), `2032` (authorization), or `2033` (transaction not sponsorable). `2018` is the generic shared-service fallback and `2034` is signature verification. Use the error code and headers to choose between backoff, wallet re-authentication, and rebuilding the transaction.

***

## 26) OpenAPI Descriptions Lag on Builder Codes

The schema descriptions rendered at `https://aftermath.finance/docs` (and in `/api/openapi/spec.json`) still carry two pre-v2 claims about builder codes:

* `integratorFee` is described as applying to "taker volume" only, with the explicit line "The fee is only applied to taker volume (not maker volume)". That is no longer true. The fee follows the order and is charged on maker fills as well as taker fills.
* `integratorId` is described as requiring that the integrator "must have a vault created for the market where the order is being placed". Per-market integrator vaults were removed. One global registration covers every market, and there is no claim step.

The same taker-only wording is repeated on the `builderCode` field of every order-placement, preview, SL/TP, stop-order, and `max-order-size` route, and `maxIntegratorFee` is still called a "maximum taker fee" on the `integrator-config` routes. Treat this page and [builder codes](https://docs.aftermath.finance/perpetuals/architecture/builder-codes-front-end-fee.md) as authoritative until the spec is regenerated.

The deployed Move ABI settles it: in [`AftermathFinance/move-interfaces`](https://github.com/AftermathFinance/move-interfaces), `perpetuals::events::FilledMakerOrder` carries `integrator_id: Option<u32>` and `integrator_fee_paid_usd: u256` alongside `maker_fees`, exactly as `FilledTakerOrder` does. A maker fill can and does pay an integrator fee.

More generally: the OpenAPI spec is the authority on routes, request shapes, and response shapes, but its human-readable descriptions are hand-written and can lag a protocol deployment. When the prose and the protocol disagree, read the Move interface for the event or entry function in question and trust that.

## 27) The OpenAPI Spec Is Not a Complete Route List

A route missing from `/api/openapi/spec.json` is not proof the service does not serve it. `GET /api/router/supported-coins` and `POST /api/router/transactions/trade` both respond in production and neither is declared. See [Undeclared Live Routes](https://docs.aftermath.finance/for-developers/api/rest-api/endpoint-inventory.md#undeclared-live-routes).

To tell a live-but-undeclared route from a genuinely absent one, send the request and compare the status against a control path you know does not exist. A 400 means the route exists and rejected the body; a 404 on both means it does not. Treat an undeclared route as unversioned: its schema is not published, so prefer the declared equivalent where one exists.
